agentix-cli 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +75 -27
  2. package/dist/{agent-RDVGL2TW.js → agent-57MG4LBM.js} +2 -2
  3. package/dist/{audit-Z47AQFFD.js → audit-JU3HWISB.js} +2 -2
  4. package/dist/{board-dashboard-KX2CNOSY.js → board-dashboard-HXDOYGIG.js} +2237 -69
  5. package/dist/board-dashboard-HXDOYGIG.js.map +1 -0
  6. package/dist/chunk-23AUU4S2.js +102 -0
  7. package/dist/chunk-23AUU4S2.js.map +1 -0
  8. package/dist/chunk-4MREHZP5.js +111 -0
  9. package/dist/chunk-4MREHZP5.js.map +1 -0
  10. package/dist/chunk-4YCH6IZV.js +2 -0
  11. package/dist/chunk-6B74TO2J.js +743 -0
  12. package/dist/chunk-6B74TO2J.js.map +1 -0
  13. package/dist/chunk-7GVXCOLO.js +440 -0
  14. package/dist/chunk-7GVXCOLO.js.map +1 -0
  15. package/dist/chunk-7P5QRX5W.js +108 -0
  16. package/dist/chunk-7P5QRX5W.js.map +1 -0
  17. package/dist/chunk-A6BKSZQA.js +3 -0
  18. package/dist/chunk-A6BKSZQA.js.map +1 -0
  19. package/dist/{chunk-6PPIFDOQ.js → chunk-CNNLREHD.js} +67 -22
  20. package/dist/{chunk-6PPIFDOQ.js.map → chunk-CNNLREHD.js.map} +1 -1
  21. package/dist/{chunk-J4WKMKTP.js → chunk-DLVOHCTA.js} +2 -2
  22. package/dist/chunk-E4ZZILAK.js +15 -0
  23. package/dist/chunk-E4ZZILAK.js.map +1 -0
  24. package/dist/{chunk-TRQSP67X.js → chunk-IKBHHTIT.js} +2 -2
  25. package/dist/chunk-JTJIPNXY.js +2 -0
  26. package/dist/chunk-JTJIPNXY.js.map +1 -0
  27. package/dist/chunk-MBOLXKA2.js +6 -0
  28. package/dist/chunk-MBOLXKA2.js.map +1 -0
  29. package/dist/{inbox-O5UB3YQN.js → chunk-MTRWXRFF.js} +69 -4
  30. package/dist/chunk-MTRWXRFF.js.map +1 -0
  31. package/dist/{processes-7W27G3J3.js → chunk-NOF4HSGK.js} +3 -3
  32. package/dist/{processes-7W27G3J3.js.map → chunk-NOF4HSGK.js.map} +1 -1
  33. package/dist/chunk-QW2OYR3N.js +7 -0
  34. package/dist/chunk-QW2OYR3N.js.map +1 -0
  35. package/dist/{chunk-JXEPJ3YD.js → chunk-TC3BSUP7.js} +5 -5
  36. package/dist/chunk-VWTBHLMX.js +1 -0
  37. package/dist/chunk-WFHIIVLL.js +719 -0
  38. package/dist/chunk-WFHIIVLL.js.map +1 -0
  39. package/dist/chunk-WPPUOTY6.js +6 -0
  40. package/dist/chunk-WPPUOTY6.js.map +1 -0
  41. package/dist/cli.js +1 -1
  42. package/dist/cli.js.map +1 -1
  43. package/dist/{compaction-S5H6DTOR.js → compaction-BTUJJ3LJ.js} +4 -4
  44. package/dist/config-QXWKEQON.js +2 -0
  45. package/dist/config-mutator-53XGR2NT.js +2 -0
  46. package/dist/conflict-detector-D7VIYPDI.js +2 -0
  47. package/dist/conflict-detector-D7VIYPDI.js.map +1 -0
  48. package/dist/{context-planner-2RGHJHSO.js → context-planner-I7ID7XF3.js} +3 -3
  49. package/dist/debug-N3B5NVJU.js +2 -0
  50. package/dist/{discover-OATU7SHI.js → discover-XJXQXXIO.js} +2 -2
  51. package/dist/doctor-SEOUFHSL.js +2 -0
  52. package/dist/{editor-chat-FUBQLMAQ.js → editor-chat-RVLCKKB7.js} +2 -2
  53. package/dist/{heal-YP7QI7D3.js → heal-YEQYWX2L.js} +2 -2
  54. package/dist/inbox-BIN2S5XN.js +2 -0
  55. package/dist/index.d.ts +830 -100
  56. package/dist/index.js +2 -2
  57. package/dist/index.js.map +1 -1
  58. package/dist/{ingest-whatsapp-C3O5UPBX.js → ingest-whatsapp-LZE62INA.js} +2 -2
  59. package/dist/loader-5CA3O5GM.js +2 -0
  60. package/dist/loader-6IHUCPVO.js +2 -0
  61. package/dist/memory-extract-KRCHD3OP.js +2 -0
  62. package/dist/migrate-v2-QO7SLKIM.js +4 -0
  63. package/dist/migrate-v2-QO7SLKIM.js.map +1 -0
  64. package/dist/processes-RJ6RDP32.js +2 -0
  65. package/dist/program-WWCXMRU2.js +2 -0
  66. package/dist/{providers-WCQSKTNP.js → providers-WVCMIW67.js} +2 -2
  67. package/dist/query-HZYYRCLU.js +2 -0
  68. package/dist/recipes-EPLE2SNT.js +2 -0
  69. package/dist/registry-HM4ELSXS.js +2 -0
  70. package/dist/rotation-memo-GMTZPMNE.js +13 -0
  71. package/dist/rotation-memo-GMTZPMNE.js.map +1 -0
  72. package/dist/scheduler-XVFIK4XH.js +2 -0
  73. package/dist/{slack-D27BE37Q.js → slack-6P7ZJ32Y.js} +2 -2
  74. package/dist/store-BAPDZHXE.js +2 -0
  75. package/dist/{subagent-EPOT3QDM.js → subagent-WV7QKQ3L.js} +2 -2
  76. package/dist/{task-store-3NUWLYRY.js → task-store-RHISEU6V.js} +2 -2
  77. package/dist/{telegram-UWV67KWG.js → telegram-PIYDRM46.js} +2 -2
  78. package/dist/timers-5LPZN55J.js +2 -0
  79. package/dist/types-VECTMYTO.js +2 -0
  80. package/dist/types-VECTMYTO.js.map +1 -0
  81. package/dist/types-ZRLHHCGB.js +2 -0
  82. package/dist/types-ZRLHHCGB.js.map +1 -0
  83. package/dist/web/activity-graph.global.js +654 -0
  84. package/dist/web/activity-graph.global.js.map +1 -0
  85. package/dist/web/workflow-editor.global.js +1 -1
  86. package/dist/web/workflow-editor.global.js.map +1 -1
  87. package/dist/{whatsapp-KJ2NRKKQ.js → whatsapp-PFRDMUMT.js} +2 -2
  88. package/dist/{whatsapp-state-3ZVQ6MQD.js → whatsapp-state-XMTCSRXU.js} +2 -2
  89. package/dist/wiki-53W5NLZV.js +2 -0
  90. package/dist/wiki-53W5NLZV.js.map +1 -0
  91. package/dist/workspace-setup-FPGN5VNY.js +2 -0
  92. package/dist/workspace-setup-FPGN5VNY.js.map +1 -0
  93. package/package.json +3 -2
  94. package/dist/board-dashboard-KX2CNOSY.js.map +0 -1
  95. package/dist/chunk-34NG7UDX.js +0 -11
  96. package/dist/chunk-34NG7UDX.js.map +0 -1
  97. package/dist/chunk-ASSJ4Z6Z.js +0 -164
  98. package/dist/chunk-ASSJ4Z6Z.js.map +0 -1
  99. package/dist/chunk-BLUXL6HR.js +0 -854
  100. package/dist/chunk-BLUXL6HR.js.map +0 -1
  101. package/dist/chunk-BTAEYL3P.js +0 -72
  102. package/dist/chunk-BTAEYL3P.js.map +0 -1
  103. package/dist/chunk-DSCMCVTV.js +0 -7
  104. package/dist/chunk-DSCMCVTV.js.map +0 -1
  105. package/dist/chunk-HPDHNIA3.js +0 -2
  106. package/dist/chunk-IM376SD6.js +0 -13
  107. package/dist/chunk-IM376SD6.js.map +0 -1
  108. package/dist/chunk-LEIYC3BF.js +0 -104
  109. package/dist/chunk-LEIYC3BF.js.map +0 -1
  110. package/dist/chunk-LY7JGDV7.js +0 -6
  111. package/dist/chunk-LY7JGDV7.js.map +0 -1
  112. package/dist/chunk-U364GNQX.js +0 -719
  113. package/dist/chunk-U364GNQX.js.map +0 -1
  114. package/dist/chunk-WZEYII2S.js +0 -6
  115. package/dist/chunk-WZEYII2S.js.map +0 -1
  116. package/dist/config-UOHEG4BW.js +0 -2
  117. package/dist/config-mutator-KSEBWKJH.js +0 -2
  118. package/dist/debug-TGAP7E7W.js +0 -2
  119. package/dist/inbox-O5UB3YQN.js.map +0 -1
  120. package/dist/loader-BGWA7IRY.js +0 -2
  121. package/dist/loader-LBHKSXBK.js +0 -2
  122. package/dist/memory-extract-KKPKAOPH.js +0 -2
  123. package/dist/program-2MDELQLX.js +0 -2
  124. package/dist/query-FZAL7AQD.js +0 -2
  125. package/dist/recipes-LZ56TA3X.js +0 -2
  126. package/dist/registry-ONJSILH4.js +0 -2
  127. package/dist/scheduler-XRM2RJIV.js +0 -2
  128. package/dist/store-4UCO56K2.js +0 -2
  129. package/dist/timers-QB4KYNAE.js +0 -2
  130. package/dist/types-ECMEC5BZ.js +0 -2
  131. package/dist/types-TTB6DJUE.js +0 -2
  132. package/dist/usage-dashboard-FQGPPABD.js +0 -803
  133. package/dist/usage-dashboard-FQGPPABD.js.map +0 -1
  134. package/dist/wiki-OUYKM7MB.js +0 -2
  135. package/dist/workspace-setup-6GDBEORT.js +0 -2
  136. /package/dist/{agent-RDVGL2TW.js.map → agent-57MG4LBM.js.map} +0 -0
  137. /package/dist/{audit-Z47AQFFD.js.map → audit-JU3HWISB.js.map} +0 -0
  138. /package/dist/{chunk-HPDHNIA3.js.map → chunk-4YCH6IZV.js.map} +0 -0
  139. /package/dist/{chunk-J4WKMKTP.js.map → chunk-DLVOHCTA.js.map} +0 -0
  140. /package/dist/{chunk-TRQSP67X.js.map → chunk-IKBHHTIT.js.map} +0 -0
  141. /package/dist/{chunk-JXEPJ3YD.js.map → chunk-TC3BSUP7.js.map} +0 -0
  142. /package/dist/{config-UOHEG4BW.js.map → chunk-VWTBHLMX.js.map} +0 -0
  143. /package/dist/{compaction-S5H6DTOR.js.map → compaction-BTUJJ3LJ.js.map} +0 -0
  144. /package/dist/{config-mutator-KSEBWKJH.js.map → config-QXWKEQON.js.map} +0 -0
  145. /package/dist/{debug-TGAP7E7W.js.map → config-mutator-53XGR2NT.js.map} +0 -0
  146. /package/dist/{context-planner-2RGHJHSO.js.map → context-planner-I7ID7XF3.js.map} +0 -0
  147. /package/dist/{heal-YP7QI7D3.js.map → debug-N3B5NVJU.js.map} +0 -0
  148. /package/dist/{discover-OATU7SHI.js.map → discover-XJXQXXIO.js.map} +0 -0
  149. /package/dist/{loader-BGWA7IRY.js.map → doctor-SEOUFHSL.js.map} +0 -0
  150. /package/dist/{editor-chat-FUBQLMAQ.js.map → editor-chat-RVLCKKB7.js.map} +0 -0
  151. /package/dist/{loader-LBHKSXBK.js.map → heal-YEQYWX2L.js.map} +0 -0
  152. /package/dist/{memory-extract-KKPKAOPH.js.map → inbox-BIN2S5XN.js.map} +0 -0
  153. /package/dist/{ingest-whatsapp-C3O5UPBX.js.map → ingest-whatsapp-LZE62INA.js.map} +0 -0
  154. /package/dist/{program-2MDELQLX.js.map → loader-5CA3O5GM.js.map} +0 -0
  155. /package/dist/{providers-WCQSKTNP.js.map → loader-6IHUCPVO.js.map} +0 -0
  156. /package/dist/{query-FZAL7AQD.js.map → memory-extract-KRCHD3OP.js.map} +0 -0
  157. /package/dist/{recipes-LZ56TA3X.js.map → processes-RJ6RDP32.js.map} +0 -0
  158. /package/dist/{registry-ONJSILH4.js.map → program-WWCXMRU2.js.map} +0 -0
  159. /package/dist/{scheduler-XRM2RJIV.js.map → providers-WVCMIW67.js.map} +0 -0
  160. /package/dist/{store-4UCO56K2.js.map → query-HZYYRCLU.js.map} +0 -0
  161. /package/dist/{task-store-3NUWLYRY.js.map → recipes-EPLE2SNT.js.map} +0 -0
  162. /package/dist/{timers-QB4KYNAE.js.map → registry-HM4ELSXS.js.map} +0 -0
  163. /package/dist/{types-ECMEC5BZ.js.map → scheduler-XVFIK4XH.js.map} +0 -0
  164. /package/dist/{slack-D27BE37Q.js.map → slack-6P7ZJ32Y.js.map} +0 -0
  165. /package/dist/{types-TTB6DJUE.js.map → store-BAPDZHXE.js.map} +0 -0
  166. /package/dist/{subagent-EPOT3QDM.js.map → subagent-WV7QKQ3L.js.map} +0 -0
  167. /package/dist/{wiki-OUYKM7MB.js.map → task-store-RHISEU6V.js.map} +0 -0
  168. /package/dist/{telegram-UWV67KWG.js.map → telegram-PIYDRM46.js.map} +0 -0
  169. /package/dist/{workspace-setup-6GDBEORT.js.map → timers-5LPZN55J.js.map} +0 -0
  170. /package/dist/{whatsapp-KJ2NRKKQ.js.map → whatsapp-PFRDMUMT.js.map} +0 -0
  171. /package/dist/{whatsapp-state-3ZVQ6MQD.js.map → whatsapp-state-XMTCSRXU.js.map} +0 -0
@@ -1,854 +0,0 @@
1
- import{a as Rn,b as In,e as St}from"./chunk-ASSJ4Z6Z.js";import{a as bn,g as xn,h as Lt,i as Cn,j as jn}from"./chunk-U364GNQX.js";import{a as Sn,b as An,c as xt,d as ct}from"./chunk-IM376SD6.js";import{a as ee,b as q,c as Pe,d as kn}from"./chunk-J4WKMKTP.js";import{d as vn,e as U,f as kt}from"./chunk-LY7JGDV7.js";import{b as fe}from"./chunk-EW27SCCC.js";import{b as at}from"./chunk-LEIYC3BF.js";import{b as _t,d as $n}from"./chunk-WZEYII2S.js";import{a as ve}from"./chunk-VJUTQAPJ.js";import{Command as Nr}from"commander";import{Command as jo}from"commander";import S from"chalk";import{existsSync as Ro,readFileSync as Io}from"fs";var ye=new jo().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");ye.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),d=["dist/cli.js","daemon","start"];e.config&&d.push("-c",e.config),e.port&&d.push("--port",e.port);let p=l("node",d,{detached:!0,stdio:["ignore","ignore","ignore"],cwd:process.cwd()});p.unref();let{writeFileSync:g}=await import("fs");g("/tmp/agentx-daemon.pid",String(p.pid)),console.log(S.green(`Daemon started in background (PID: ${p.pid})`)),console.log(S.dim(" Logs: tail -f /tmp/agentx-daemon.log")),console.log(S.dim(" Stop: agentx daemon stop"));return}let{readFileSync:t,writeFileSync:n,mkdirSync:o,existsSync:s}=await import("fs"),{resolve:r}=await import("path"),i=r(process.cwd(),".agentx");s(i)||o(i,{recursive:!0});let a=r(i,"daemon.pid");if(s(a)){let l=parseInt(t(a,"utf-8").trim(),10);if(l&&l!==process.pid)try{process.kill(l,0),console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0)}catch{}}n(a,String(process.pid));try{Eo(r(process.cwd(),".env"))}catch{}await new Lt(e.config).start()});function Eo(e){if(!Ro(e))return;let t=Io(e,"utf-8");for(let n of t.split(`
2
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s<0)continue;let r=o.slice(0,s).trim();if(!r||process.env[r]!==void 0)continue;let i=o.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),process.env[r]=i}}ye.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:t,unlinkSync:n}=await import("fs"),{resolve:o}=await import("path"),s=[o(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let i of s)if(t(i))try{let a=parseInt(e(i,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{n(i)}catch{}console.log(S.green(`Daemon stopped (PID: ${a})`));return}catch{try{n(i)}catch{}}let{execSync:r}=await import("child_process");try{r("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(S.green("Daemon stopped"))}catch{console.log(S.yellow("No daemon process found"))}});ye.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let t=U(e.config),[n,o]=t.node.bind.split(":"),s=`http://${n||"127.0.0.1"}:${o}/health`,i=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(S.bold(` ${i.node.name}`)+S.dim(` (${i.node.id})`)),console.log(S.green(" Status: running")+S.dim(` \u2014 uptime ${Oo(i.uptime)}`)),console.log(),console.log(S.bold(" Agents:"));for(let c of i.agents){let l=c.active>0?S.yellow(` [${c.active} active]`):"",d=c.errors>0?S.red(` (${c.errors} errors)`):"";console.log(` ${S.cyan(c.name)} ${S.dim(`(${c.tier})`)}${l}${d}`),console.log(S.dim(` ${c.workspace}`))}let a=i.crons.filter(c=>c.enabled);if(i.crons.length){console.log(),console.log(S.bold(` Crons: ${a.length} enabled / ${i.crons.length} total`));for(let c of i.crons){let l=c.enabled?S.green("\u25CF"):S.dim("\u25CB"),d=c.nextRun?S.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${d}`)}}if(i.mesh?.length){console.log(),console.log(S.bold(" Mesh:"));for(let c of i.mesh){let l=c.healthy?S.green("\u25CF"):S.red("\u25CF"),d=c.skills?.length?S.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${S.dim(c.peerUrl)}${d}`)}}console.log()}catch(t){if(t.cause?.code==="ECONNREFUSED"||t.name==="TimeoutError")console.log(S.red(" Daemon is not running")),console.log(S.dim(" Start with: agentx daemon start"));else try{let n=U(e.config),o=kt(n);if(console.log(),console.log(S.bold(` ${n.node.name}`)+S.dim(` (${n.node.id})`)),console.log(S.yellow(" Status: stopped")),console.log(S.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(S.yellow(` \u26A0 ${s}`))}console.log()}catch(n){console.log(S.red(` ${n.message}`))}}});ye.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:t,spawn:n}=await import("child_process"),o="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(o)){console.log(S.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let r=n("tail",["-f","-n",e.lines,o],{stdio:"inherit"});process.on("SIGINT",()=>{r.kill(),process.exit(0)})}else t(`tail -n ${e.lines} ${o}`,{stdio:"inherit"})});ye.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=`http://${(U(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(S.dim(` Connecting to ${o}...`)),console.log(S.dim(` Press Ctrl+C to stop
3
- `));try{let s=await fetch(o);if(!s.ok||!s.body){console.log(S.red(` Failed: ${s.status}`));return}let r=s.body.getReader(),i=new TextDecoder,a="";for(;;){let{done:c,value:l}=await r.read();if(c)break;a+=i.decode(l,{stream:!0});let d=a.split(`
4
- `);a=d.pop()||"";for(let p of d)if(p.startsWith("data: "))try{let g=JSON.parse(p.slice(6)),u=new Date(g.time).toLocaleTimeString(),f=g.message?.replace(/^\[agentx\]\s*/,"")||"";f.includes("executing")?console.log(`${S.dim(u)} ${S.cyan("\u25B6")} ${f}`):f.includes("completed")?console.log(`${S.dim(u)} ${S.green("\u2713")} ${f}`):f.includes("error")||f.includes("Error")?console.log(`${S.dim(u)} ${S.red("\u2717")} ${f}`):f.includes("Routing")?console.log(`${S.dim(u)} ${S.yellow("\u2192")} ${f}`):f.includes("mention")?console.log(`${S.dim(u)} ${S.magenta("@")} ${f}`):f.includes("Skipping")?console.log(`${S.dim(u)} ${S.dim("\u2298")} ${S.dim(f)}`):console.log(`${S.dim(u)} ${f}`)}catch{}else p.startsWith("event: status")}}catch(s){console.log(S.red(` Connection failed: ${s.message}`)),console.log(S.dim(" Is the daemon running? Try: agentx daemon status"))}});ye.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,t,n)=>{let o=t.join(" ");try{let s=U(n.config),[r,i]=s.node.bind.split(":"),a=`http://${r||"127.0.0.1"}:${i}`,c,l;n.peer?(c=`${a}/mesh/task`,l={peer:n.peer,message:o,agent:e}):(c=`${a}/task`,l={agent:e,message:o}),console.log(S.dim(` Sending to ${n.peer?`${n.peer}/${e}`:e}...`));let p=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();n.json?console.log(JSON.stringify(p,null,2)):p.error?console.log(S.red(` Error: ${p.error}`)):(console.log(),console.log(p.content||p.response||"No response"),p.duration&&console.log(S.dim(`
5
- (${(p.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(S.red(` Failed: ${s.message}`)),console.log(S.dim(" Is the daemon running? Try: agentx daemon status"))}});ye.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,t)=>{let{execSync:n}=await import("child_process"),o=t.identity?`-e "ssh -i ${t.identity}"`:"",s=`${t.user}@${e}:${t.path}/dist/`;if(!t.skipChecks){try{console.log(S.dim(" Running tests...")),n("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(S.green(" \u2713 Tests passed"))}catch{console.log(S.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(S.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:r,statSync:i}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!r(c)){console.log(S.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-i(c).mtimeMs>3e5&&(console.log(S.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),n("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(S.green(" \u2713 Build complete")))}console.log(S.dim(` Deploying to ${t.user}@${e}:${t.path}...`));try{if(n(`rsync -avzL --delete ${o} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(S.green(" \u2713 Deploy complete")),t.restart){console.log(S.dim(" Restarting remote daemon..."));let r=t.identity?`ssh -i ${t.identity}`:"ssh";n(`${r} ${t.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${t.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(S.green(" Remote daemon restarted"))}}catch(r){console.log(S.red(` Deploy failed: ${r.message}`))}});ye.action(async e=>{await new Lt(e.config).start()});function Oo(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}import{Command as To}from"commander";import he from"chalk";import{existsSync as lt,readFileSync as Do,writeFileSync as En,mkdirSync as On}from"fs";import{hostname as Tn}from"os";import{resolve as Ke}from"path";var Dn=new To().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),n=Ke(t,"agentx.json"),o=Ke(t,".env"),s=Ke(t,".agentx/sessions");if(console.log(),console.log(he.bold(" agentx init")),console.log(),lt(n)&&!e.force){console.log(he.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let r=[Ke(t,"agentx.example.json"),Ke(t,"node_modules/agentix-cli/agentx.example.json")],i;for(let c of r)if(lt(c)){i=Do(c,"utf-8");break}i||(i=JSON.stringify({node:{id:Tn().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Tn(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:t,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),En(n,i),console.log(he.green(" \u2713 Created agentx.json")),lt(o)||(En(o,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
6
- `)),console.log(he.green(" \u2713 Created .env template"))),lt(s)||(On(s,{recursive:!0}),console.log(he.green(" \u2713 Created .agentx/sessions/")));let a=Ke(t,".claude");lt(a)||(On(a,{recursive:!0}),console.log(he.green(" \u2713 Created .claude/"))),console.log(),console.log(he.bold(" Next steps:")),console.log(` 1. Edit ${he.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${he.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${he.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${he.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Po}from"commander";import dt from"chalk";import{spawn as Nn}from"child_process";import{existsSync as No}from"fs";import{resolve as Wo}from"path";var Wn=new Po().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let t=In(),n=e.port?parseInt(e.port,10):Mo(),o=`http://127.0.0.1:${n}/setup`;if(console.log(),t.configExists?console.log(dt.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(dt.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(dt.bold(` Opening ${o}`)),console.log(),await Lo(o).catch(()=>!1))console.log(dt.dim(" Dashboard is already running.")),e.open!==!1&&Pn(o);else{console.log(dt.dim(` Starting dashboard server on port ${n} (Ctrl-C to quit)\u2026`));let r=_o(),i=Nn(process.execPath,[r,"board","serve","--port",String(n)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Pn(o),await new Promise(a=>i.on("exit",()=>a()))}});function Mo(){try{return U().dashboard.port||4202}catch{return 4202}}function _o(){let e=Wo(__dirname,"cli.js");return No(e)?e:process.argv[1]||e}async function Lo(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function Pn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Nn(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}import{Command as Uo}from"commander";import H from"chalk";var gt=new Uo().name("token").description("scoped API tokens for external access (mesh peers, integrations)");gt.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let t=new St,n=String(e.scope).split(",").map(i=>i.trim()).filter(Boolean),o=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!o||o<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:r}=t.create({name:e.name,scopes:n,expiresInDays:o});console.log(),console.log(H.bold(" Token created.")),console.log(),console.log(` id: ${H.cyan(r.id)}`),console.log(` name: ${r.name}`),console.log(` scopes: ${r.scopes.join(", ")}`),console.log(` expires: ${r.expiresAt||H.dim("never")}`),console.log(),console.log(H.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${H.green.bold(s)}`),console.log(),console.log(H.dim(" Use it via the Authorization header:")),console.log(H.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(H.red(` ${t.message}`)),process.exit(1)}});gt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new St().list();if(e.length===0){console.log(H.dim(`
7
- No tokens issued.
8
- `));return}console.log();for(let t of e){let n=t.revokedAt?H.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?H.red("expired"):H.green("active");console.log(` ${H.cyan(t.id)} ${n} ${t.name}`),console.log(H.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(H.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(H.red(` ${e.message}`)),process.exit(1)}});gt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new St().revoke(e);t||(console.log(H.red(` Token ${e} not found.`)),process.exit(1)),console.log(H.green(`
9
- \u2713 Revoked ${e} (${t.name})
10
- `))}catch(t){console.log(H.red(` ${t.message}`)),process.exit(1)}});import{Command as zo}from"commander";import le from"chalk";import{execFileSync as Ut}from"child_process";import{existsSync as At,readFileSync as Ft,readdirSync as Bo,statSync as Fo}from"fs";import{resolve as Ve}from"path";var Mn=new zo().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async e=>{let t=[];await qo(t);let n=Jo(t);n&&Ho(t,n),n&&Yo(t,n),n&&Go(t,n),n&&Ko(t,n),e.running!==!1&&n&&await Vo(t,n),e.json?process.stdout.write(JSON.stringify({checks:t,summary:Bt(t)},null,2)+`
11
- `):Qo(t);let{errors:o}=Bt(t);process.exit(o>0?1:0)});async function qo(e){let t=Number(process.versions.node.split(".")[0]);e.push({severity:t>=20?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:t>=20?void 0:"AgentX needs Node 20 or newer.",fix:t>=20?void 0:"Install a newer Node (nvm install 20 && nvm use 20)"});let n=r=>{try{return Ut(process.platform==="win32"?"where":"which",[r],{encoding:"utf-8"}).trim().split(`
12
- `)[0]}catch{return null}},o=n("npm");e.push({severity:o?"ok":"fail",group:"Environment",title:o?"npm on PATH":"npm not found",detail:o||void 0});let s=n("claude");if(s){let r;try{r=Ut("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}e.push({severity:"ok",group:"Environment",title:`claude CLI ${r||"installed"}`,detail:s})}else e.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"})}function Jo(e){let t=Ve(process.cwd(),"agentx.json");if(!At(t))return e.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${t}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let n;try{n=JSON.parse(Ft(t,"utf-8"))}catch(s){return e.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:s.message}),null}try{U(t),e.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(n.agents||{}).length} agents, ${Object.keys(n.crons||{}).length} schedules)`})}catch(s){e.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:s.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let o=Object.entries(n.agents||{}).filter(([,s])=>s.tier==="claude-code");return o.length>0&&((()=>{try{return Ut(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||e.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use claude-code tier but claude CLI is missing`,detail:o.map(([r])=>r).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."})),n}function Ho(e,t){let n=new Set;if(zt(t,n),n.size===0){e.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let o=Ve(process.cwd(),".env"),s={};if(At(o))for(let a of Ft(o,"utf-8").split(/\r?\n/)){let c=a.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);c&&(s[c[1]]=c[2])}let r=[],i=[];for(let a of n){let c=process.env[a]??s[a];c===void 0?r.push(a):(!c.trim()||/^["']?\s*["']?$/.test(c))&&i.push(a)}r.length===0&&i.length===0?e.push({severity:"ok",group:"Secrets",title:`${n.size} env reference(s) resolved`}):(r.length>0&&e.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),i.length>0&&e.push({severity:"warn",group:"Secrets",title:`${i.length} env var(s) set but empty`,detail:i.join(", ")}))}function zt(e,t){if(typeof e=="string")for(let n of e.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))t.add(n[1]);else if(Array.isArray(e))for(let n of e)zt(n,t);else if(e&&typeof e=="object")for(let n of Object.values(e))zt(n,t)}function Yo(e,t){let n=[];for(let[o,s]of Object.entries(t.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:Ve(process.cwd(),s.workspace);try{Fo(r).isDirectory()||n.push(`${o}: ${r} (exists but not a directory)`)}catch{n.push(`${o}: ${r}`)}}n.length===0?e.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):e.push({severity:"warn",group:"Workspaces",title:`${n.length} agent workspace(s) missing`,detail:n.join(`
13
- `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function Go(e,t){let n=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,o=[];for(let[s,r]of Object.entries(t.agents||{})){if(!r.workspace)continue;let i=r.workspace.startsWith("/")?r.workspace:Ve(process.cwd(),r.workspace);for(let a of["settings.json","settings.local.json"]){let c=Ve(i,".claude",a);if(!At(c))continue;let l;try{l=JSON.parse(Ft(c,"utf-8"))}catch(u){o.push({severity:"fail",agent:s,msg:`${a}: JSON parse error \u2014 ${u.message}`});continue}let d=l.env||{};for(let[u,f]of Object.entries(d)){if(typeof f!="string")continue;let y=f.match(n);y&&o.push({severity:"fail",agent:s,msg:`${a} env.${u} contains unexpanded ${[...new Set(y)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let p=d.PATH;if(typeof p=="string"){let u=p.split(":").filter(Boolean);u.includes("/usr/bin")||o.push({severity:"fail",agent:s,msg:`${a} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),u.includes("/bin")||o.push({severity:"fail",agent:s,msg:`${a} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let g=l.permissions;if(g&&typeof g=="object"&&"allow"in g){let u=g.allow,f=g.deny;Array.isArray(u)&&u.length===0&&Array.isArray(f)&&f.length>0&&o.push({severity:"warn",agent:s,msg:`${a} permissions.allow is explicitly [] with ${f.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(o.length===0){e.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(t.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of o)e.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function Ko(e,t){let n=t.webhooks??[],o=[],s=Ve(process.cwd(),t.workflows?.dir||".agentx/workflows"),r=new Set;try{if(At(s))for(let d of Bo(s))d.endsWith(".json")&&!d.startsWith("_")&&!d.endsWith(".disabled.json")&&r.add(d.replace(/\.json$/,""))}catch{}let i=new Set(["github","gitlab"]);for(let d of n){if(!d.enabled||!i.has(d.source))continue;!(d.triggers&&Object.keys(d.triggers).length>0)&&!d.defaultWorkflow&&o.push({severity:"warn",title:`webhook "${d.id}" (${d.source} -> ${d.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let d of n)if(!(!d.enabled||!d.triggers)){for(let[p,g]of Object.entries(d.triggers))r.size>0&&!r.has(g)&&o.push({severity:"fail",title:`webhook "${d.id}".triggers["${p}"] -> "${g}" \u2014 no such workflow under ${t.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});d.defaultWorkflow&&r.size>0&&!r.has(d.defaultWorkflow)&&o.push({severity:"fail",title:`webhook "${d.id}".defaultWorkflow -> "${d.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}let a=new Set((t.mesh?.peers??[]).map(d=>d.name));for(let d of n)!d.enabled||!d.node||a.has(d.node)||o.push({severity:"fail",title:`webhook "${d.id}" routes to mesh peer "${d.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let c=new Map;for(let d of n){if(!d.enabled)continue;let p=`${d.source}:${d.agentId}`,g=c.get(p);g?o.push({severity:"warn",title:`webhook entries "${g}" and "${d.id}" both enabled for ${d.source} -> ${d.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):c.set(p,d.id)}let l=new Set(Object.keys(t.agents??{}));for(let d of t.channels?.gitlab?.agentMappings??[])if(d?.agentId){if(d.node){a.has(d.node)||o.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${d.agentId}" routes to mesh peer "${d.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}l.has(d.agentId)||o.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${d.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[d,p]of Object.entries(t.channels?.telegram?.accounts??{}))p.agentBinding?l.has(p.agentBinding)||o.push({severity:"fail",title:`telegram account "${d}".agentBinding -> "${p.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):o.push({severity:"fail",title:`telegram account "${d}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});if(o.length===0){e.push({severity:"ok",group:"Routing",title:`${n.length} webhook(s), ${Object.keys(t.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let d of o)e.push({severity:d.severity,group:"Routing",title:d.title,fix:d.fix})}async function Vo(e,t){let n=t.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",o={};t.dashboard?.token&&(o.Authorization=`Bearer ${t.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),i=await fetch(n+"/health",{headers:o,signal:s.signal});if(clearTimeout(r),!i.ok){e.push({severity:"warn",group:"Runtime",title:`Daemon responded ${i.status}`,detail:n});return}let a=await i.json();e.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${a.agents?.length??0} agents live, uptime ${Math.round((a.uptime??0)/60)}m`,detail:n})}catch{e.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:n,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function Bt(e){return{errors:e.filter(t=>t.severity==="fail").length,warnings:e.filter(t=>t.severity==="warn").length,ok:e.filter(t=>t.severity==="ok").length}}function Qo(e){console.log(),console.log(le.bold(" agentx doctor")),console.log();let t=new Map;for(let o of e)t.has(o.group)||t.set(o.group,[]),t.get(o.group).push(o);for(let[o,s]of t){console.log(le.bold(" "+o));for(let r of s){let i=r.severity==="ok"?le.green("\u2713"):r.severity==="warn"?le.yellow("!"):le.red("\u2717");console.log(` ${i} ${r.title}`),r.detail&&console.log(le.dim(" "+r.detail.replace(/\n/g,`
14
- `))),r.fix&&console.log(le.dim(" \u2192 "+r.fix))}console.log()}let n=Bt(e);n.errors>0?console.log(le.red.bold(` ${n.errors} error${n.errors===1?"":"s"}`)+(n.warnings?le.yellow(`, ${n.warnings} warning${n.warnings===1?"":"s"}`):"")+`. Fix the error${n.errors===1?"":"s"} and rerun.`):n.warnings>0?console.log(le.yellow.bold(` ${n.warnings} warning${n.warnings===1?"":"s"}.`)+le.dim(" Review but not blocking.")):console.log(le.green.bold(` All checks passed (${n.ok}).`)),console.log()}import{Command as ke}from"commander";import h from"chalk";import de from"prompts";import{readFileSync as Re,writeFileSync as Qe,existsSync as z,mkdirSync as we,cpSync as qt,readdirSync as Ht}from"fs";import{resolve as D,join as je}from"path";function Y(){let e=D(process.cwd(),"agentx.json");if(!z(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Re(e,"utf-8"))}function ge(e){return ee(t=>{for(let n of Object.keys(t))delete t[n];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(h.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var pt=new ke().name("agent").description("manage agents \u2014 add, list, remove");pt.command("list").alias("ls").description("list configured agents").action(()=>{let e=Y();console.log();for(let[t,n]of Object.entries(e.agents||{})){let o=n.mentions?.join(", ")||"";console.log(` ${h.cyan(t)} \u2014 ${n.name} (${n.tier})`),console.log(h.dim(` workspace: ${n.workspace}`)),o&&console.log(h.dim(` mentions: ${o}`))}console.log()});pt.command("add").description("add a new agent interactively").action(async()=>{let e=Y(),t=await de([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:D(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let n=t.workspace.endsWith(t.id)?t.workspace:je(t.workspace,t.id);we(D(n,".claude/skills"),{recursive:!0});let o={name:t.name,workspace:n,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-6GDBEORT.js"),r=s(t.id,o,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),i=D(process.cwd(),"src/wiki/SKILL.md"),a=D(__dirname,"../wiki/SKILL.md"),c=z(i)?i:a;z(c)&&(we(D(n,".claude/skills/wiki"),{recursive:!0}),qt(c,D(n,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=o,await ge(e),console.log(h.green(`
15
- Agent "${t.id}" added`)),console.log(h.dim(` Workspace: ${n}`)),console.log(h.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});pt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Y();if(!t.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete t.agents[e],await ge(t),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});var Ct=new ke().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");Ct.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Y();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(h.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${h.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let n=e.channels?.whatsapp;if(n?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${n.defaultAgent||"(none)"}`),console.log(` session: ${n.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of n.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let o=e.channels?.discord;o?.enabled?(console.log(h.bold(" Discord:")),console.log(` agent: ${o.agentBinding||"(none)"}`)):console.log(h.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Ct.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=Y(),t=Object.keys(e.agents||{});if(!t.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let n=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:o}=await de({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 s=await de([{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 i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log(h.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log(h.red(` Invalid token: ${r.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await ge(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(o==="whatsapp"){let s=await de([{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 r=[],i=s.addRoute;for(;i;){let a=await de([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +21624309128)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:n},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await ge(e),we(D(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(o==="discord"){let s=await de([{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;e.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await ge(e),console.log(h.green(` Discord added -> ${s.agentBinding}`))}if(o==="gitlab"){let s=await de([{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 r=[],i=s.addRoute;for(;i;){let a=await de([{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}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await ge(e),console.log(h.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Xe=new ke().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Xe.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Y();console.log();for(let[t,n]of Object.entries(e.crons||{})){let o=n.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${o} ${h.cyan(t)} \u2014 ${n.schedule} (${n.timezone})`),console.log(h.dim(` agent: ${n.agent} | timeout: ${n.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Xe.command("add").description("add a cron job").action(async()=>{let e=Y(),t=Object.keys(e.agents||{}),n=await de([{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}]);!n.id||!n.schedule||(e.crons=e.crons||{},e.crons[n.id]={enabled:n.enabled,schedule:n.schedule,timezone:n.timezone,agent:n.agent,prompt:n.prompt,timeout:n.timeout,onError:["log"]},await ge(e),console.log(h.green(` Cron "${n.id}" added (${n.enabled?"enabled":"disabled"})`)),console.log())});Xe.command("enable <id>").description("enable a cron job").action(async e=>{let t=Y();if(!t.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!0,await ge(t),console.log(h.green(` Cron "${e}" enabled`))});Xe.command("disable <id>").description("disable a cron job").action(async e=>{let t=Y();if(!t.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await ge(t),console.log(h.green(` Cron "${e}" disabled`))});var mt=new ke().name("mesh").description("manage mesh peers \u2014 add, list, remove");mt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Y();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let n=h.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();n=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(t.name)} ${h.dim(t.url)} ${n}`)}}console.log()});mt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Y(),t=await de([{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(h.green(` Connected: ${o.name} (${o.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await ge(e),console.log(h.green(` Peer "${t.name}" added`)),console.log()}});mt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Y();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(n=>n.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await ge(t),console.log(h.green(` Peer "${e}" removed`)))});var Ze=new ke().name("skill").description("manage skills \u2014 add to agent(s), list");Ze.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 n=Y(),o=D(e);if(!z(o)){console.log(h.red(` Skill not found: ${o}`));return}let s=z(je(o,"SKILL.md"))?o.split("/").pop():o.replace(/\/SKILL\.md$/,"").split("/").pop(),r;if(t.all)r=Object.keys(n.agents||{});else if(t.agent)r=t.agent;else{let i=Object.keys(n.agents||{});r=(await de({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(c=>({title:`${c} (${n.agents[c].name})`,value:c}))})).agents||[]}for(let i of r){let a=n.agents[i];if(!a){console.log(h.yellow(` Agent "${i}" not found, skipping`));continue}let c=D(a.workspace,".claude/skills",s);we(c,{recursive:!0}),z(je(o,"SKILL.md"))?qt(o,c,{recursive:!0}):o.endsWith(".md")&&qt(o,je(c,"SKILL.md")),console.log(h.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});Ze.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Y();console.log();for(let[t,n]of Object.entries(e.agents||{})){let o=D(n.workspace,".claude/skills"),s=z(o)?Ht(o).filter(r=>!r.startsWith(".")):[];console.log(` ${h.cyan(t)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ze.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,t)=>{let{createHash:n}=await import("node:crypto"),o=process.cwd(),s=t.source?[t.source]:[D(o,"src",e,"SKILL.md"),D(o,"skills",e,"SKILL.md")],r=s.find(b=>z(b));if(!r){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(h.dim(` ${b}`));return}let i=Re(r,"utf-8"),a=n("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=U()}catch(b){console.log(h.red(` Can't load agentx.json: ${b.message}`));return}let d=Object.entries(l.agents||{}),p=t.agent?d.filter(([b])=>b===t.agent):d;if(p.length===0){console.log(h.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${r}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let g=0,u=0,f=0,y=0;for(let[b,$]of p){let v=$.workspace;if(!v||!z(v)){console.log(` ${h.yellow("\u2717")} ${b.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),y++;continue}let x=D(v,".claude/skills",e),k=D(x,"SKILL.md");if(!z(k)){if(!t.allWorkspaces){console.log(` ${h.dim("\xB7")} ${b.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}t.dryRun||(we(x,{recursive:!0}),Qe(k,i)),console.log(` ${h.green("+")} ${b.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),g++;continue}let j=Re(k,"utf-8");if(n("sha256").update(j).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${b.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),f++;continue}let O=(j.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Qe(k,i),console.log(` ${h.yellow("\u21BB")} ${b.padEnd(22)} ${h.dim(`v${O} \u2192 v${c}`)}`),u++}console.log();let w=t.dryRun?"would":"did";console.log(h.dim(` Summary: ${w} seed ${g}, ${w} update ${u}, ${f} already current, ${y} skipped.`)),t.dryRun&&(g>0||u>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ze.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:t}=await import("./loader-LBHKSXBK.js"),{auditAll:n}=await import("./audit-Z47AQFFD.js"),{loadReferences:o}=await import("./loader-BGWA7IRY.js"),{loadRecipes:s}=await import("./recipes-LZ56TA3X.js"),r=[];if(e.workspace){let u=Y().agents?.[e.workspace];u||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(D(u.workspace))}else if(e.allWorkspaces){let g=Y();for(let u of Object.values(g.agents||{}))u?.workspace&&r.push(D(u.workspace))}else r.push(D(e.cwd));let i=D(e.referencesCwd||e.cwd),c=(await Promise.all(r.map(g=>t(g)))).flat(),[l,d]=await Promise.all([o(i),s(i)]),p=n({skills:c,references:l,recipes:d});if(e.json)console.log(JSON.stringify(p.map(g=>({name:g.name,verdict:g.verdict,reasons:g.reasons,path:g.skill?.path})),null,2));else{let g={PASS:0,REVIEW:0,FAILING:0};for(let u of p)g[u.verdict]++;console.log();for(let u of p){let f=u.verdict==="PASS"?h.green("PASS "):u.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${f} ${h.bold(u.name)}${u.skill?.path?h.dim(` (${u.skill.path})`):""}`);for(let y of u.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${g.PASS} PASS`)} ${h.yellow(`${g.REVIEW} REVIEW`)} ${h.red(`${g.FAILING} FAILING`)}`),console.log()}process.exit(p.some(g=>g.verdict==="FAILING")?1:0)});var ut=new ke().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");ut.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let n=D(t.cwd),o=D(n,"references/example"),s=D(n,"references/recipes/example.yaml");z(o)||(console.log(h.red(` Example template not found at ${o}. Are you running this from the agentx repo root?`)),process.exit(1));let r=D(n,".agentx/references",e),i=D(n,".agentx/references/recipes");we(r,{recursive:!0}),we(i,{recursive:!0});let a=Ht(o).filter(p=>p.endsWith(".yaml")||p.endsWith(".yml")),c=0,l=0;for(let p of a){let g=je(r,p);if(z(g)&&!t.force){console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;continue}let f=Re(je(o,p),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Qe(g,f),console.log(h.green(` + ${g}`)),c++}let d=je(i,`${e}.yaml`);if(z(d)&&!t.force)console.log(h.dim(` skip ${d} (exists; --force to overwrite)`)),l++;else if(z(s)){let p=Re(s,"utf-8").replaceAll("example.",`${e}.`);Qe(d,p),console.log(h.green(` + ${d}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});ut.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.noqta.tn)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:n}=await import("./loader-LBHKSXBK.js"),{discoverFromSkills:o,renderDiscovery:s}=await import("./discover-OATU7SHI.js"),r=D(t.cwd),i=t.from?String(t.from).split(",").map(y=>y.trim()).filter(Boolean):[e],a=await n(r),c=o(a,{namespace:e,filter:i,gitlabHost:t.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${i.join(", ")}] under ${r}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([y,w])=>[y,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let d=s(c,e),p=D(t.referencesCwd||t.cwd),g=D(p,".agentx/references",e);if(!t.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${g}/`));for(let[y,w]of Object.entries(d))console.log(h.cyan(`
16
- --- ${y} ---`)),console.log(w.split(`
17
- `).slice(0,30).map(b=>` ${b}`).join(`
18
- `)),w.split(`
19
- `).length>30&&console.log(h.dim(` \u2026 (${w.split(`
20
- `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${g}/`)),console.log();return}we(g,{recursive:!0});let u=0,f=0;for(let[y,w]of Object.entries(d)){let b=je(g,y);if(z(b)&&!t.force){console.log(h.dim(` skip ${b} (exists; --force to overwrite)`)),f++;continue}Qe(b,w),console.log(h.green(` + ${b}`)),u++}console.log(),console.log(h.dim(` ${u} written, ${f} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});ut.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:t}=await import("./loader-BGWA7IRY.js"),n=await t(D(e.cwd)),o=[...n.byId.values()].sort((s,r)=>s.id.localeCompare(r.id));if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of o){let r=n.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(h.dim(` ${r}`))}console.log(),console.log(h.dim(` ${o.length} reference(s) loaded.`)),console.log()});var Yt=new ke().name("hook").description("manage hooks \u2014 add to agent workspace");Yt.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let n=Y().agents?.[e];if(!n){console.log(h.red(` Agent "${e}" not found`));return}let o=D(n.workspace,".claude/settings.json"),s=z(o)?JSON.parse(Re(o,"utf-8")):{},r=await de([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!r.event||!r.value)return;s.hooks=s.hooks||{},s.hooks[r.event]=s.hooks[r.event]||[];let a={hooks:[{type:r.type,...r.type==="command"?{command:r.value}:{url:r.value}}]};r.matcher&&(a.matcher=r.matcher),s.hooks[r.event].push(a),we(D(n.workspace,".claude"),{recursive:!0}),Qe(o,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Gt=new ke().name("migrate").description("import configuration from OpenClaw or other tools");Gt.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 n=[e,D(process.env.HOME||"",".openclaw/openclaw.json"),D(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),o;for(let u of n)if(u&&z(u)){o=u;break}if(!o){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${o}`));let s=JSON.parse(Re(o,"utf-8")),r=z(D(process.cwd(),"agentx.json"))?Y():{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:[]}},i=s.agents?.list||[],a=s.bindings||[],c={};for(let u of a)u.match?.channel==="telegram"&&(c[u.match.accountId]=u.agentId);i.find(u=>u.id==="main"||u.default)&&(c.default="main");let l=0;for(let u of i){if(u.workspace?.startsWith("/data"))continue;let f=u.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),y=u.groupChat?.mentionPatterns||[];if(y.some(w=>w===f)||y.push(f),r.agents[f]={name:u.name,workspace:u.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:y,maxConcurrent:u.id==="main"?2:1,systemPrompt:`You are ${u.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){we(D(u.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-6GDBEORT.js");w(f,r.agents[f])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let d=s.channels?.telegram?.accounts||{},p=0;for(let[u,f]of Object.entries(d)){if(!f.botToken)continue;let w=c[u]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.channels.telegram.accounts[u]={token:f.botToken,agentBinding:w},r.channels.telegram.enabled=!0,p++}console.log(` ${h.green(p)} Telegram accounts imported`);let g=D(o,"../cron/jobs.json");if(z(g)){let u=JSON.parse(Re(g,"utf-8")),f=0;for(let y of u.jobs||[]){let w=y.name||y.id,b=y.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.crons[w]={enabled:y.enabled||!1,schedule:y.schedule?.expr||"0 9 * * *",timezone:y.schedule?.tz||"UTC",agent:b,prompt:y.payload?.message||"",timeout:y.payload?.timeoutSeconds||600,onError:["log"]},f++}console.log(` ${h.green(f)} cron jobs imported`)}t.dryRun?(console.log(h.yellow(`
21
- Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await ge(r),console.log(h.green(`
22
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ne=new ke().name("config").description("validate and inspect configuration");Ne.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=U(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(h.dim(` Bind: ${t.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(h.dim(` Mesh peers: ${t.mesh.peers.length}`));let n=Object.keys(t.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${t.channels.telegram.enabled?`${n} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(h.dim(` Discord: ${t.channels.discord?.enabled?"enabled":"disabled"}`));let o=kt(t);if(o.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of o)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=z(D(i,".claude")),c=z(D(i,"CLAUDE.md")),l=z(D(i,".claude/settings.json")),d=z(D(i,".claude/skills"))?Ht(D(i,".claude/skills")).filter(g=>!g.startsWith(".")).length:0,p=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${d} skills`];console.log(` ${h.cyan(s)}: ${p.join(" ")}`)}}catch(t){console.log(h.red(` \u2717 ${t.message}`))}console.log()});Ne.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=U(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(h.red(t.message))}});function Xo(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(n=>n.trim()).filter(Boolean):e}function Jt(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ne.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,t)=>{let{readFileSync:n,existsSync:o}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:r}=await import("./config-mutator-KSEBWKJH.js"),{expandEnvVars:i}=await import("./config-UOHEG4BW.js"),a=t.config||s(process.cwd(),"agentx.json");o(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(n(a,"utf-8")),l=t.raw?c:i(c),d=r(l,e);t.json?console.log(JSON.stringify(d)):console.log(Jt(d))});Ne.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,t,n)=>{let{applyConfigMutation:o,setAtPath:s,getAtPath:r}=await import("./config-mutator-KSEBWKJH.js"),i=Xo(t,!!n.string),a=await o(l=>{s(l,e,i)},{configPath:n.config,dryRun:!!n.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=r(a.after,e);n.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${Jt(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Jt(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Ne.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,t)=>{let{applyConfigMutation:n,getAtPath:o,unsetAtPath:s}=await import("./config-mutator-KSEBWKJH.js"),r=await n(a=>{o(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log(h.red(` \u2717 ${r.error}`)),process.exit(1)),o(r.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),r.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});import{Command as Zo}from"commander";import Ie from"chalk";import{resolve as Ee}from"path";import{existsSync as es}from"fs";var xe=new Zo().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function We(e){let t=Ee(e,".agentx/db.sqlite");es(t)||(console.log(Ie.red(` No SQLite at ${t}`)),console.log(Ie.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let n=xn({path:t});return n||(console.log(Ie.red(` Could not open ${t}`)),console.log(Ie.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),n}function Me(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Ie.dim(" (no rows)"));return}let n=Object.keys(e[0]),o=n.map(r=>Math.max(r.length,...e.map(i=>String(i[r]??"").length))),s=r=>r.map((i,a)=>String(i??"").padEnd(o[a])).join(" ");console.log(s(n)),console.log(n.map((r,i)=>"-".repeat(o[i])).join(" "));for(let r of e)console.log(s(n.map(i=>r[i])))}xe.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let t=We(Ee(e.cwd)),n=[],o={};e.agent&&(n.push("agent_id = @agent"),o.agent=e.agent),e.day&&(n.push("started_at LIKE @day"),o.day=`${e.day}%`),e.status&&(n.push("status = @status"),o.status=e.status);let s=`
23
- SELECT agent_id, channel, status, duration_ms,
24
- input_tokens, output_tokens,
25
- substr(message_preview, 1, 60) AS message,
26
- started_at
27
- FROM task_history
28
- ${n.length?"WHERE "+n.join(" AND "):""}
29
- ORDER BY started_at DESC
30
- LIMIT @limit
31
- `,r=t.prepare(s).all({...o,limit:Number(e.limit)});Me(r,!!e.json)});xe.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let t=We(Ee(e.cwd)),n=[],o={};e.agent&&(n.push("agent_id = @agent"),o.agent=e.agent),e.reason&&(n.push("reason = @reason"),o.reason=e.reason);let s=n.length?"WHERE "+n.join(" AND "):"",r=e.summary?`
32
- SELECT agent_id, reason, COUNT(*) AS n,
33
- ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
34
- MAX(last_turn_input_tokens) AS max_input_tokens
35
- FROM rotations
36
- ${s}
37
- GROUP BY agent_id, reason
38
- ORDER BY n DESC
39
- `:`
40
- SELECT agent_id, channel, reason, last_turn_input_tokens, rotated_at
41
- FROM rotations
42
- ${s}
43
- ORDER BY rotated_at DESC
44
- LIMIT @limit
45
- `,i=t.prepare(r).all({...o,limit:Number(e.limit)});Me(i,!!e.json)});xe.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let t=We(Ee(e.cwd)),n=[],o={};e.agent&&(n.push("agent_id = @agent"),o.agent=e.agent),e.day&&(n.push("day = @day"),o.day=e.day);let s=`
46
- SELECT day, agent_id, model, tasks,
47
- input_tokens AS in_tok, output_tokens AS out_tok,
48
- cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
49
- FROM usage_daily
50
- ${n.length?"WHERE "+n.join(" AND "):""}
51
- ORDER BY day DESC, agent_id
52
- `,r=t.prepare(s).all(o);Me(r,!!e.json)});xe.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let t=We(Ee(e.cwd)),n=[],o={};e.channel&&(n.push("channel = @channel"),o.channel=e.channel),e.kind&&(n.push("kind = @kind"),o.kind=e.kind);let s=n.length?"WHERE "+n.join(" AND "):"",r=e.summary?`
53
- SELECT channel, kind, deciding_stage, COUNT(*) AS n
54
- FROM route_traces
55
- ${s}
56
- GROUP BY channel, kind, deciding_stage
57
- ORDER BY n DESC
58
- `:`
59
- SELECT channel, chat_id, kind, deciding_stage, agent_id,
60
- substr(reason, 1, 60) AS reason, at
61
- FROM route_traces
62
- ${s}
63
- ORDER BY at DESC
64
- LIMIT @limit
65
- `,i=t.prepare(r).all({...o,limit:Number(e.limit)});Me(i,!!e.json)});xe.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let t=We(Ee(e.cwd)),n=["status = 'error'"],o={};e.agent&&(n.push("agent_id = @agent"),o.agent=e.agent);let s=`
66
- SELECT agent_id, channel, duration_ms,
67
- substr(error, 1, 120) AS error,
68
- started_at
69
- FROM task_history
70
- WHERE ${n.join(" AND ")}
71
- ORDER BY started_at DESC
72
- LIMIT @limit
73
- `,r=t.prepare(s).all({...o,limit:Number(e.limit)});Me(r,!!e.json)});xe.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let t=We(Ee(e.cwd)),o=t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:t.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Me(o,!!e.json)});xe.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,t)=>{let n=We(Ee(t.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Ie.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Ie.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let o=n.prepare(e).all();Me(o,!!t.json)}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});import{Command as os}from"commander";import N from"chalk";import{existsSync as ss,readFileSync as rs}from"fs";import{resolve as is}from"path";import as from"prompts";import ts from"cronstrue";var Kt={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},jt={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 $e(e){try{return ts.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function ns(e){if(/\b(noon|midday)\b/.test(e))return jt.noon;if(/\bmidnight\b/.test(e))return jt.midnight;let t=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(t){let n=parseInt(t[1],10),o=t[2]?parseInt(t[2],10):0,s=t[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 Vt(e){let t=e.trim().toLowerCase();if(!t)return null;let n;if(n=t.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let p=parseInt(n[1],10);return p<1||p>59?null:{cron:`*/${p} * * * *`,human:$e(`*/${p} * * * *`),matched:n[0]}}if(/\bevery\s+minute\b/.test(t))return{cron:"* * * * *",human:$e("* * * * *"),matched:"every minute"};if(n=t.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let p=parseInt(n[1],10);return p<1||p>23?null:{cron:`0 */${p} * * *`,human:$e(`0 */${p} * * *`),matched:n[0]}}if(/\b(every hour|hourly)\b/.test(t))return{cron:"0 * * * *",human:$e("0 * * * *"),matched:"every hour"};let o=ns(t),s=null;for(let[p,g]of Object.entries(jt))if(!(p==="noon"||p==="midnight")&&new RegExp(`\\b(every\\s+)?${p}s?\\b`).test(t)){s=g;break}let r=o||s,i=t.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(i){let p=i[1],g=1;if(p==="last"||(/^\d+(st|nd|rd|th)?$/.test(p)?g=parseInt(p,10):p==="first"||p==="1st"?g=1:p==="2nd"?g=2:p==="3rd"&&(g=3),g<1||g>31))return null;let u=r||{h:9,m:0},f=`${u.m} ${u.h} ${g} * *`;return{cron:f,human:$e(f),matched:i[0]}}let a=[],c=Object.keys(Kt).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),d=t.match(l);if(d){let p=d[1];for(let g of Object.keys(Kt))if(new RegExp(`\\b${g}s?\\b`).test(p)){let u=Kt[g];a.includes(u)||a.push(u)}}if(a.length){let p=r||{h:9,m:0};a.sort((f,y)=>f-y);let g=a.join(","),u=`${p.m} ${p.h} * * ${g}`;return{cron:u,human:$e(u),matched:`on ${g}`}}if(/\b(weekday|workday|business day)s?\b/.test(t)){let p=r||{h:9,m:0},g=`${p.m} ${p.h} * * 1-5`;return{cron:g,human:$e(g),matched:"weekdays"}}if(/\bweekends?\b/.test(t)){let p=r||{h:9,m:0},g=`${p.m} ${p.h} * * 0,6`;return{cron:g,human:$e(g),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(t)||s){let p=r||{h:9,m:0},g=`${p.m} ${p.h} * * *`;return{cron:g,human:$e(g),matched:s&&Object.entries(jt).find(([,u])=>u===s)?.[0]||"daily"}}if(o){let p=`${o.m} ${o.h} * * *`;return{cron:p,human:$e(p),matched:`at ${o.h}:${String(o.m).padStart(2,"0")}`}}return null}function _n(e,t){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${t}`}function Ln(e){let t=e||is(process.cwd(),"agentx.json");return ss(t)||(console.log(N.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(rs(t,"utf-8"))}function cs(e){return e?e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t==="log"||t==="notify"||t==="disable"):["log"]}async function ls(e,t){if(!e)return;if(e==="me"){let o=t?.notifications?.destination;if(o?.channel&&o?.chatId)return{channel:o.channel,chatId:o.chatId,accountId:o.accountId};console.log(N.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await as([{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||!r?void 0:{channel:s,chatId:r,accountId:i||void 0}}let n=e.split(":");if(n.length>=2)return{channel:n[0],chatId:n[1],accountId:n[2]};console.log(N.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Oe=new os().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Oe.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){Oe.help();return}t.agent||(console.log(N.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(N.red(' --do "<prompt>" is required')),process.exit(1));let n=Vt(e);n||(console.log(N.red(` Couldn't parse: "${e}"`)),console.log(N.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(N.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(N.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let o=Ln(t.config),s=vn(o);o.agents?.[t.agent]||(console.log(N.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(N.dim(` Available: ${Object.keys(o.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=cs(t.onError),i=await ls(t.notify,s);i&&!r.includes("notify")&&r.push("notify");let a=t.id||_n(n.matched,t.agent),c={enabled:!t.disabled,schedule:n.cron,timezone:t.timezone,agent:t.agent,prompt:t.do,timeout:parseInt(t.timeout,10),onError:r};t.model&&(c.model=t.model),i&&(c.notify=i);let l=await ee(p=>q(p,`crons.${a}`,c),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(N.red(` \u2717 ${l.error}`)),process.exit(1));let d=t.dryRun?"would add":"Added";console.log(N.green(` \u2713 ${d} cron ${N.cyan(a)}`)),console.log(N.dim(` Schedule: ${n.cron} (${n.human}, ${t.timezone})`)),console.log(N.dim(` Agent: ${t.agent}`)),i&&console.log(N.dim(` Notify: ${i.channel} ${i.chatId}`)),r.length&&console.log(N.dim(` On error: ${r.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Oe.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=Ln(e.config).crons||{},o=Object.entries(n);if(!o.length){console.log(N.dim(" No scheduled jobs"));return}console.log();for(let[s,r]of o){let i=r.enabled?N.green("\u25CF"):N.dim("\u25CB"),a=r.schedule;try{a=(await import("cronstrue")).default.toString(r.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${i} ${N.cyan(s.padEnd(32))} ${N.dim(r.schedule.padEnd(14))} ${N.dim("\u2192")} ${r.agent}`),console.log(N.dim(` ${a} (${r.timezone||"UTC"})`)),r.notify&&console.log(N.dim(` notify: ${r.notify.channel} ${r.notify.chatId}`))}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Oe.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async n=>{let o=await ee(s=>{if(!Pe(s,`crons.${n}`))throw new Error(`cron "${n}" not found`);q(s,`crons.${n}.enabled`,t)});o.success||(console.log(N.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${n} ${t?"enabled":"disabled"}`)),o.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Oe.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ee(n=>{if(!Pe(n,`crons.${e}`))throw new Error(`cron "${e}" not found`);kn(n,`crons.${e}`)});t.success||(console.log(N.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Oe.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),n=Vt(t);n||(console.log(N.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(N.green(` "${t}"`)),console.log(N.dim(` \u2192 ${n.cron}`)),console.log(N.dim(` \u2192 ${n.human}`))});import{Command as Ns}from"commander";import Le from"chalk";import _ from"chalk";import ht from"prompts";import{readFileSync as ds,writeFileSync as gs,existsSync as ps}from"fs";import{resolve as Un}from"path";var ms=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function us(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Qt(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function zn(e=".env"){let t=Un(e);if(!ps(t))return[];let n=ds(t,"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 r=s.match(ms);r?o.push({kind:"kv",key:r[1],value:us(r[2]),raw:s}):o.push({kind:"comment",raw:s})}return o.length&&o[o.length-1].kind==="blank"&&o.pop(),o}function hs(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Qt(t.value)}`:t.raw).join(`
74
- `)+`
75
- `}function _e(e,t,n=".env"){let o=Un(n),s=zn(o),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Qt(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Qt(t)}`})),gs(o,hs(s))}function Xt(e,t=".env"){return zn(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Bn="https://t.me/BotFather";async function fs(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let n=await t.json();return n?.ok?n.result:null}catch{return null}}async function ys(e,t){let n=Date.now()+t,o=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(o=r.result[0].update_id+1)}catch{}for(;Date.now()<n;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${o}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){o=Math.max(o,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Fn(e={}){console.log(),console.log(_.bold(" Connect Telegram")),console.log(),console.log(_.dim(` 1. Open ${Bn}`)),console.log(_.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(_.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await ht({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:$}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$(v,[Bn],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:n}=await ht({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:$=>/^\d+:[A-Za-z0-9_-]{20,}$/.test($.trim())||"That doesn't look like a Telegram token"});n||(console.log(_.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let o=await fs(n.trim());o||(console.log(_.red("\u2717 invalid or revoked")),process.exit(1)),console.log(_.green(`\u2713 ${o.first_name} (@${o.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(_.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(_.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await ht({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),d||(console.log(_.red(" Aborted")),process.exit(1));let p=c.channels?.telegram?.accounts||{},g=e.account||d;p[g]&&p[g].agentBinding!==d&&(g=(await ht({type:"text",name:"account",message:`Account "${g}" is already in use. Pick a different label:`,initial:`${d}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),g||(console.log(_.red(" Aborted")),process.exit(1));let u=`TG_${g.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;_e(u,n.trim()),process.env[u]=n.trim();let f=await ee($=>{q($,"channels.telegram.enabled",!0),q($,`channels.telegram.accounts.${g}`,{token:`\${${u}}`,agentBinding:d});let v=Pe($,`agents.${d}.mentions`)||[],x=`@${o.username}`;v.includes(x)||(v.push(x),q($,`agents.${d}.mentions`,v))},{configPath:e.configPath});if(f.success||(console.log(_.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(_.green(` \u2713 Bot @${o.username} bound to agent "${d}"`)),console.log(_.dim(` Token stored in .env as ${u}`)),console.log(_.dim(` Mentions updated to include @${o.username}`)),f.reloaded?console.log(_.dim(" Daemon hot-reloaded.")):console.log(_.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await ht({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(_.dim(` Send any message to @${o.username} from the chat you want to use.`)),console.log(_.dim(" Waiting up to 90s..."));let w=await ys(n.trim(),9e4);if(!w){console.log(_.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(_.dim(" agentx config set notifications.destination.channel telegram")),console.log(_.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(_.dim(` agentx config set notifications.destination.accountId ${g}`));return}let b=await ee($=>{q($,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:g})},{configPath:e.configPath});if(!b.success){console.log(_.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(_.green(" \u2713 Default --notify target set")),console.log(_.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(_.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(_.dim(" Daemon hot-reloaded."))}import F from"chalk";import Rt from"prompts";import{spawn as ws}from"child_process";var qn="https://discord.com/developers/applications",$s="67584";async function bs(e){try{let t=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${e}`},signal:AbortSignal.timeout(8e3)});return t.ok?await t.json():null}catch{return null}}function Jn(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ws(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function Hn(e={}){console.log(),console.log(F.bold(" Connect Discord")),console.log(),console.log(F.dim(" 1. Open the Discord Developer Portal")),console.log(F.dim(` ${qn}`)),console.log(F.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(F.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(F.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:t}=await Rt({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});t&&Jn(qn);let{token:n}=await Rt({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(F.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let o=await bs(n.trim());o||(console.log(F.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(F.green(`\u2713 ${s} (bot id ${o.id})`));let{readFileSync:r,existsSync:i}=await import("fs"),{resolve:a}=await import("path"),c=e.configPath||a(process.cwd(),"agentx.json");i(c)||(console.log(F.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let l=JSON.parse(r(c,"utf-8")),d=Object.keys(l.agents||{});d.length===0&&(console.log(F.red(" No agents configured. Run: agentx agent add")),process.exit(1));let p=e.agent;p||(p=(await Rt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(b=>({title:b,value:b})),initial:0})).agent),p||(console.log(F.red(" Aborted")),process.exit(1));let g="DISCORD_BOT_TOKEN";_e(g,n.trim()),process.env[g]=n.trim();let u=await ee(w=>{q(w,"channels.discord.enabled",!0),q(w,"channels.discord.token",`\${${g}}`),q(w,"channels.discord.agentBinding",p)},{configPath:e.configPath});u.success||(console.log(F.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(F.green(` \u2713 Discord bot ${s} bound to agent "${p}"`)),console.log(F.dim(` Token stored in .env as ${g}`)),u.reloaded?console.log(F.dim(" Daemon hot-reloaded.")):console.log(F.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(F.bold(" Install the bot to a server")),console.log();let f=`https://discord.com/oauth2/authorize?client_id=${o.id}&scope=bot&permissions=${$s}`;console.log(` ${F.cyan(f)}`),console.log();let{openInstall:y}=await Rt({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});y&&Jn(f),console.log(),console.log(F.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(F.dim(" Mention the bot in any channel to route messages to the agent."))}import B from"chalk";import Zt from"prompts";import{existsSync as tn,mkdirSync as vs,readdirSync as ks,readFileSync as Yn}from"fs";import{resolve as en}from"path";var xs=".agentx/whatsapp-sessions";function Ss(){let e=en(process.cwd(),".agentx/daemon.pid");if(!tn(e))return!1;try{let t=parseInt(Yn(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function As(e){if(!tn(e))return!1;try{return ks(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Cs(e,t){let n;try{n=await import("@whiskeysockets/baileys")}catch{return t(B.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(B.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:o,useMultiFileAuthState:s}=n.default||n;vs(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await n.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=o({auth:{creds:r.creds,keys:n.makeCacheableSignalKeyStore?n.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(d=>{let g=setTimeout(()=>{t(B.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}d(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){t(B.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:f}=await import("qrcode-terminal");f.generate(u.qr,{small:!0})}catch{t(` QR: ${u.qr}`)}t("")}if(u.connection==="open"){clearTimeout(g),t(B.green(" \u2713 Paired"));try{l.end(void 0)}catch{}d(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(g),t(B.red(" \u2717 Authorization failed \u2014 rescan required")),d(!1))})})}async function Gn(e={}){if(console.log(),console.log(B.bold(" Connect WhatsApp")),console.log(),Ss()){console.log(B.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(B.dim(" agentx daemon stop")),console.log();let{cont:l}=await Zt({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(B.red(" Aborted")),process.exit(1))}let t=e.configPath||en(process.cwd(),"agentx.json");tn(t)||(console.log(B.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let n=JSON.parse(Yn(t,"utf-8")),o=e.sessionDir||n.channels?.whatsapp?.sessionDir||xs,s=en(process.cwd(),o),r=Object.keys(n.agents||{});r.length===0&&(console.log(B.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Zt({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(d=>({title:d,value:d})),initial:0})).agent),i||(console.log(B.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(As(s)&&a){let{keep:l}=await Zt({type:"confirm",name:"keep",message:`An existing session was found at ${o}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(B.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Cs(s,d=>console.log(d))||(console.log(B.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ee(l=>{q(l,"channels.whatsapp.enabled",!0),q(l,"channels.whatsapp.sessionDir",o),q(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(B.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(B.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(B.dim(` Session: ${o}`)),console.log(B.dim(" Start the daemon to begin receiving:")),console.log(B.dim(" agentx daemon start")),console.log(B.dim(" Add routes later with:")),console.log(B.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as js}from"crypto";import J from"chalk";import Kn from"prompts";var It="agentx-mesh:",Et="//join/";function Rs(e){return Buffer.from(e,"utf-8").toString("base64url")}function Is(e){return Buffer.from(e,"base64url").toString("utf-8")}function Es(e){return`${It}${Et}${Rs(JSON.stringify(e))}`}function Os(e){if(!e.startsWith(`${It}${Et}`))throw new Error(`Not a mesh invite link \u2014 expected ${It}${Et}\u2026`);let t=e.slice(It.length+Et.length),n=JSON.parse(Is(t));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 Ts(){return js(32).toString("hex")}function Ds(e){let t=e?.node?.bind||"127.0.0.1:18800",[n,o]=t.split(":");return`http://${n}:${o}`}function Ps(e){return e?.node?.name||e?.node?.id||"node"}async function Vn(e){let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:o}=await import("path"),s=e.configPath||o(process.cwd(),"agentx.json");n(s)||(console.log(J.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Xt("MESH_TOKEN");i||(i=Ts(),_e("MESH_TOKEN",i),console.log(J.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ds(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:p}=await Kn({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:g=>/^https?:\/\//.test(g)||"must start with http:// or https://"});p||(console.log(J.red(" Aborted")),process.exit(1)),a=p}let l=await ee(p=>{q(p,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(J.red(` \u2717 ${l.error}`)),process.exit(1));let d=Es({url:a,token:i,name:Ps(r),version:1});console.log(),console.log(J.bold(" Mesh invite")),console.log(),console.log(` ${J.cyan(d)}`),console.log(),console.log(J.dim(" Run on the other node:")),console.log(J.dim(` agentx connect mesh join "${d}"`)),console.log(),console.log(J.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Qn(e,t={}){let n;try{n=Os(e)}catch(r){console.log(J.red(` \u2717 ${r.message}`)),process.exit(1)}let o=Xt("MESH_TOKEN");if(o&&o!==n.token){let{overwrite:r}=await Kn({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(J.red(" Aborted (keeping existing .env)")),process.exit(1))}_e("MESH_TOKEN",n.token);let s=await ee(r=>{q(r,"mesh.enabled",!0);let i=Pe(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===n.name),c={name:n.name,url:n.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),q(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(J.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(J.green(" \u2713 Joined mesh")),console.log(J.dim(` Peer: ${n.name} @ ${n.url}`)),console.log(J.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(J.dim(" Daemon hot-reloaded.")):console.log(J.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${n.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(J.dim(` Reachable \u2014 ${n.name} exposes ${a} agents`))}else console.log(J.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(J.yellow(` Could not reach ${n.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Ue=new Ns().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Ue.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Fn({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Ue.command("discord").description("pair a Discord bot \u2014 verify token, emit install URL, save to .env").option("--agent <id>","agent to bind the bot to").option("-c, --config <path>","path to agentx.json").action(async e=>{await Hn({agent:e.agent,configPath:e.config})});Ue.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Gn({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Xn=Ue.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Xn.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Vn({url:e.url,configPath:e.config})});Xn.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Qn(e,{configPath:t.config})});Ue.action(()=>{console.log(),console.log(Le.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Le.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Le.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${Le.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Le.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Le.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Le.dim(" GitLab connect is the next slice.")),console.log()});import{Command as Ws}from"commander";import ae from"chalk";var ft=new Ws().name("usage").description("token usage analysis and reporting");ft.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=U(),[t,n]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${n}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ae.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ae.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ae.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ae.red(String(s.totalErrors))}`),console.log(),console.log(ae.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),d=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ae.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ae.dim(d)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ae.red(" Daemon not running. Start with: agentx daemon start")):console.log(ae.red(` ${e.message}`))}});ft.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-FQGPPABD.js");t(parseInt(e.port))});ft.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:n}=await import("fs"),{resolve:o}=await import("path"),s=o(process.cwd(),"scripts/token-report.py");if(!n(s)){console.log(ae.red(` Script not found: ${s}`)),console.log(ae.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ae.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ae.red(" Analysis failed. Is Python 3 installed?"))}});import{Command as Ms}from"commander";import ne from"chalk";var et=new Ms().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");et.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{let t=_s(e.port,e.bind),{startBoardDashboard:n}=await import("./board-dashboard-KX2CNOSY.js");n(t)}catch(t){console.log(ne.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(ne.dim(t.stack)),process.exit(1)}});function _s(e,t){try{let n=U();return e&&(n.dashboard.port=parseInt(e,10)),t&&(n.dashboard.bind=t),n}catch{return console.log(ne.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ne.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
76
- `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}et.command("list").description("list configured boards").action(()=>{try{let e=U();if(!e.boards?.length){console.log(ne.dim(`
77
- No boards configured.
78
- `));return}console.log();for(let t of e.boards){console.log(` ${ne.cyan(t.id)} \u2014 ${t.name}`);let n=t.source;console.log(ne.dim(` source: ${n.type}${n.projects?" ("+n.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(ne.dim(` primary label: ${t.primaryToolLabel}`)),console.log(ne.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(ne.red(` ${e.message}`)),process.exit(1)}});et.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'mtgl/system,mtgl/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{Zn(n=>{if(Array.isArray(n.boards)||(n.boards=[]),n.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let o=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(o.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:o},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),n.boards.push(s),`added board "${e}" (${o.join(", ")})`})}catch(n){console.log(ne.red(` ${n.message}`)),process.exit(1)}});et.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Zn(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let n=t.boards.length;if(t.boards=t.boards.filter(o=>o.id!==e),t.boards.length===n)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(ne.red(` ${t.message}`)),process.exit(1)}});function Zn(e){let{summary:t,backupPath:n}=Rn(o=>e(o));console.log(ne.green(`
79
- \u2713 ${t}
80
- `)),n&&console.log(ne.dim(` Backup: ${n}`)),console.log(ne.dim(` Restart the dashboard to pick up the change if not auto-reloading.
81
- `))}import{Command as Xs}from"commander";import m from"chalk";import{createServer as Ls}from"http";var Ot=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(n=>({url:n.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];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)&&t.push({...s,nodeId:o.nodeId,peerUrl:n.url})}catch{}})),t}async getRemoteArticles(t,n){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,n,o){try{let s=await this.fetchJson(`${t}/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(t){let n=this.cache.get(t);if(n&&Date.now()-n.ts<this.ttl)return n.data;let o=await fetch(t,{signal:AbortSignal.timeout(5e3)});if(!o.ok)throw new Error(`HTTP ${o.status}`);let s=await o.json();return this.cache.set(t,{data:s,ts:Date.now()}),s}};function C(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Us(e){return e.replace(/<!--\s*tags?:[^>]*-->\s*\n?/gi,"")}function eo(e,t){return`<a href="${t?`/agent/${encodeURIComponent(t)}/tag/${encodeURIComponent(e)}`:`/tag/${encodeURIComponent(e)}`}" class="tag">${C(e)}</a>`}function ze(e,t){return(e||[]).map(n=>eo(n,t)).join(" ")}function zs(e,t){if(!e)return;let n=t.get(e);if(n)return n;let o=new Set(t.values());if(o.has(e))return e;let s=e.endsWith(".md")?e:`${e}.md`;if(o.has(s))return s;let r=e.toLowerCase();for(let[i,a]of t)if(i.toLowerCase()===r)return a}function Tt(e,t,n=""){let o=C(Us(e));return o=o.replace(/```(\w*)\n([\s\S]*?)```/g,(s,r,i)=>`<pre><code class="lang-${r}">${i.trim()}</code></pre>`),o=o.replace(/`([^`]+)`/g,"<code>$1</code>"),o=o.replace(/^(\|.+\|)\n(\|[-| :]+\|)\n((?:\|.+\|\n?)*)/gm,(s,r,i,a)=>{let c=r.split("|").filter(d=>d.trim()).map(d=>`<th>${d.trim()}</th>`).join(""),l=a.trim().split(`
82
- `).map(d=>`<tr>${d.split("|").filter(g=>g.trim()).map(g=>`<td>${g.trim()}</td>`).join("")}</tr>`).join("");return`<table><thead><tr>${c}</tr></thead><tbody>${l}</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,r)=>{let[i,a]=r.split("|",2),c=i.trim().replace(/^\//,""),l=(a||i).trim(),d=zs(c,t);return d?`<a href="${n}/article/${encodeURIComponent(d)}" class="wikilink">${l}</a>`:`<a href="${n}/search?q=${encodeURIComponent(c)}" class="wikilink broken" title="Not found \u2014 click to search">${l}</a>`}),o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank">$1</a>'),o=o.replace(/^(>\s?.*(?:\n>\s?.*)*)/gm,s=>`<blockquote>${s.split(`
83
- `).map(i=>i.replace(/^>\s?/,"")).join("<br>")}</blockquote>`),o=o.replace(/^[-*] \[( |x|X)\] (.+)$/gm,(s,r,i)=>`<li class="task">${r.toLowerCase()==="x"?"\u2611":"\u2610"} ${i}</li>`),o=o.replace(/^[-*] (.+)$/gm,"<li>$1</li>"),o=o.replace(/^\d+\. (.+)$/gm,'<li data-ordered="1">$1</li>'),o=o.replace(/(<li data-ordered="1">.*?<\/li>(?:\n?<li data-ordered="1">.*?<\/li>)*)/g,"<ol>$1</ol>"),o=o.replace(/((?:<li(?! data-ordered)[^>]*>.*?<\/li>\n?)+)/g,"<ul>$1</ul>"),o=o.replace(/ data-ordered="1"/g,""),o=o.replace(/^---$/gm,"<hr>"),o=o.replace(/\n\n+/g,"</p><p>"),o=`<p>${o}</p>`,o=o.replace(/<p>\s*(<(?:h[1-6]|ul|ol|blockquote|table|pre|hr)\b[^>]*>[\s\S]*?<\/(?:h[1-6]|ul|ol|blockquote|table|pre)>)\s*<\/p>/g,"$1"),o=o.replace(/<p>\s*<hr>\s*<\/p>/g,"<hr>"),o=o.replace(/<p>\s*<\/p>/g,""),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 Bs=`<link rel="preconnect" href="https://fonts.googleapis.com">
84
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
85
- <link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,300..600;1,6..72,300..600&family=Inter+Tight:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">`,Fs=`
86
- :root {
87
- --bg: #FAF8F3;
88
- --bg-raised: #FFFFFF;
89
- --bg-sunk: #F2EFE7;
90
- --bg-hover: #EFEBE0;
91
- --ink: #1A1915;
92
- --ink-2: #3D3A32;
93
- --muted: #6B6860;
94
- --muted-2: #96918A;
95
- --line: #E4DED0;
96
- --line-2: #D1CAB8;
97
- --accent: oklch(55% 0.14 45);
98
- --accent-soft: oklch(55% 0.14 45 / 0.10);
99
- --accent-hover: oklch(48% 0.14 45);
100
- --cool: oklch(55% 0.08 230);
101
- --cool-soft: oklch(55% 0.08 230 / 0.10);
102
- --ok: oklch(55% 0.10 145);
103
- --warn: oklch(60% 0.14 75);
104
- --err: oklch(55% 0.16 20);
105
- --font-display: 'Newsreader', Georgia, serif;
106
- --font-ui: 'Inter Tight', -apple-system, system-ui, sans-serif;
107
- --font-mono: 'JetBrains Mono', ui-monospace, Menlo, monospace;
108
- --sidebar-w: 260px;
109
- --topbar-h: 52px;
110
- --radius: 6px;
111
- --radius-sm: 4px;
112
- --radius-lg: 10px;
113
- --shadow-sm: 0 1px 2px rgba(26,25,21,0.04), 0 1px 1px rgba(26,25,21,0.03);
114
- --shadow-md: 0 4px 12px rgba(26,25,21,0.06), 0 2px 4px rgba(26,25,21,0.04);
115
- --shadow-lg: 0 12px 40px rgba(26,25,21,0.12), 0 4px 12px rgba(26,25,21,0.06);
116
- }
117
- [data-theme="dark"] {
118
- --bg: #0F0E0C;
119
- --bg-raised: #1A1815;
120
- --bg-sunk: #07060A;
121
- --bg-hover: #22201C;
122
- --ink: #EBE7DD;
123
- --ink-2: #C9C4B7;
124
- --muted: #8B867B;
125
- --muted-2: #5E5A52;
126
- --line: #2A2822;
127
- --line-2: #3A3830;
128
- --accent: oklch(70% 0.16 45);
129
- --accent-soft: oklch(70% 0.16 45 / 0.14);
130
- --accent-hover: oklch(78% 0.16 45);
131
- --cool: oklch(70% 0.10 230);
132
- --cool-soft: oklch(70% 0.10 230 / 0.14);
133
- --ok: oklch(70% 0.14 145);
134
- --warn: oklch(75% 0.16 75);
135
- --err: oklch(68% 0.18 20);
136
- --shadow-sm: 0 1px 2px rgba(0,0,0,0.4);
137
- --shadow-md: 0 4px 12px rgba(0,0,0,0.5);
138
- --shadow-lg: 0 12px 40px rgba(0,0,0,0.7);
139
- }
140
-
141
- * { box-sizing: border-box; margin: 0; padding: 0; }
142
- html, body {
143
- background: var(--bg); color: var(--ink);
144
- font-family: var(--font-ui); font-size: 14px; line-height: 1.55;
145
- font-feature-settings: 'ss01','cv11';
146
- -webkit-font-smoothing: antialiased; min-height: 100vh;
147
- }
148
- a { color: var(--accent); text-decoration: none; }
149
- a:hover { color: var(--accent-hover); }
150
- button { font: inherit; color: inherit; background: none; border: none; cursor: pointer; }
151
- input, textarea, select { font: inherit; color: inherit; }
152
- code, pre, .mono { font-family: var(--font-mono); font-size: 0.92em; }
153
- .display { font-family: var(--font-display); font-weight: 400; letter-spacing: -0.01em; }
154
-
155
- /* \u2014\u2014\u2014 App shell \u2014\u2014\u2014 */
156
- .app {
157
- display: grid;
158
- grid-template-columns: var(--sidebar-w) 1fr;
159
- grid-template-rows: var(--topbar-h) 1fr;
160
- min-height: 100vh;
161
- }
162
- .topbar {
163
- grid-column: 1 / -1;
164
- display: flex; align-items: center; gap: 16px; padding: 0 20px;
165
- background: var(--bg); border-bottom: 1px solid var(--line);
166
- position: sticky; top: 0; z-index: 20; backdrop-filter: blur(8px);
167
- }
168
- .topbar-logo {
169
- display: flex; align-items: center; gap: 10px;
170
- font-family: var(--font-display); font-size: 18px; color: var(--ink);
171
- width: calc(var(--sidebar-w) - 20px); padding-right: 12px;
172
- border-right: 1px solid var(--line); height: 100%;
173
- text-decoration: none;
174
- }
175
- .topbar-logo .mark {
176
- width: 22px; height: 22px; flex: 0 0 auto;
177
- display: inline-flex; align-items: center; justify-content: center;
178
- background: var(--accent); color: var(--bg-raised);
179
- border-radius: 5px; font-family: var(--font-mono);
180
- font-size: 11px; font-weight: 700;
181
- }
182
- .topbar-search {
183
- flex: 1; max-width: 520px;
184
- display: flex; align-items: center; gap: 8px; padding: 6px 12px;
185
- background: var(--bg-raised); border: 1px solid var(--line);
186
- border-radius: var(--radius); color: var(--muted);
187
- transition: border-color 0.15s, background 0.15s;
188
- }
189
- .topbar-search:focus-within { border-color: var(--line-2); background: var(--bg-hover); }
190
- .topbar-search input {
191
- flex: 1; border: 0; outline: 0; background: transparent;
192
- color: var(--ink); font: inherit;
193
- }
194
- .topbar-search input::placeholder { color: var(--muted); }
195
- .topbar-search kbd {
196
- font-family: var(--font-mono); font-size: 11px;
197
- padding: 2px 6px; border: 1px solid var(--line); border-radius: 3px;
198
- background: var(--bg); color: var(--muted);
199
- }
200
- .topbar-tools { margin-left: auto; display: flex; align-items: center; gap: 4px; }
201
- .icon-btn {
202
- width: 32px; height: 32px;
203
- display: inline-flex; align-items: center; justify-content: center;
204
- border-radius: var(--radius-sm); color: var(--muted);
205
- transition: background 0.15s, color 0.15s;
206
- }
207
- .icon-btn:hover { background: var(--bg-hover); color: var(--ink); }
208
- .icon-btn.active { color: var(--accent); background: var(--accent-soft); }
209
- .icon-btn svg { width: 16px; height: 16px; }
210
-
211
- /* \u2014\u2014\u2014 Sidebar \u2014\u2014\u2014 */
212
- .sidebar {
213
- grid-column: 1; grid-row: 2;
214
- background: var(--bg); border-right: 1px solid var(--line);
215
- padding: 16px 12px 40px; overflow-y: auto;
216
- position: sticky; top: var(--topbar-h);
217
- height: calc(100vh - var(--topbar-h));
218
- }
219
- .nav-section { margin-bottom: 20px; }
220
- .nav-section-title {
221
- display: flex; align-items: center; justify-content: space-between;
222
- padding: 4px 10px; font-size: 11px; font-weight: 600;
223
- text-transform: uppercase; letter-spacing: 0.06em;
224
- color: var(--muted); margin-bottom: 2px;
225
- }
226
- .nav-item {
227
- display: flex; align-items: center; gap: 8px;
228
- padding: 5px 10px; color: var(--ink-2);
229
- font-size: 13px; border-radius: var(--radius-sm);
230
- line-height: 1.35; cursor: pointer;
231
- transition: background 0.1s;
232
- text-decoration: none;
233
- }
234
- .nav-item:hover { background: var(--bg-hover); color: var(--ink); }
235
- .nav-item.active {
236
- background: var(--accent-soft); color: var(--accent); font-weight: 500;
237
- }
238
- .nav-item .count {
239
- margin-left: auto; font-family: var(--font-mono);
240
- font-size: 11px; color: var(--muted);
241
- }
242
- .nav-item.active .count { color: var(--accent); }
243
- .nav-agent-header {
244
- display: flex; align-items: center; gap: 8px;
245
- padding: 6px 10px; font-size: 13px; color: var(--ink);
246
- cursor: pointer; border-radius: var(--radius-sm);
247
- text-decoration: none;
248
- }
249
- .nav-agent-header:hover { color: var(--accent); background: var(--bg-hover); }
250
- .nav-agent-header .name { font-weight: 500; }
251
- .nav-agent-header .badge {
252
- margin-left: auto; font-family: var(--font-mono);
253
- font-size: 10.5px; color: var(--muted);
254
- }
255
- .nav-agent-type-label {
256
- padding: 6px 8px 2px; font-size: 10px;
257
- text-transform: uppercase; letter-spacing: 0.08em;
258
- color: var(--muted-2); font-weight: 600;
259
- }
260
- .nav-agent-children {
261
- padding-left: 14px; display: flex; flex-direction: column; gap: 1px;
262
- margin-top: 2px; border-left: 1px dashed var(--line); margin-left: 10px;
263
- }
264
-
265
- /* \u2014\u2014\u2014 Main \u2014\u2014\u2014 */
266
- .main {
267
- grid-column: 2; grid-row: 2;
268
- padding: 32px 48px 80px;
269
- max-width: 1180px; width: 100%;
270
- }
271
- .main.article { max-width: 1100px; }
272
-
273
- /* \u2014\u2014\u2014 Breadcrumb \u2014\u2014\u2014 */
274
- .breadcrumb {
275
- display: flex; align-items: center; gap: 6px;
276
- font-size: 12.5px; color: var(--muted);
277
- margin-bottom: 14px; font-family: var(--font-ui);
278
- }
279
- .breadcrumb a { color: var(--muted); }
280
- .breadcrumb a:hover { color: var(--accent); }
281
- .breadcrumb .sep { color: var(--muted-2); }
282
- .breadcrumb .current { color: var(--ink-2); }
283
-
284
- /* \u2014\u2014\u2014 Display heading \u2014\u2014\u2014 */
285
- .page-head {
286
- display: flex; align-items: flex-end; justify-content: space-between;
287
- gap: 24px; padding-bottom: 16px;
288
- border-bottom: 1px solid var(--line); margin-bottom: 28px;
289
- }
290
- .page-head h1 {
291
- font-family: var(--font-display); font-size: 38px;
292
- font-weight: 400; letter-spacing: -0.015em; line-height: 1.1;
293
- }
294
- .page-head .page-sub {
295
- font-size: 13.5px; color: var(--muted);
296
- margin-top: 6px; max-width: 60ch; line-height: 1.5;
297
- }
298
- .page-head .page-actions { display: flex; gap: 8px; flex: 0 0 auto; }
299
-
300
- /* \u2014\u2014\u2014 Buttons \u2014\u2014\u2014 */
301
- .btn {
302
- display: inline-flex; align-items: center; gap: 6px;
303
- padding: 6px 12px; font-size: 13px;
304
- color: var(--ink-2); background: var(--bg-raised);
305
- border: 1px solid var(--line); border-radius: var(--radius-sm);
306
- transition: all 0.1s; text-decoration: none;
307
- }
308
- .btn:hover { background: var(--bg-hover); border-color: var(--line-2); color: var(--ink); }
309
- .btn.primary { background: var(--ink); color: var(--bg); border-color: var(--ink); }
310
- .btn.primary:hover { background: var(--ink-2); color: var(--bg); }
311
- .btn.ghost { background: transparent; border-color: transparent; }
312
- .btn.ghost:hover { background: var(--bg-hover); }
313
- .btn svg { width: 14px; height: 14px; }
314
-
315
- /* \u2014\u2014\u2014 Stat strip \u2014\u2014\u2014 */
316
- .stats, .stat-strip {
317
- display: grid;
318
- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
319
- gap: 0;
320
- background: var(--bg-raised); border: 1px solid var(--line);
321
- border-radius: var(--radius); overflow: hidden;
322
- margin-bottom: 28px;
323
- }
324
- .stat-card, .stat-cell {
325
- padding: 16px 20px;
326
- border-right: 1px solid var(--line);
327
- display: flex; flex-direction: column; gap: 4px;
328
- background: transparent; text-align: left;
329
- }
330
- .stat-card:last-child, .stat-cell:last-child { border-right: none; }
331
- .stat-card .label, .stat-cell .label {
332
- font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em;
333
- color: var(--muted); font-weight: 600;
334
- }
335
- .stat-card .number, .stat-cell .number {
336
- font-family: var(--font-display); font-size: 32px; font-weight: 400;
337
- line-height: 1; color: var(--ink);
338
- }
339
-
340
- /* \u2014\u2014\u2014 Section heading \u2014\u2014\u2014 */
341
- .section-head, h2.section {
342
- display: flex; align-items: baseline; justify-content: space-between;
343
- margin: 40px 0 14px;
344
- }
345
- .section-head h2 {
346
- font-family: var(--font-display); font-size: 22px;
347
- font-weight: 400; letter-spacing: -0.01em; color: var(--ink);
348
- border: none; padding: 0;
349
- }
350
-
351
- /* \u2014\u2014\u2014 Agent grid (hub home) \u2014\u2014\u2014 */
352
- .agent-grid {
353
- display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
354
- gap: 14px;
355
- }
356
- .agent-card {
357
- background: var(--bg-raised); border: 1px solid var(--line);
358
- border-radius: var(--radius); padding: 18px 20px;
359
- display: flex; flex-direction: column; gap: 12px;
360
- transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s;
361
- }
362
- .agent-card:hover {
363
- border-color: var(--line-2); box-shadow: var(--shadow-md);
364
- transform: translateY(-1px);
365
- }
366
- .agent-card h3 {
367
- font-family: var(--font-display); font-size: 20px; font-weight: 400;
368
- color: var(--ink); margin: 0;
369
- }
370
- .agent-card h3 a { color: inherit; text-decoration: none; }
371
- .agent-card h3 a:hover { color: var(--accent); }
372
- .agent-card .agent-stats {
373
- display: flex; gap: 20px; font-size: 13px; color: var(--muted);
374
- }
375
- .agent-card .agent-stats strong {
376
- color: var(--ink); font-weight: 600; font-family: var(--font-mono);
377
- }
378
- .agent-card .article-list {
379
- display: flex; flex-direction: column; gap: 4px; margin-top: 4px; font-size: 13px;
380
- }
381
- .agent-card .article-row {
382
- display: flex; flex-wrap: wrap; align-items: center; gap: 4px;
383
- padding: 2px 0;
384
- }
385
- .agent-card .article-row .article-title {
386
- color: var(--ink-2); text-decoration: none; margin-left: 4px; flex: 1;
387
- }
388
- .agent-card .article-row .article-title:hover { color: var(--accent); }
389
-
390
- /* \u2014\u2014\u2014 Tags \u2014\u2014\u2014 */
391
- .tag {
392
- display: inline-flex; align-items: center;
393
- font-family: var(--font-mono); font-size: 11.5px;
394
- padding: 1px 7px 2px; background: var(--bg-sunk);
395
- color: var(--ink-2); border-radius: 3px;
396
- line-height: 1.4; cursor: pointer;
397
- transition: background 0.1s, color 0.1s;
398
- text-decoration: none;
399
- }
400
- .tag:hover { background: var(--accent-soft); color: var(--accent); }
401
- .tag.lg { font-size: 12.5px; padding: 3px 10px; }
402
-
403
- /* \u2014\u2014\u2014 Article meta \u2014 inline dl below h1 \u2014\u2014\u2014 */
404
- .meta {
405
- background: var(--bg-raised); border: 1px solid var(--line);
406
- border-radius: var(--radius); padding: 14px 18px;
407
- margin-bottom: 24px; font-size: 13px;
408
- display: grid; grid-template-columns: auto 1fr;
409
- gap: 6px 18px;
410
- }
411
- .meta dt {
412
- font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em;
413
- color: var(--muted); font-weight: 600;
414
- align-self: center;
415
- }
416
- .meta dd { color: var(--ink-2); font-family: var(--font-mono); font-size: 12.5px; }
417
-
418
- /* \u2014\u2014\u2014 Prose body \u2014\u2014\u2014 */
419
- .prose {
420
- font-size: 15.5px; line-height: 1.65; color: var(--ink-2);
421
- max-width: 68ch;
422
- }
423
- .main h1, .prose h1 {
424
- font-family: var(--font-display); font-size: 40px;
425
- font-weight: 400; letter-spacing: -0.015em; line-height: 1.1;
426
- color: var(--ink); margin-bottom: 16px;
427
- border: none; padding: 0;
428
- }
429
- .main h2, .prose h2 {
430
- font-family: var(--font-display); font-size: 26px;
431
- font-weight: 400; letter-spacing: -0.01em;
432
- margin: 36px 0 12px; color: var(--ink);
433
- padding-bottom: 4px; border-bottom: 1px solid var(--line);
434
- }
435
- .main h3, .prose h3 {
436
- font-family: var(--font-display); font-size: 20px; font-weight: 500;
437
- margin: 28px 0 8px; color: var(--ink);
438
- }
439
- .main h4, .prose h4 {
440
- font-size: 15px; font-weight: 600; margin: 20px 0 6px; color: var(--ink);
441
- }
442
- .main p, .prose p { margin: 10px 0; }
443
- .main ul, .prose ul, .main ol, .prose ol { margin: 10px 0 10px 22px; }
444
- .main li, .prose li { margin: 4px 0; }
445
- .main code, .prose code {
446
- background: var(--bg-sunk); padding: 1px 5px; border-radius: 3px;
447
- font-family: var(--font-mono);
448
- }
449
- .main pre, .prose pre {
450
- background: var(--bg-sunk); border: 1px solid var(--line);
451
- border-radius: var(--radius-sm); padding: 14px 16px;
452
- overflow-x: auto; margin: 14px 0; font-size: 13px;
453
- }
454
- .main pre code, .prose pre code { background: none; padding: 0; }
455
- .main blockquote, .prose blockquote {
456
- border-left: 3px solid var(--accent);
457
- padding: 4px 0 4px 14px; color: var(--muted);
458
- font-style: italic; margin: 14px 0;
459
- }
460
-
461
- /* Wikilinks in prose */
462
- .prose a.wikilink, .main a.wikilink {
463
- color: var(--accent);
464
- text-decoration: underline;
465
- text-decoration-color: var(--accent-soft);
466
- text-underline-offset: 3px;
467
- text-decoration-thickness: 1.5px;
468
- }
469
- .prose a.wikilink:hover, .main a.wikilink:hover { text-decoration-color: var(--accent); }
470
- .prose a.wikilink.broken, .main a.wikilink.broken {
471
- color: var(--err); text-decoration-color: var(--err);
472
- text-decoration-style: dashed;
473
- }
474
-
475
- /* \u2014\u2014\u2014 Tables \u2014\u2014\u2014 */
476
- table {
477
- width: 100%; border-collapse: collapse;
478
- margin: 14px 0; font-size: 14px;
479
- }
480
- th, td {
481
- border-bottom: 1px solid var(--line);
482
- padding: 8px 12px; text-align: left;
483
- }
484
- th {
485
- background: var(--bg-sunk); font-weight: 600;
486
- color: var(--ink); font-size: 12.5px;
487
- text-transform: uppercase; letter-spacing: 0.04em;
488
- }
489
- tr:hover td { background: var(--bg-hover); }
490
-
491
- /* \u2014\u2014\u2014 Entry cards \u2014\u2014\u2014 */
492
- .entry-card {
493
- background: var(--bg-raised); border: 1px solid var(--line);
494
- border-radius: var(--radius);
495
- padding: 14px 18px; margin: 10px 0;
496
- transition: border-color 0.15s, box-shadow 0.15s;
497
- }
498
- .entry-card:hover { border-color: var(--line-2); box-shadow: var(--shadow-sm); }
499
- .entry-card .meta-line {
500
- font-size: 11.5px; color: var(--muted);
501
- margin-bottom: 6px; font-family: var(--font-mono);
502
- }
503
- .entry-card h3 {
504
- font-family: var(--font-display); font-size: 19px; font-weight: 400;
505
- color: var(--ink); margin: 4px 0 6px;
506
- border: none; padding: 0;
507
- }
508
- .entry-card h3 a { color: inherit; }
509
- .entry-card h3 a:hover { color: var(--accent); }
510
- .entry-card p {
511
- color: var(--ink-2); font-size: 13.5px;
512
- line-height: 1.55; margin: 4px 0;
513
- }
514
-
515
- /* \u2014\u2014\u2014 Backlinks \u2014\u2014\u2014 */
516
- .backlinks {
517
- margin-top: 40px; padding: 16px 18px;
518
- background: var(--bg-raised); border: 1px solid var(--line);
519
- border-radius: var(--radius);
520
- }
521
- .backlinks h4 {
522
- font-size: 11px; text-transform: uppercase;
523
- letter-spacing: 0.08em; color: var(--muted);
524
- font-weight: 600; margin-bottom: 8px;
525
- }
526
- .backlinks ul { list-style: none; padding: 0; margin: 0; }
527
- .backlinks li { padding: 4px 0; font-size: 13.5px; }
528
-
529
- /* \u2014\u2014\u2014 Health issues list \u2014\u2014\u2014 */
530
- .health-list { display: flex; flex-direction: column; gap: 6px; }
531
- .health-row {
532
- display: grid; grid-template-columns: 96px 1fr 2fr;
533
- gap: 14px; align-items: center;
534
- padding: 10px 14px; background: var(--bg-raised);
535
- border: 1px solid var(--line); border-radius: var(--radius-sm);
536
- font-size: 13px;
537
- }
538
- .health-row .kind {
539
- font-family: var(--font-mono); font-size: 10.5px;
540
- text-transform: uppercase; letter-spacing: 0.06em;
541
- color: var(--muted);
542
- }
543
- .health-row .article { color: var(--ink); font-weight: 500; }
544
- .health-row .msg { color: var(--ink-2); }
545
-
546
- @media (max-width: 900px) {
547
- .app { grid-template-columns: 1fr; }
548
- .topbar-logo { width: auto; border-right: none; }
549
- .sidebar { display: none; }
550
- .main { padding: 20px; grid-column: 1; }
551
- }
552
- `;function G(e,t,n,o=""){return`<!DOCTYPE html>
553
- <html lang="en">
554
- <head>
555
- <meta charset="utf-8">
556
- <meta name="viewport" content="width=device-width, initial-scale=1">
557
- <title>${C(e)} \u2014 AgentX Wiki</title>
558
- ${Bs}
559
- <style>${Fs}</style>
560
- <script>(function(){try{var t=localStorage.getItem('wiki-theme');if(t)document.documentElement.setAttribute('data-theme',t)}catch(e){}})();</script>
561
- </head>
562
- <body>
563
- <div class="app">
564
- <header class="topbar">
565
- <a href="/" class="topbar-logo">
566
- <span class="mark">W</span>
567
- <span class="display">AgentX Wiki</span>
568
- </a>
569
- <form class="topbar-search" action="/search" method="get">
570
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
571
- <input type="search" name="q" placeholder="Search every wiki\u2026" value="${C(o)}" autocomplete="off" />
572
- <kbd>\u2318K</kbd>
573
- </form>
574
- <div class="topbar-tools">
575
- <button class="icon-btn" id="wiki-theme-toggle" title="Toggle theme" aria-label="Toggle theme">
576
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
577
- </button>
578
- </div>
579
- </header>
580
- <nav class="sidebar">${t}</nav>
581
- <main class="main">${n}</main>
582
- </div>
583
- <script>
584
- (function(){
585
- var btn = document.getElementById('wiki-theme-toggle');
586
- if (!btn) return;
587
- btn.addEventListener('click', function(){
588
- var cur = document.documentElement.getAttribute('data-theme') === 'dark' ? '' : 'dark';
589
- if (cur) document.documentElement.setAttribute('data-theme', 'dark');
590
- else document.documentElement.removeAttribute('data-theme');
591
- try { localStorage.setItem('wiki-theme', cur); } catch(e){}
592
- });
593
- // Cmd/Ctrl-K focuses search
594
- document.addEventListener('keydown', function(e){
595
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
596
- e.preventDefault();
597
- var inp = document.querySelector('.topbar-search input');
598
- if (inp) inp.focus();
599
- }
600
- });
601
- })();
602
- </script>
603
- </body>
604
- </html>`}function nn(e){let t=new Map;for(let n of e){let o=n.path.includes("/")?n.path.split("/").slice(0,-1).join("/"):"/",s=t.get(o)||[];s.push(n),t.set(o,s)}return new Map([...t].sort((n,o)=>n[0].localeCompare(o[0])))}function on(e){return e==="/"?"Root":e.split("/").pop().replace(/-/g," ")}function pe(e,t){let n='<div class="nav-section">';n+=`<a class="nav-item${t?"":" active"}" href="/">Home</a>`,n+='<a class="nav-item" href="/entries">All entries</a>',n+="</div>";for(let o of e){let s=`/agent/${encodeURIComponent(o.agentId)}`;n+='<div class="nav-section">',n+=`<a class="nav-agent-header" href="${s}">`,n+=`<span class="name">${C(o.agentId)}</span>`,n+=`<span class="badge">${o.totalArticles}</span>`,n+="</a>",n+='<div class="nav-agent-children">';let r=nn(o.articles);for(let[i,a]of r){n+=`<div class="nav-agent-type-label">${on(i)}</div>`;for(let c of a){let d=`${o.agentId}/${c.path}`===t;n+=`<a class="nav-item${d?" active":""}" href="${s}/article/${encodeURIComponent(c.path)}">${C(c.title)}</a>`}}n+="</div>",n+="</div>"}return n}function qs(e,t,n){let o=t||e.summary(),r=e.getSharedStore().listEntries().length,i=o.reduce((d,p)=>d+p.totalArticles,0),a=o.reduce((d,p)=>d+p.unabsorbed,0),c=new Set((n||[]).map(d=>d.agentId)),l=`<div class="page-head">
605
- <div>
606
- <h1>AgentX Wiki</h1>
607
- <p class="page-sub">Agent-owned institutional knowledge, typed and cross-referenced. Everything here compiles from raw conversation entries through the nightly absorb pass.</p>
608
- </div>
609
- </div>`;if(l+='<div class="stat-strip">',l+=`<div class="stat-cell"><div class="label">Agents</div><div class="number">${o.length}</div></div>`,l+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${i}</div></div>`,l+=`<div class="stat-cell"><div class="label">Raw entries</div><div class="number">${r}</div></div>`,a>0&&(l+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${a}</div></div>`),n&&n.length>0){let d=new Set(n.map(p=>p.nodeId));l+=`<div class="stat-cell"><div class="label">Mesh nodes</div><div class="number">${d.size}</div></div>`}l+="</div>",l+='<div class="section-head"><h2>Agent wikis</h2></div>',l+='<div class="agent-grid">';for(let d of o){let p=d.unabsorbed>0?`<span class="tag" style="color:var(--warn);background:color-mix(in oklch, var(--warn) 12%, transparent)">${d.unabsorbed} unabsorbed</span>`:'<span class="tag" style="color:var(--ok);background:color-mix(in oklch, var(--ok) 12%, transparent)">up to date</span>',u=c.has(d.agentId)&&!e.listAgents().includes(d.agentId)?' <span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote</span>':"";if(l+='<div class="agent-card">',l+=`<h3><a href="/agent/${encodeURIComponent(d.agentId)}">${C(d.agentId)}</a>${u}</h3>`,l+=`<div class="agent-stats">
610
- <span><strong>${d.totalArticles}</strong> articles</span>
611
- <span><strong>${d.totalEntries}</strong> entries</span>
612
- ${p}
613
- </div>`,d.articles.length>0){l+='<div class="article-list">';for(let f of d.articles.slice(0,6)){let y=ze((f.tags||[]).slice(0,2),d.agentId);l+=`<div class="article-row">${y} <a class="article-title" href="/agent/${encodeURIComponent(d.agentId)}/article/${encodeURIComponent(f.path)}">${C(f.title)}</a></div>`}d.articles.length>6&&(l+=`<div class="article-row"><a class="article-title" style="color:var(--muted)" href="/agent/${encodeURIComponent(d.agentId)}">+ ${d.articles.length-6} more \u2192</a></div>`),l+="</div>"}l+="</div>"}return l+="</div>",G("Hub",pe(o),l)}function Js(e,t,n){let o=n||e.summary(),s=o.find(g=>g.agentId===t);if(!s)return G("Not Found",pe(o),"<h1>Agent not found</h1>");let r=s.peerUrl!==void 0,i=e.getAgentEntries(t),a=s.articles||[],c=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">${C(t)}</span></nav>`;if(c+=`<div class="page-head"><div><h1>${C(t)}</h1>`,r&&(c+=`<p class="page-sub"><span class="tag" style="color:var(--cool);background:var(--cool-soft)">remote @ ${C(s.nodeId)}</span></p>`),c+="</div></div>",c+='<div class="stat-strip">',c+=`<div class="stat-cell"><div class="label">Articles</div><div class="number">${s.totalArticles}</div></div>`,c+=`<div class="stat-cell"><div class="label">Entries</div><div class="number">${s.totalEntries}</div></div>`,c+=`<div class="stat-cell"><div class="label">Unabsorbed</div><div class="number">${s.unabsorbed}</div></div>`,c+="</div>",a.length>0){c+='<div class="section-head"><h2>Articles</h2><span class="mono" style="font-size:12px;color:var(--muted)">'+a.length+" total</span></div>";let g=nn(a);for(let[u,f]of g){c+=`<h3 class="display" style="font-size:17px;color:var(--muted);font-weight:500;margin:20px 0 8px">${on(u)}</h3>`,c+='<div class="agent-card" style="padding:4px 14px"><div class="article-list">';for(let y of f)c+=`<div class="article-row">${ze((y.tags||[]).slice(0,3),t)} <a class="article-title" href="/agent/${encodeURIComponent(t)}/article/${encodeURIComponent(y.path)}">${C(y.title)}</a></div>`;c+="</div></div>"}}let l=i.slice(-5).reverse();if(l.length>0){c+='<div class="section-head"><h2>Recent entries</h2><a class="btn ghost" href="/entries">See all \u2192</a></div>';for(let g of l)c+=`<div class="entry-card">
614
- <div class="meta-line">${g.date} \xB7 via ${C(g.source)} \xB7 <code>${C(g.id)}</code></div>
615
- <p>${C(g.content.slice(0,300))}${g.content.length>300?"\u2026":""}</p>
616
- </div>`}let p=e.getAgentWiki(t).lint();if(p.length>0){c+=`<div class="section-head"><h2>Health issues</h2><span class="mono" style="font-size:12px;color:var(--warn)">${p.length}</span></div>`,c+='<div class="health-list">';for(let g of p)c+=`<div class="health-row">
617
- <span class="kind">${C(g.type)}</span>
618
- <span class="article">${C(g.article)}</span>
619
- <span class="msg">${C(g.message)}</span>
620
- </div>`;c+="</div>"}return G(t,pe(o,t),c)}function Hs(e,t,n,o){let s=e.getAgentWiki(t),r=s.readArticle(n);if(!r)return null;let i=o||e.summary(),a=s.rebuildIndex(),c=new Map;for(let u of a.articles)c.set(u.title,u.path);let l=`/agent/${encodeURIComponent(t)}`,p=s.buildBacklinks()[r.meta.title]||[],g=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${l}">${C(t)}</a> <span class="sep">/</span> <span class="current">${C(r.meta.title)}</span></nav>`;if(g+=`<article class="prose"><h1>${C(r.meta.title)}</h1>`,g+='<dl class="meta">',r.meta.type&&(g+=`<dt>Type</dt><dd>${eo(r.meta.type,t)}</dd>`),r.meta.tags?.length&&(g+=`<dt>Tags</dt><dd>${ze(r.meta.tags,t)}</dd>`),r.meta.owner&&(g+=`<dt>Owner</dt><dd>${C(r.meta.owner)}</dd>`),g+=`<dt>Created</dt><dd>${C(r.meta.created||"\u2014")}</dd>`,g+=`<dt>Updated</dt><dd>${C(r.meta.lastUpdated||"\u2014")}</dd>`,r.meta.sources?.length&&(g+=`<dt>Sources</dt><dd>${r.meta.sources.length} entries</dd>`),g+="</dl>",g+=Tt(r.content,c,l),p.length>0){g+='<div class="backlinks"><h4>Pages that link here</h4><ul>';for(let u of p){let f=s.readArticle(u);g+=`<li><a href="${l}/article/${encodeURIComponent(u)}">${C(f?.meta.title||u)}</a></li>`}g+="</ul></div>"}return g+="</article>",G(r.meta.title,pe(i,`${t}/${n}`),g)}function Ys(e,t){let n=t||e.summary(),s=e.getSharedStore().listEntries(),r='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Entries</span></nav>';r+='<div class="page-head"><div><h1>All raw entries</h1><p class="page-sub">Every conversation line that the ingest pipeline captured. Absorb compiles these into typed articles nightly.</p></div></div>';let i=new Map;for(let a of s){let c=i.get(a.date)||[];c.push(a),i.set(a.date,c)}for(let[a,c]of[...i].reverse()){r+=`<div class="section-head"><h2>${a}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${c.length} entries</span></div>`;for(let l of c)r+=`<div class="entry-card">
621
- <div class="meta-line">
622
- <a href="/agent/${encodeURIComponent(l.agentId)}">${C(l.agentId)}</a>
623
- \xB7 via ${C(l.source)} \xB7 <code>${C(l.id)}</code>
624
- </div>
625
- <p>${C(l.content.slice(0,400))}${l.content.length>400?"\u2026":""}</p>
626
- </div>`}return G("All Entries",pe(n),r)}function Gs(e,t,n){let o=n||e.summary(),s='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Search</span></nav>';s+=`<div class="page-head"><div><h1>\u201C${C(t)}\u201D</h1><p class="page-sub">Full-text search across every agent's wiki.</p></div></div>`;let r=0,i=[];for(let a of o){let l=e.getAgentWiki(a.agentId).findRelevant(t,void 0,10);if(l.length>0){i.push(`<div class="section-head"><h2>${C(a.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${l.length} match${l.length===1?"":"es"}</span></div>`);for(let d of l){let p=`/agent/${encodeURIComponent(a.agentId)}`;i.push(`<div class="entry-card">
627
- <div class="meta-line">${ze((d.meta.tags||[]).slice(0,3),a.agentId)}</div>
628
- <h3><a href="${p}/article/${encodeURIComponent(d.path)}">${C(d.meta.title)}</a></h3>
629
- <p>${C(d.content.slice(0,240))}\u2026</p>
630
- </div>`)}r+=l.length}}return s+=i.join(""),r===0&&(s+='<p style="color:var(--muted);margin-top:24px">No matching articles found.</p>'),G(`Search: ${t}`,pe(o),s,t)}function Ks(e,t,n){let o=n||e.summary(),s='<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <span class="current">Tag</span></nav>';s+=`<div class="page-head"><div><h1>${C(t)}</h1><p class="page-sub">All articles tagged <span class="tag">${C(t)}</span>, across every agent.</p></div></div>`;let r=0;for(let i of o){let a;try{a=e.getAgentWiki(i.agentId)}catch{continue}let c=a.findByTags([t],void 0,100);if(c.length!==0){s+=`<div class="section-head"><h2>${C(i.agentId)}</h2><span class="mono" style="font-size:12px;color:var(--muted)">${c.length}</span></div>`;for(let l of c){let d=`/agent/${encodeURIComponent(i.agentId)}`;s+=`<div class="entry-card">
631
- <div class="meta-line">${ze((l.meta.tags||[]).slice(0,6),i.agentId)}</div>
632
- <h3><a href="${d}/article/${encodeURIComponent(l.path)}">${C(l.meta.title)}</a></h3>
633
- </div>`}r+=c.length}}return r===0&&(s+=`<p style="color:var(--muted);margin-top:24px">No articles tagged <code>${C(t)}</code>.</p>`),G(`Tag: ${t}`,pe(o),s)}function Vs(e,t,n,o){let s=o||e.summary(),r;try{r=e.getAgentWiki(t)}catch{return G(`Tag: ${n}`,pe(s),`<h1>Agent not found: ${C(t)}</h1>`)}let i=r.findByTags([n],void 0,100),a=`/agent/${encodeURIComponent(t)}`,c=`<nav class="breadcrumb"><a href="/">Hub</a> <span class="sep">/</span> <a href="${a}">${C(t)}</a> <span class="sep">/</span> <span class="current">${C(n)}</span></nav>`;c+=`<div class="page-head"><div><h1>${C(n)}</h1><p class="page-sub">${i.length} article${i.length===1?"":"s"} tagged <code>${C(n)}</code> in <b>${C(t)}</b>.</p></div></div>`;for(let l of i)c+=`<div class="entry-card">
634
- <div class="meta-line">${ze((l.meta.tags||[]).slice(0,6),t)}</div>
635
- <h3><a href="${a}/article/${encodeURIComponent(l.path)}">${C(l.meta.title)}</a></h3>
636
- </div>`;return G(`${t} \xB7 ${n}`,pe(s),c)}function tt(e,t,n){let o=e.rebuildIndex(),s=nn(o.articles.map(i=>({title:i.title,path:i.path,tags:i.tags}))),r='<div class="nav-section">';r+=`<div class="nav-section-title">${C(t)}</div>`,r+=`<a class="nav-item${n?"":" active"}" href="/">Home</a>`,r+='<a class="nav-item" href="/lint">Health check</a>',r+="</div>";for(let[i,a]of s){r+='<div class="nav-section">',r+=`<div class="nav-section-title">${on(i)}</div>`;for(let c of a){let l=c.path===n;r+=`<a class="nav-item${l?" active":""}" href="/article/${encodeURIComponent(c.path)}">${C(c.title)}</a>`}r+="</div>"}return r}function to(e,t=4200,n,o=[],s="graph"){let r=new at(e,void 0,s),i=o.length>0?new Ot(o):null;Ls(async(c,l)=>{let d=new URL(c.url||"/",`http://localhost:${t}`),p=decodeURIComponent(d.pathname),g=null,u=200;try{if(p.startsWith("/remote/")&&i){let f=p.slice(8).split("/article/");if(f.length===2){let[y,w]=f,b=y.indexOf("/"),$=decodeURIComponent(y.slice(0,b)),v=y.slice(b+1),x=await i.getRemoteArticle($,v,w);if(x){let k=await i.getRemoteAgents(),j=[...r.summary(),...k.map(I=>({...I,agentId:`${I.agentId} @${I.nodeId}`}))],A=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${C(v)} @ ${C($)}</div>`;A+=`<h1>${C(x.meta.title)}</h1>`,A+='<dl class="meta">',A+=`<dt>Tags</dt><dd>${(x.meta.tags||[]).map(I=>`<span class="tag">${I}</span>`).join(" ")}</dd>`,A+=`<dt>Owner</dt><dd>${C(x.meta.owner)}</dd>`,A+=`<dt>Source</dt><dd><span class="tag">remote</span> ${C($)}</dd>`,A+=`<dt>Updated</dt><dd>${x.meta.lastUpdated}</dd>`,A+="</dl>";let O=new Map;A+=Tt(x.content,O),g=G(x.meta.title,pe(j),A)}}}if(!g&&n){let f=r.getAgentWiki(n);if(p==="/"||p===""){let y=f.rebuildIndex(),w=r.getAgentEntries(n),b=`<h1>${C(n)}</h1>`;if(b+='<div class="stats">',b+=`<div class="stat-card"><div class="number">${y.articles.length}</div><div class="label">Articles</div></div>`,b+=`<div class="stat-card"><div class="number">${w.length}</div><div class="label">Entries</div></div>`,b+="</div>",y.articles.length>0){b+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let $ of y.articles)b+=`<tr><td><a href="/article/${encodeURIComponent($.path)}">${C($.title)}</a></td><td><span class="tag">${($.tags||[]).slice(0,3).join(", ")}</span></td><td>${$.lastUpdated||""}</td></tr>`;b+="</table>"}g=G(n,tt(f,n),b)}else if(p.startsWith("/article/")){let y=p.slice(9),w=f.readArticle(y);if(w){let b=f.rebuildIndex(),$=new Map;for(let x of b.articles)$.set(x.title,x.path);let v=`<h1>${C(w.meta.title)}</h1>`;v+='<dl class="meta">',v+=`<dt>Tags</dt><dd>${(w.meta.tags||[]).map(x=>`<span class="tag">${x}</span>`).join(" ")}</dd>`,v+=`<dt>Updated</dt><dd>${w.meta.lastUpdated}</dd>`,w.meta.sources?.length&&(v+=`<dt>Sources</dt><dd>${w.meta.sources.length} entries</dd>`),v+="</dl>",v+=Tt(w.content,$),g=G(w.meta.title,tt(f,n,y),v)}}else if(p==="/lint"){let y=f.lint(),w="<h1>Health Check</h1>";if(y.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 b of y)w+=`<tr><td><span class="tag">${b.type}</span></td><td>${C(b.article)}</td><td>${C(b.message)}</td></tr>`;w+="</table>"}g=G("Health Check",tt(f,n),w)}else if(p==="/search"){let y=d.searchParams.get("q")||"",w=f.findRelevant(y,void 0,20),b=`<h1>Search: "${C(y)}"</h1>`;for(let $ of w)b+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${C($.meta.title)}</a></h3><p>${C($.content.slice(0,200))}...</p></div>`;w.length===0&&(b+="<p>No results.</p>"),g=G(`Search: ${y}`,tt(f,n),b)}else if(p.startsWith("/tag/")){let y=decodeURIComponent(p.slice(5)),w=f.findByTags([y],void 0,100),b=`<h1>Tag: <a class="tag" href="#">${C(y)}</a></h1>`;b+=`<p>${w.length} article${w.length===1?"":"s"} tagged <code>${C(y)}</code></p>`;for(let $ of w)b+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent($.path)}">${C($.meta.title)}</a></h3><div class="meta-line">${ze(($.meta.tags||[]).slice(0,6))}</div></div>`;w.length===0&&(b+="<p>No articles with this tag.</p>"),g=G(`Tag: ${y}`,tt(f,n),b)}}else{let f=i?await i.getRemoteAgents():[],y=r.summary(),w=new Map(y.map(v=>[v.agentId,v])),b=[],$=new Set;for(let v of y){let x=f.find(k=>k.agentId===v.agentId);x&&x.totalArticles>v.totalArticles?b.push({...x,totalEntries:Math.max(v.totalEntries,x.totalEntries),unabsorbed:Math.max(v.unabsorbed,x.unabsorbed)}):b.push(v),$.add(v.agentId)}for(let v of f)$.has(v.agentId)||(b.push(v),$.add(v.agentId));if(p==="/"||p==="")g=qs(r,b,f);else if(p==="/entries")g=Ys(r,b);else if(p==="/search")g=Gs(r,d.searchParams.get("q")||"",b);else if(p.startsWith("/tag/"))g=Ks(r,decodeURIComponent(p.slice(5)),b);else if(p.match(/^\/agent\/[^/]+\/tag\/.+/)){let v=p.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);g=Vs(r,decodeURIComponent(v[1]),decodeURIComponent(v[2]),b)}else if(p.startsWith("/agent/")){let v=p.slice(7),x=v.indexOf("/article/");if(x===-1)g=Js(r,v,b);else{let k=v.slice(0,x),j=v.slice(x+9);if(g=Hs(r,k,j,b),!g&&i){let A=f.find(O=>O.agentId===k);if(A){let O=await i.getRemoteArticle(A.peerUrl,k,j);if(O){let I=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${C(A.nodeId)}</span> / ${C(k)}</div>`;I+=`<h1>${C(O.meta.title)}</h1>`,I+='<dl class="meta">',I+=`<dt>Tags</dt><dd>${(O.meta.tags||[]).map(P=>`<span class="tag">${P}</span>`).join(" ")}</dd>`,I+=`<dt>Source</dt><dd><span class="tag">remote</span> ${C(A.nodeId)}</dd>`,I+=`<dt>Updated</dt><dd>${O.meta.lastUpdated}</dd>`,I+="</dl>",I+=Tt(O.content,new Map),g=G(O.meta.title,pe(b),I)}}}}}}if(!g){u=404;let f=n?tt(r.getAgentWiki(n),n):pe(r.summary());g=G("Not Found",f,"<h1>Page not found</h1>")}}catch(f){u=500,g=G("Error","",`<h1>Error</h1><pre>${C(f.message)}</pre>`)}l.writeHead(u,{"Content-Type":"text/html; charset=utf-8"}),l.end(g)}).listen(t)}function no(e,t,n,o,s,r){return Qs(t,n,o,s,r)}function Qs(e,t,n,o,s){let r=t?`
637
- ## Worldview
638
-
639
- ${t}
640
- `:"",i=new Map;for(let c of n){let l=c.type||"untyped",d=i.get(l)||[];d.push(c),i.set(l,d)}let a=n.length===0?"":`
641
- ## Existing Articles (the current catalog)
642
-
643
- `+Array.from(i.entries()).sort().map(([c,l])=>`**${c}**
644
- `+l.sort((d,p)=>d.title.localeCompare(p.title)).map(d=>`- [[${d.title}]] \u2014 ${d.path}`).join(`
645
- `)).join(`
646
-
647
- `)+`
648
- `;return`You are compiling a personal wiki for the "${e}" agent in the Karpathy / Farzapedia pattern.
649
-
650
- ## The Pattern (read this first \u2014 it shapes every decision below)
651
-
652
- The wiki is a compounding knowledge base of interlinked markdown articles that a future LLM will read by walking the graph, NOT by bag-of-words search. Your job is to produce articles that another agent can navigate via \`type\` + wikilinks. If the wikilinks don't form a coherent graph, the wiki is useless regardless of how many tags you add.
653
-
654
- **Three rules, in priority order:**
655
-
656
- 1. **\`type\` is the organizational spine.** Every article has exactly one of: \`person | project | place | concept | event | decision | pattern\`. Choose the type BEFORE writing; if you can't pick one, the article probably isn't needed.
657
- 2. **\`related\` is the navigation surface.** Every article cross-references 2\u20135 other articles via \`[[Article Title]]\` wikilinks in the body AND lists them in the \`related\` frontmatter field. Links the reader could follow to learn more.
658
- 3. **Tags are a secondary hint, not a retrieval spine.** 2\u20134 specific tags max. Do NOT tag aggressively. Do NOT tag with dates unless the article is an \`event\`. Do NOT tag with generic terms ("deploy", "work") that will match half the corpus.
659
-
660
- ## Path convention
661
-
662
- Path reflects type: \`<type>s/<slug>.md\` where slug is a kebab-case title.
663
-
664
- - People: \`people/anis-marrouchi.md\`
665
- - Projects: \`projects/mtgl-system-v2.md\`
666
- - Concepts: \`concepts/staging-deployment.md\`
667
- - Events: \`events/YYYY-MM-DD-<slug>.md\` (date in path)
668
- - Decisions: \`decisions/<slug>.md\`
669
- - Patterns: \`patterns/<slug>.md\`
670
- - Places: \`places/<slug>.md\`
671
-
672
- ## How to process entries
673
-
674
- For each of the ${s} raw entries below, ask in this order:
675
-
676
- 1. **Does it extend an existing article?** If a person/project/concept mentioned in the entry already has an article in the catalog, produce an UPDATE with the full merged content. Prefer merging over proliferating.
677
- 2. **Does it deserve a new article?** Only if the subject is a persistent entity (a person, a project, a recurring concept, a specific event/decision) that future queries will need to find. Not every conversation deserves an article.
678
- 3. **Does it belong in an existing \`event\` or \`decision\`?** Most work entries fold into one of these.
679
- 4. **Can you skip it?** If the entry is small talk, a transient status ping, or already covered elsewhere \u2014 skip. The wiki is curated, not exhaustive.
680
-
681
- ## Writing standards
682
-
683
- - **Wikipedia-style, flat, factual, encyclopedic.** This is the agent's knowledge, not a diary. Write about the *role* of the entity in our work, not a product description.
684
- - **Synthesize, don't quote.** At most 2 short quoted lines per article.
685
- - **Organize by theme, not chronology.** An article about a person lists what they do, who they work with, how they prefer to be contacted \u2014 not a log of every interaction.
686
- - **Length: 20\u2013100 lines.** Articles exceeding 100 lines should split into multiple type-specific articles.
687
- - **Every paragraph earns its place.** Cut narrative filler. If you can remove a sentence without losing a fact, remove it.
688
-
689
- ## Wikilink discipline
690
-
691
- - Use \`[[Article Title]]\` **inside the body** every time another tracked entity is referenced.
692
- - List those same targets in the \`related\` frontmatter field.
693
- - If you reference something that has no article yet (\`[[New Thing]]\`), add "New Thing" to the output \`gaps\` array so the next pass can create it.
694
-
695
- ## Article frontmatter (exact shape \u2014 do not invent fields)
696
-
697
- \`\`\`yaml
698
- ---
699
- title: "Article Title"
700
- type: person | project | place | concept | event | decision | pattern
701
- related: ["Other Article", "Another Article"]
702
- tags: ["2-4-specific-tags", "no-dates-unless-event"]
703
- owner: ${e}
704
- access: public | shared | private
705
- created: YYYY-MM-DD
706
- last_updated: YYYY-MM-DD
707
- sources: ["entry-id-1", "entry-id-2"]
708
- ---
709
- \`\`\`
710
-
711
- Access guidance: default \`public\`; \`private\` only for sensitive credentials or agent-specific learnings; \`shared\` with specific agent IDs when the article matters only to a subset.
712
- ${r}${a}
713
- ## Gap Detection
714
-
715
- After compiling, populate a \`gaps\` array: wikilink targets you referenced but for which no article exists yet. Be specific:
716
-
717
- - Good: "Karim Rahmouni \u2014 coach for Tunis Padel club, mentioned twice but no \`people/\` article"
718
- - Bad: "We need more content about deployments"
719
-
720
- ## Output \u2014 valid JSON only, no markdown fencing
721
-
722
- \`\`\`
723
- {
724
- "articles": [
725
- {
726
- "path": "projects/mtgl-system-v2.md",
727
- "title": "MTGL System V2",
728
- "type": "project",
729
- "related": ["Anis Marrouchi", "Laravel", "Staging Deployment"],
730
- "tags": ["mtgl", "laravel", "react"],
731
- "content": "MTGL System V2 is [[Anis Marrouchi]]'s production Laravel + React app for \u2026",
732
- "sources": ["entry-id-1", "entry-id-2"]
733
- }
734
- ],
735
- "gaps": [
736
- "Karim Rahmouni \u2014 Tunis Padel coach, mentioned in entries but no people/ article"
737
- ]
738
- }
739
- \`\`\`
740
-
741
- ENTRIES (${s}):
742
-
743
- ${o}`}import{resolve as M,relative as oo,dirname as so}from"path";import{execSync as Be}from"child_process";import{writeFileSync as Fe,mkdirSync as Se,readFileSync as wt,readdirSync as Zs,renameSync as Dt,rmSync as er,existsSync as yt}from"fs";function re(e,t){return new at(e||M(process.cwd(),".agentx/wiki"),void 0,t||"graph")}function rn(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var K=new Xs().name("wiki").description("wiki knowledge base management");K.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let t=e.mode,n=re(e.dir,t),o=n.summary(),r=n.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${rn(t)}]`)),console.log(),console.log(` Total raw entries: ${r}`),console.log(` Agents: ${o.length}`),console.log();for(let a of o){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let i=o.reduce((a,c)=>a+c.unabsorbed,0);i>0&&(console.log(m.dim(` ${i} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});K.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let t=re(e.dir,e.mode),n=e.agent?[e.agent]:t.listAgents(),o=0;console.log();for(let s of n){let i=t.getAgentWiki(s).lint();if(o+=i.length,i.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${i.length} issues`)}`);for(let a of i){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),o===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});K.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--max <n>","max entries per agent","10").action(async e=>{let t=e.mode,n=re(e.dir,t),o=e.agent?[e.agent]:n.listAgents(),s=parseInt(e.max),r=0;for(let i of o){let a=n.getUnabsorbedEntries(i).slice(0,s);if(a.length===0){console.log(` ${m.cyan(i)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(i)}: ${a.length} entries to absorb`));for(let y of a.slice(0,3))console.log(m.dim(` [${y.date} via ${y.source}] ${y.content.slice(0,80)}...`));if(a.length>3&&console.log(m.dim(` ... and ${a.length-3} more`)),e.dryRun)continue;let c=n.getAgentWiki(i),l=c.rebuildIndex(),d=c.getWorldview()||n.getSharedStore().getWorldview()||"",p=a.map(y=>`--- ENTRY ${y.id} [${y.date} ${y.agentId} via ${y.source}] ---
744
- ${y.content}
745
- --- END ENTRY ---`).join(`
746
-
747
- `),g=no(t,i,d,l.articles,p,a.length);console.log(m.dim(` Mode: ${rn(t)}`));let u=M(c.baseDir,"_tmp");Se(u,{recursive:!0});let f=M(u,"absorb-prompt.txt");Fe(f,g),console.log(m.dim(" Compiling with Claude..."));try{let y;try{y=Be(`cat '${f}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(R){if(y=R.stdout||"",!y)throw R}let w=y;try{let R=JSON.parse(y);w=R.result||R.content||"",w||(console.log(m.dim(` Claude envelope keys: ${Object.keys(R).join(", ")}`)),console.log(m.dim(` is_error: ${R.is_error}, stop_reason: ${R.stop_reason}`)))}catch{}let b,$=[],v=w.indexOf("{"),x=w.indexOf("["),k=v>=0&&(x<0||v<x)?v:x;if(k===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(w.slice(0,500)));continue}let j=w[k],A=j==="{"?"}":"]",O=0,I=-1;for(let R=k;R<w.length;R++)if(w[R]===j)O++;else if(w[R]===A&&(O--,O===0)){I=R+1;break}if(I===-1){console.log(m.red(" Unbalanced JSON"));continue}let P=w.slice(k,I);try{let R=JSON.parse(P);Array.isArray(R)?b=R:(b=R.articles||[],$=R.gaps||[])}catch(R){console.log(m.red(` JSON parse error: ${R.message}`)),console.log(m.dim(` First 300 chars: ${P.slice(0,300)}`));continue}for(let R of b){let me=new Date().toISOString().slice(0,10);c.writeArticle(R.path,{title:R.title,type:R.type,related:Array.isArray(R.related)?R.related:void 0,tags:R.tags||[],owner:i,access:"public",created:me,lastUpdated:me,sources:R.sources||[]},R.content,i);let He=R.type?m.magenta(`[${R.type}]`)+" ":"",se=Array.isArray(R.related)&&R.related.length?` \u2192 ${R.related.slice(0,3).join(", ")}${R.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${He}${R.path}: ${R.title}${m.dim(se)}`);let ce=(R.tags||[]).slice(0,4).join(", ");ce&&console.log(m.dim(` tags: ${ce}`)),r++}if($.length>0){console.log(),console.log(m.yellow(` Gaps detected (${$.length} missing pieces):`));for(let R of $)console.log(m.yellow(` ? ${R}`))}c.rebuildIndex()}catch(y){console.log(m.red(` Absorb failed: ${y.message?.slice(0,200)}`)),y.stderr&&console.log(m.dim(String(y.stderr).slice(0,300))),y.stdout&&console.log(m.dim("stdout: "+String(y.stdout).slice(0,300)))}}console.log(),e.dryRun?console.log(m.dim(" Dry run \u2014 no changes made")):r>0&&console.log(m.green(` ${r} articles compiled across ${o.length} agent(s)`)),console.log()});K.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",M(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-FZAL7AQD.js"),{readdirSync:n,readFileSync:o,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=re(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),d=parseInt(e.n),p=r(e.history,c);if(!s(p)){console.log(m.yellow(` no task-history at ${p}`));return}let g=[],u=n(p).sort().reverse();for(let w of u){let b=i(p,w),$=[];try{$=n(b).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of $){if(g.length>=d)break;try{let x=JSON.parse(o(i(b,v),"utf-8")),k=x.message||x.task?.message;typeof k=="string"&&k.trim().length>10&&g.push({id:x.id||v.replace(".json",""),message:k.trim(),ts:x.at||x.timestamp||w})}catch{}}if(g.length>=d)break}if(g.length===0){console.log(m.yellow(` no task messages found under ${p}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${g.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let f=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${g.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<g.length;w++){let b=g[w];process.stdout.write(m.dim(` [${w+1}/${g.length}] querying... `));let v=l.findRelevant(b.message,c,3).map(k=>`- **${k.meta.title}** [${k.meta.type||"?"}] (${k.path})`).join(`
748
- `)||"_(none returned)_",x;try{let k=await t(b.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(k.status!=="ok")x=`_(status: ${k.status}${k.error?" \u2014 "+k.error:""})_`;else{let j=k.citations.map(A=>`\`${A.title}\` [${A.type||"?"}]`).join(", ");x=`**Answer:**
749
-
750
- ${k.answer}
751
-
752
- **Citations:** ${j}`}}catch(k){x=`_(error: ${k.message})_`}console.log(m.dim("done")),f.push(`## ${w+1}. ${b.id}`,"",`> ${b.message.replace(/\n/g," ").slice(0,400)}${b.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",x,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let y=f.join(`
753
- `);e.out?((await import("fs")).writeFileSync(e.out,y),console.log(),console.log(m.green(` Wrote ${y.length} bytes to ${e.out}`))):(console.log(),console.log(y))});K.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'MTGL deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:n}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:o}=await import("./types-ECMEC5BZ.js"),s=e.answers?wt(e.answers,"utf-8").split(/\r?\n/).filter(E=>E.length>0):null,r=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let i=re(e.dir),a;try{a=i.getAgentWiki(e.agent)}catch(E){console.log(m.red(` can't open wiki for agent "${e.agent}": ${E.message}`));return}let c=s?null:t.createInterface({input:process.stdin,output:process.stdout}),l=async E=>{if(s){let Z=s[r++]??"";return process.stdout.write(E+m.dim(`[scripted] ${Z.slice(0,80)}${Z.length>80?"\u2026":""}`)+`
754
- `),Z.trim()}return(await c.question(E)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let d=e.topic||"";if(!d&&(d=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!d||d==="/abort")){c?.close();return}let p=(e.type||"").toLowerCase(),g=new Set(o);if(!g.has(p)){console.log(m.dim(` Types: ${o.join(" | ")}`));let E=await l(m.cyan(" Type? "));if(E==="/abort"){c?.close();return}g.has(E)?p=E:(console.log(m.yellow(` "${E}" isn't a valid type. Falling back to "concept".`)),p="concept")}let u={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},f=u[p]||u.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(d)} \xB7 Type: ${m.magenta(p)}`)),console.log(m.dim(` ${f.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let y=[],w=!1;for(let E=0;E<f.length;E++){let Z=f[E],ue=await l(` ${m.dim(`[${E+1}/${f.length}]`)} ${Z}
755
- ${m.green(">")} `);if(ue==="/abort"){w=!0;break}if(ue==="/done")break;ue!=="/skip"&&ue&&y.push({q:Z,a:ue})}if(!w){let E=await l(`
756
- ${m.dim("Anything else worth capturing?")}
757
- ${m.green(">")} `);E&&E!=="/abort"&&E!=="/done"&&y.push({q:"Anything else worth capturing?",a:E})}if(w||y.length===0){console.log(m.yellow(`
758
- Nothing captured. Exiting.`)),c?.close();return}let $=a.listArticles(e.agent).slice(0,40).map(E=>`- ${E.meta.title} [${E.meta.type||"?"}]`).join(`
759
- `),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${d}`,`**Type:** ${p}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...y.map(E=>`
760
- Q: ${E.q}
761
- A: ${E.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",$||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${p}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
762
- `),x=M(a.baseDir,"_tmp");Se(x,{recursive:!0});let k=M(x,`interview-${n().slice(0,8)}.txt`);Fe(k,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let j="";try{let E=`cat '${k}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,Z=Be(E,{encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let ue=JSON.parse(Z);j=String(ue.result||ue.content||"")}catch{j=Z}}catch(E){console.log(m.red(` synthesis failed: ${E.message?.slice(0,200)}`)),c?.close();return}j=j.trim();let A=j.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);A&&(j=A[1].trim());let O=j.indexOf("---");O>0&&(j=j.slice(O));let I=j.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!I){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(j.slice(0,600)),c?.close();return}let P={};for(let E of I[1].split(`
763
- `)){let Z=E.match(/^(\w+):\s*(.+)$/);Z&&(P[Z[1]]=Z[2].trim().replace(/^"(.*)"$/,"$1"))}let R=I[2],me=P.title||d,He=me.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ce=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[p]||p+"s"}/${He}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ce}`)),console.log(),console.log(j),console.log();let Ye=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),Ye==="scrap"||Ye==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${k} (prompt only; no article file)`));return}let Ge=R,Ae={title:me,type:P.type||p,related:P.related?P.related.replace(/^\[|\]$/g,"").split(",").map(E=>E.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:P.tags?P.tags.replace(/^\[|\]$/g,"").split(",").map(E=>E.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:P.access||"public",created:P.created||new Date().toISOString().slice(0,10),lastUpdated:P.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(Ye==="edit"){let E=process.env.EDITOR||"vi",Z=M(x,`draft-${n().slice(0,8)}.md`);Fe(Z,j);try{Be(`${E} '${Z}'`,{stdio:"inherit"});let Wt=wt(Z,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Wt){let Ce={};for(let it of Wt[1].split(`
764
- `)){let Mt=it.match(/^(\w+):\s*(.+)$/);Mt&&(Ce[Mt[1]]=Mt[2].trim().replace(/^"(.*)"$/,"$1"))}Ge=Wt[2],Ae={...Ae,title:Ce.title||Ae.title,type:Ce.type||Ae.type,access:Ce.access||Ae.access,related:Ce.related?Ce.related.replace(/^\[|\]$/g,"").split(",").map(it=>it.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ae.related,tags:Ce.tags?Ce.tags.replace(/^\[|\]$/g,"").split(",").map(it=>it.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ae.tags}}}catch(ue){console.log(m.red(` editor failed: ${ue.message}`));return}}if(!a.writeArticle(ce,Ae,Ge,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ce} saved.`));let Co=a.extractWikilinks(Ge),yn=new Map;for(let E of a.listArticles(e.agent))yn.set(E.meta.title.toLowerCase(),!0);let wn=Co.filter(E=>!yn.has(E.toLowerCase()));if(wn.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let E of wn.slice(0,8))console.log(m.dim(` - ${E}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});K.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:n}=await import("node:crypto"),{agenticQuery:o}=await import("./query-FZAL7AQD.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=re(e.dir),r;try{r=s.getAgentWiki(e.agent)}catch(u){console.log(m.red(` can't open wiki for agent "${e.agent}": ${u.message}`));return}let i=null;if(e.script){let f=wt(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);i=[];for(let y of f){let w=y.split(/\r?\n/).filter(v=>v.trim());if(w.length<2)continue;let b=w[0].replace(/^Q:\s*/i,"").trim(),$=w.slice(1).join(" ").trim();b&&$&&i.push({q:b,verdict:$})}}let a=i?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async u=>a?(await a.question(u)).trim():"",l=Math.min(parseInt(e.rounds)||20,i?.length??999),d=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${d?"commit":"dry-run"} \xB7 ${i?`scripted (${i.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let p=[],g=0;for(let u=0;u<l;u++){let f,y;if(i){let se=i[u];if(!se)break;f=se.q,y=se.verdict,console.log(m.cyan(` [${u+1}] Q: `)+f)}else{if(f=await c(m.cyan(` [${u+1}] Q: `)),!f||f==="/done"||f==="/abort")break;y=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await o(f,r,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(se){console.log(m.red(`failed: ${se.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let se=w.citations.map(ce=>`${ce.title} [${ce.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
765
- `)),console.log(m.dim(" citations: "+se))}i||(y=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+y);let b={q:f,answer:w.answer,citations:w.citations,verdict:y},$=y.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),p.push(b);continue}let v=$[1].toLowerCase(),x=($[2]||"").trim();if(p.push(b),v==="/ok"||v==="/skip")continue;if(!x){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let k=w.citations[0];if(!k){console.log(m.yellow(" no cited article to patch."));continue}let j=r.readArticle(k.path);if(!j){console.log(m.red(` can't read ${k.path} to patch.`));continue}console.log(m.dim(` patching ${k.title} (${k.path})...`));let A=nr(j.content,v,x,j.meta.title,j.meta.type),O=M(r.baseDir,"_tmp");Se(O,{recursive:!0});let I=M(O,`quiz-patch-${n().slice(0,8)}.txt`);Fe(I,A);let P="";try{let se=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ce=Be(se,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ge=JSON.parse(ce);P=String(Ge.result||Ge.content||"")}catch{P=ce}let Ye=P.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);Ye&&(P=Ye[1].trim()),P=P.trim()}catch(se){console.log(m.red(` patch failed: ${se.message?.slice(0,120)}`));continue}if(!P||P.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let R=j.content.split(`
766
- `).length,me=P.split(`
767
- `).length;if(console.log(m.dim(` diff: ${R} \u2192 ${me} lines (${me-R>=0?"+":""}${me-R})`)),!d){console.log(m.dim(" (--no-commit: patch not written)")),b.patched=k.path+" (dry)";continue}if(!r.writeArticle(k.path,{...j.meta,lastUpdated:new Date().toISOString().slice(0,10)},P,e.agent)){console.log(m.red(" write failed (permission?)"));continue}g++,b.patched=k.path,console.log(m.green(` \u2713 patched ${k.path}`))}if(a&&a.close(),g>0&&d&&r.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${p.length} rounds, ${g} patches applied.`)),e.out){let u=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} rounds \xB7 ${g} patches_`,""];for(let f=0;f<p.length;f++){let y=p[f];u.push(`## ${f+1}. Q: ${y.q}`,"",`**A:** ${y.answer}`,"",`**Citations:** ${y.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${y.verdict}\``+(y.patched?` \u2192 patched \`${y.patched}\``:""),"")}Fe(e.out,u.join(`
768
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});K.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,n)=>{let o=re(n.dir),s;try{s=o.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let r=ao(s,t,e);if(!r){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let i=M(s.baseDir,r),a=n.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{Be(`${a} '${i}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(r);if(c){let l=new Set,d=s.extractWikilinks(c.content).filter(u=>l.has(u)?!1:(l.add(u),!0)),p=c.meta.related||[];(d.some(u=>!p.includes(u))||p.some(u=>!d.includes(u)))&&(s.writeArticle(r,{...c.meta,related:d.length?d:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${d.length} wikilink${d.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${r} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});K.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,t,n,o)=>{let s=await import("node:readline/promises"),{randomUUID:r}=await import("node:crypto"),i=re(o.dir),a;try{a=i.getAgentWiki(e)}catch(k){console.log(m.red(` can't open wiki for agent "${e}": ${k.message}`));return}let c=ao(a,t,e);if(!c){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let d=tr(l.content,l.meta.title,l.meta.type,n),p=M(a.baseDir,"_tmp");Se(p,{recursive:!0});let g=M(p,`patch-${r().slice(0,8)}.txt`);Fe(g,d),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${o.patchModel}...`));let u="";try{let k=`cat '${g}' | claude -p - --output-format json --max-turns 1 --model ${o.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,j=Be(k,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let O=JSON.parse(j);u=String(O.result||O.content||"")}catch{u=j}let A=u.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);A&&(u=A[1].trim()),u=u.trim()}catch(k){console.log(m.red(` patch failed: ${k.message?.slice(0,150)}`));return}if(!u||u.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let f=l.content.split(`
769
- `).length,y=u.split(`
770
- `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${f} \u2192 ${y} lines (${y-f>=0?"+":""}${y-f})`)),console.log(),console.log(u),console.log(),!o.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let w=!!o.yes;if(!w){let k=s.createInterface({input:process.stdin,output:process.stdout}),j=(await k.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();k.close(),w=j==="y"||j==="yes"}if(!w){console.log(m.dim(" aborted."));return}let b=new Set,$=a.extractWikilinks(u).filter(k=>b.has(k)?!1:(b.add(k),!0));if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},u,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let x=(l.meta.related||[]).filter(k=>!$.includes(k));x.length&&console.log(m.dim(` (pruned stale related: ${x.slice(0,3).join(", ")}${x.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function ao(e,t,n){let o=t.trim(),s=e.listArticles(n),r=o.toLowerCase(),i=s.find(l=>l.meta.title.toLowerCase()===r);if(i)return i.path;if(o.includes("/")||o.endsWith(".md")){let l=o.endsWith(".md")?o:`${o}.md`,d=s.find(p=>p.path===l||p.path===o);if(d)return d.path}let a=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let d=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return d===a||d.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function tr(e,t,n,o){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${n||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",o,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
771
- `)}function nr(e,t,n,o,s){let r={"/correct":`The operator says the article contains an error:
772
-
773
- ${n}
774
-
775
- Edit the article to correct ONLY this mistake. Do not rewrite untouched sections. Keep the existing prose style. If the correction invalidates a larger passage, revise the minimum that must change.`,"/add":`The operator wants to add this detail:
776
-
777
- ${n}
778
-
779
- Incorporate it into the most relevant existing section, or create a short new section if nothing fits. Keep the prose encyclopedic and under 100 additional words.`,"/link":`The operator wants to add this resource:
780
-
781
- ${n}
782
-
783
- Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${n}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${o}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",r[t]||`Make a minimal edit per: ${n}`,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
784
- `)}K.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let t=re(e.dir),n=e.agent?[e.agent]:t.listAgents(),o=!!e.commit,s=e.dir?M(e.dir):M(process.cwd(),".agentx/wiki"),r="graph",i=["flat","unified"];console.log(),console.log(m.bold(o?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${r}/ \xB7 Legacy to collapse: ${i.join("/, ")}/`));let a=0,c=0,l=0,d=0;for(let p of n){let g=M(s,"agents",p);if(!yt(g))continue;let u=M(g,r),f=i.map($=>({mode:$,dir:M(g,$)})).filter($=>yt($.dir));if(f.length===0)continue;let y=new Map;sn(u,$=>{let v=oo(u,$);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let x=ro(wt($,"utf-8"));x?.meta.title&&y.set(x.meta.title.trim().toLowerCase(),{relPath:v,type:x.meta.type,lastUpdated:x.meta.lastUpdated||""})});let w=[];for(let $ of f)sn($.dir,v=>{let x=oo($.dir,v);if(x.startsWith("_")||x.startsWith("raw/")||x.includes("_tmp/"))return;let k=ro(wt(v,"utf-8"));k?.meta.title&&w.push({mode:$.mode,relPath:x,absPath:v,title:k.meta.title.trim(),type:k.meta.type,lastUpdated:k.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let b=f.map($=>$.mode).join("+");console.log(m.bold(` ${m.cyan(p)}: ${w.length} legacy article(s) across ${b}`));for(let $ of w){let v=$.title.toLowerCase(),x=y.get(v),k;x?!x.type&&$.type||!!x.type==!!$.type&&$.lastUpdated&&x.lastUpdated&&$.lastUpdated>x.lastUpdated?k="upgrade":k="archive":k="promote";let j=$.type?m.magenta(`[${$.type}]`):m.yellow("[untyped]"),A=k==="promote"?m.green("\u2192 promote "):k==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),O=$.relPath.length>46?$.relPath.slice(0,43)+"...":$.relPath.padEnd(46);if(console.log(` ${A} ${j} ${m.dim($.mode+"/")}${O}`),k==="upgrade"&&console.log(m.dim(` (replaces ${x.relPath}, old version kept under _versions/)`)),!o){k==="promote"?c++:k==="upgrade"?l++:d++;continue}try{if(k==="promote"){let I=M(u,$.relPath);yt(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${$.relPath}`)),io(g,$),d++):(Se(so(I),{recursive:!0}),Dt($.absPath,I),y.set(v,{relPath:$.relPath,type:$.type,lastUpdated:$.lastUpdated}),c++)}else if(k==="upgrade"){let I=M(u,x.relPath);if(yt(I)){let P=M(g,"_versions",x.relPath.replace(/\.md$/,""));Se(P,{recursive:!0});let R=new Date().toISOString().replace(/[:.]/g,"-");Dt(I,M(P,`${R}.md`))}Se(so(I),{recursive:!0}),Dt($.absPath,I),y.set(v,{relPath:x.relPath,type:$.type,lastUpdated:$.lastUpdated}),l++}else io(g,$),d++}catch(I){console.log(m.red(` ! ${k} failed: ${I.message?.slice(0,120)}`))}}if(o){for(let $ of f)try{er($.dir,{recursive:!0,force:!0})}catch{}try{t.getAgentWiki(p).rebuildIndex()}catch($){console.log(m.dim(` (catalog rebuild skipped: ${$.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),o?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${d}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${d}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function sn(e,t){if(yt(e))for(let n of Zs(e,{withFileTypes:!0})){let o=M(e,n.name);n.isDirectory()?sn(o,t):n.isFile()&&n.name.endsWith(".md")&&t(o)}}function ro(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let n={};for(let o of t[1].split(`
785
- `)){let s=o.match(/^(\w+):\s*(.+)$/);if(!s)continue;let r=s[1]==="last_updated"?"lastUpdated":s[1];n[r]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:n}}function io(e,t){let n=M(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));Se(n,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-");Dt(t.absPath,M(n,`${o}.md`))}K.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let t=re(e.dir),n=e.agent?[e.agent]:t.listAgents(),o=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,r=!!e.commit;console.log(),console.log(m.bold(r?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${o} \xB7 Model: ${e.model}`)),console.log();let i=0,a=0,c=0;for(let l of n){let d=t.getAgentWiki(l),p=d.listArticles(l),g=p.filter(b=>!b.meta.type);if(i+=p.length,a+=g.length,g.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${p.length} articles)`);continue}let u=Math.max(0,s-c),f=Math.min(g.length,u);if(f===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${f}/${g.length} untyped articles`));let y=d.baseDir,w=M(y,"_tmp");Se(w,{recursive:!0});for(let b=0;b<f;b+=o){let $=g.slice(b,Math.min(b+o,f)),v=sr($),x=M(w,"migrate-prompt.txt");Fe(x,v);let k;try{let j=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,A=Be(j,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),O=JSON.parse(A),P=String(O.result||O.content||"").match(/\[[\s\S]*\]/);if(!P)throw new Error("no JSON array in classifier response");k=JSON.parse(P[0])}catch(j){console.log(m.red(` LLM classify failed: ${j.message?.slice(0,150)}`));continue}for(let j of $){let A=k.find(He=>He.path===j.path),O=or(A?.type);if(!A||!O){console.log(m.yellow(` ? ${j.path}: unclassified${A?` (got "${A.type}")`:""}`));continue}let I=d.extractWikilinks(j.content),P={...j.meta,type:O.type,related:I.length?I:void 0,lastUpdated:new Date().toISOString().slice(0,10)},R=I.length?m.dim(` \u2192 ${I.slice(0,3).join(", ")}${I.length>3?", \u2026":""}`):"",me=O.alias?m.dim(` (from "${O.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+O.type+"]")}${me} ${j.path}${R}`),r&&(d.writeArticle(j.path,P,j.content,l),c++)}}r&&d.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${i} articles; ${a} needed migration`)),console.log(r?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function or(e){if(!e)return null;let t=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!t)return null;let o={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[t];return o?o===t?{type:o}:{type:o,alias:t}:null}function sr(e){let t=e.map((n,o)=>{let s=n.content.replace(/\s+/g," ").slice(0,400),r=(n.meta.tags||[]).slice(0,8).join(", ");return`${o+1}. path: "${n.path}"
786
- title: "${n.meta.title}"
787
- tags: [${r}]
788
- body: ${s}${n.content.length>400?"\u2026":""}`}).join(`
789
-
790
- `);return`Classify each of these ${e.length} wiki articles into EXACTLY ONE type from this closed set (no synonyms, no plurals, no new values):
791
-
792
- person | project | place | concept | event | decision | pattern
793
-
794
- What each type means:
795
- - person: an individual human (team member, stakeholder, contact)
796
- - project: a named initiative, repo, product, service, bot, agent, team, or org
797
- - place: a physical or logical location (office, server, environment, infrastructure)
798
- - concept: a recurring idea, philosophy, methodology, or thinking pattern
799
- - event: a specific dated thing that happened (incident, deploy, launch, GitLab issue, MR)
800
- - decision: a specific choice made and why (architecture decision, policy, ADR)
801
- - pattern: a reusable workflow, template, recipe, procedure, runbook, or SOP
802
-
803
- Explicit mappings (you WILL be tempted to volunteer these \u2014 don't; use the right-hand value):
804
- - "agent" / "bot" / "service" / "repo" / "team" \u2192 project
805
- - "issue" / "MR" / "ticket" / "incident" / "deploy" \u2192 event
806
- - "process" / "procedure" / "runbook" / "workflow" \u2192 pattern
807
- - "infrastructure" / "server" / "environment" \u2192 place
808
- - "ADR" / "decision record" \u2192 decision
809
-
810
- Rules:
811
- - Return EXACTLY one type per article, by path, from the 7 allowed values above.
812
- - Do not invent new types. Do not return plurals. Do not return synonyms.
813
- - If the title is a person's name, it's person. If it's a repo/product/bot name, it's project. If it's dated + past tense, it's event.
814
- - If you genuinely cannot decide, pick "concept" as the fallback.
815
- - Output ONLY valid JSON, no markdown fencing, no prose.
816
-
817
- Articles:
818
-
819
- ${t}
820
-
821
- Output (JSON array, one entry per input article, same order):
822
- [
823
- {"path": "path/to/article.md", "type": "project"},
824
- ...
825
- ]`}K.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let o=re(e.dir).getSharedStore().listEntries();e.agent&&(o=o.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${o.length} raw entries`)),console.log();for(let s of o.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);o.length>20&&console.log(m.dim(` ... showing last 20 of ${o.length}`)),console.log()});K.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let t=e.dir||M(process.cwd(),".agentx/wiki"),n=parseInt(e.port),o=e.peer||[];if(o.length===0)try{let{loadDaemonConfig:s}=await import("./config-UOHEG4BW.js");o=(s().mesh?.peers||[]).map(i=>i.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${n}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),o.length>0&&console.log(` Mesh: ${m.cyan(o.length+" peer(s)")} \u2014 ${o.join(", ")}`),console.log(m.dim(` Wiki: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),to(t,n,e.agent,o,e.mode)});K.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,t)=>{let{agenticQuery:n}=await import("./query-FZAL7AQD.js"),o=re(t.dir),s=t.agent?[t.agent]:o.listAgents(),r=null;for(let c of s){let l=o.getAgentWiki(c),d=M(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(d)){r=c;break}}catch{}}if(!r){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let i=o.getAgentWiki(r),a=await n(e,i,r,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles)});if(t.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${r} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(t.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(d=>d.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});K.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action((e,t)=>{let n=re(t.dir,t.mode),o=t.agent?[t.agent]:n.listAgents();console.log();let s=0;for(let r of o){let a=n.getAgentWiki(r).findRelevant(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(r)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});K.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.67.108.119:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let n=re(e.dir).getSharedStore(),o=[];if(e.peer)o=[e.peer];else try{let{loadDaemonConfig:i}=await import("./config-UOHEG4BW.js");o=(i().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.67.108.119:19900"));return}if(o.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(n.listEntries().map(i=>i.id)),r=0;for(let i of o){console.log(),console.log(m.bold(` Syncing from ${i}...`));try{let a=await fetch(`${i}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],d=c.nodeId||"unknown";console.log(m.dim(` Node: ${d} \u2014 ${l.length} entries`));let p=0;for(let g of l)s.has(g.id)||(e.dryRun||(n.addEntry({id:g.id,date:g.date,agentId:g.agentId,source:`${g.source}@${d}`,sourceContext:g.sourceContext,content:g.content}),s.add(g.id)),p++);p>0?console.log(m.green(` ${p} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),r+=p;try{let g=await fetch(`${i}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(g.ok){let u=await g.json();for(let f of u.agents||[])f.totalEntries>0&&console.log(m.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),r>0&&!e.dryRun?console.log(m.green(` ${r} entries synced.`)):r>0?console.log(m.dim(` ${r} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});K.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||M(process.cwd(),".agentx/wiki"),n=e.agent,s=["flat","graph","unified"].map(c=>{let l=new at(t,void 0,c),p=l.getAgentWiki(n).rebuildIndex(),g=l.getAgentEntries(n),u=l.getUnabsorbedEntries(n),f=new Set,y=0,w=new Set;for(let $ of p.articles){for(let v of $.tags||[])f.add(v);y+=$.tags?.length||0;for(let v of $.sources||[])w.add(v)}let b=new Set(p.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:rn(c),articles:p.articles.length,entries:g.length,unabsorbed:u.length,uniqueTags:f.size,avgTags:p.articles.length>0?(y/p.articles.length).toFixed(1):"0",dirs:b.size,coverage:w.size,articleList:p.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${n}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let r=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(r)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(r)).join(" ")}`);let i=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of i){let d=s.map(p=>l(p).padEnd(r));console.log(` ${c.padEnd(20)} ${d.join(" ")}`)}console.log();let a=(c,l)=>{let d=Math.max(...s.map(g=>g[c])),p=s.filter(g=>g[c]===d).map(g=>g.label);d>0&&console.log(m.dim(` Best ${l}: ${p.join(", ")} (${d})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});import{Command as rr}from"commander";import W from"chalk";import{resolve as co}from"path";var Pt=new rr().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Pt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let t=U();if(!t.graph?.enabled){console.log(W.yellow(" graph.enabled is false \u2014 nothing to review"));return}let n=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!n){console.log(W.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[n]){console.log(W.red(` agent "${n}" not in config`));return}let o=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),r=new _t({baseDir:co(process.cwd(),t.graph.baseDir)}),i=r.listPendingClassifications(s);if(i.length===0){console.log(W.dim(" no pending classifications \u2014 nothing to review"));return}let a=r.loadSchema(),c=r.loadNodes().nodes;console.log(),console.log(W.bold(` Graph review \u2014 ${i.length} pending`)),console.log(W.dim(` Reviewer: ${n} \xB7 daemon: ${o} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,d=0,p=0,g=0;for(let f=0;f<i.length;f++){let y=i[f],w=$n(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${f+1}/${i.length}] ${W.cyan(y.msgHash.slice(0,8))} ${W.dim(w)} ... `);let b=ir(y,a,c),$=null;try{$=await ar(o,n,b,t.dashboard?.token)}catch(k){g++,console.log(W.red(`ERR ${k.message?.slice(0,80)}`));continue}if(!$||!$.decision){g++,console.log(W.red("ERR no decision"));continue}let v=String($.decision).toLowerCase().trim(),x=($.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(W.green("APPROVE")+" "+W.dim(x)),e.dryRun)l++;else try{cr(r,y,a,c,n),r.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:n,reviewReason:x}),l++}catch(k){console.log(W.yellow(` (commit failed, staying pending: ${k.message?.slice(0,100)})`)),g++}else v==="reject"?(console.log(W.red("REJECT")+" "+W.dim(x)),e.dryRun||r.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:n,reviewReason:x}),d++):(console.log(W.yellow("SKIP")+" "+W.dim(x||v)),p++)}console.log();let u=e.dryRun?"would":"did";console.log(W.dim(` Summary: ${u} approve ${l}, ${u} reject ${d}, ${p} skipped, ${g} errors.`)),e.dryRun&&(l>0||d>0)&&console.log(W.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Pt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://clawd.noqta.tn:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let t=U();if(!t.graph?.enabled){console.log(W.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let n=String(e.from).replace(/\/+$/,""),o=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let r=new _t({baseDir:co(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,c=new Set(a.map(A=>A.id));console.log(),console.log(W.bold(` graph pull \u2190 ${n}`));let l,d,p;try{let A=await fetch(`${n}/graph/schema`,{headers:s});if(!A.ok)throw new Error(`schema HTTP ${A.status}`);l=(await A.json()).schema;let I=await fetch(`${n}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);d=(await I.json()).nodes||[];let P=await fetch(`${n}/graph/classifications?status=approved&limit=${o}`,{headers:s});if(!P.ok)throw new Error(`classifications HTTP ${P.status}`);p=(await P.json()).classifications||[]}catch(A){console.log(W.red(` fetch failed: ${A.message}`));return}let g=i.levels.map(A=>A.id).join(","),u=l?.levels?.map(A=>A.id).join(","),f=g===u;f?console.log(W.dim(` schema matches (${i.levels.length} levels)`)):(console.log(W.yellow(" \u26A0 schema levels differ:")),console.log(W.dim(` local: ${g}`)),console.log(W.dim(` peer: ${u}`)),a.length===0&&!e.dryRun?(console.log(W.dim(" local is empty \u2014 adopting peer schema")),r.saveSchema(l)):console.log(W.yellow(" keeping local schema; node import may fail if levels disagree")));let y=f?i:l,w=new Map;y.levels.forEach((A,O)=>w.set(A.id,O));let b=[...d].sort((A,O)=>(w.get(A.level)??99)-(w.get(O.level)??99)),$=0,v=0,x=0;for(let A of b){if(c.has(A.id)){v++;continue}if(e.dryRun){$++,c.add(A.id);continue}try{r.addNode({...A,createdBy:A.createdBy?`${A.createdBy} (sync)`:`sync:${n}`}),c.add(A.id),$++}catch(O){x++,console.log(W.yellow(` skip node ${A.id}: ${O.message?.slice(0,100)}`))}}console.log(W.dim(` nodes: +${$} added \xB7 ${v} already-present \xB7 ${x} failed`));let k=0,j=0;for(let A of p)if(!(!A.msgHash||!Array.isArray(A.path))){if(r.getFingerprint(A.msgHash)){j++;continue}if(e.dryRun){k++;continue}r.setFingerprint(A.msgHash,{path:A.path,leaf:A.leaf||{}}),k++}console.log(W.dim(` fingerprints: +${k} cached \xB7 ${j} already-present`)),console.log(),e.dryRun?console.log(W.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(W.green(` \u2713 pulled from ${n}`)),console.log()});function ir(e,t,n){let o={};for(let i of n)(o[i.level]||=[]).push(`${i.id}${i.axes?.name?` (${i.axes.name})`:""}`);let s=t.levels.map(i=>` ${i.id}: [${(o[i.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
826
- `),r=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",r,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
827
- `)}async function ar(e,t,n,o){let s={"Content-Type":"application/json"};o&&(s.Authorization=`Bearer ${o}`);let r=new AbortController,i=setTimeout(()=>r.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:t,message:n,context:{channel:"a2a",sender:"graph-review"}}),signal:r.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return lr((c?.content||"").toString())}finally{clearTimeout(i)}}function cr(e,t,n,o,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},n,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function lr(e){if(!e)return null;try{return JSON.parse(e)}catch{}let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)try{return JSON.parse(t[1])}catch{}let n=e.indexOf("{");if(n<0)return null;let o=0;for(let s=n;s<e.length;s++)if(e[s]==="{")o++;else if(e[s]==="}"&&(o--,o===0))try{return JSON.parse(e.slice(n,s+1))}catch{return null}return null}import{Command as pr}from"commander";import V from"chalk";import{existsSync as an,mkdirSync as dr,readFileSync as lo,readdirSync as gr,writeFileSync as go}from"fs";import{resolve as cn,relative as ln}from"path";import{z as te}from"zod";var nt=te.object({id:te.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:te.string().min(1),trigger:te.string().min(1,"procedures must describe when they apply"),inputs:te.array(te.string()).default([]),expected:te.string().optional(),kpis:te.array(te.string()).default([]),owner:te.string().optional(),tags:te.array(te.string()).default([]),created:te.string().optional(),updated:te.string().optional(),related:te.array(te.string()).default([])});function po(e){let t=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!t)return{meta:{},body:e};let n={};for(let o of t[1].split(`
828
- `)){let s=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!s)continue;let r=s[1],i=s[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{n[r]=JSON.parse(i);continue}catch{}n[r]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),n[r]=i}return{meta:n,body:t[2]}}function mo(e){let t=["---"];return t.push(`id: ${e.id}`),t.push(`title: "${e.title.replace(/"/g,'\\"')}"`),t.push(`trigger: "${e.trigger.replace(/"/g,'\\"')}"`),e.inputs?.length&&t.push(`inputs: ${JSON.stringify(e.inputs)}`),e.expected&&t.push(`expected: "${e.expected.replace(/"/g,'\\"')}"`),e.kpis?.length&&t.push(`kpis: ${JSON.stringify(e.kpis)}`),e.owner&&t.push(`owner: ${e.owner}`),e.tags?.length&&t.push(`tags: ${JSON.stringify(e.tags)}`),e.related?.length&&t.push(`related: ${JSON.stringify(e.related)}`),e.created&&t.push(`created: ${e.created}`),e.updated&&t.push(`updated: ${e.updated}`),t.push("---"),t.join(`
829
- `)}var qe=class{baseDir;constructor(t={}){this.baseDir=t.baseDir??cn(process.cwd(),".agentx/procedures"),dr(this.baseDir,{recursive:!0})}pathFor(t){return cn(this.baseDir,`${t}.md`)}list(){if(!an(this.baseDir))return[];let t=[];for(let n of gr(this.baseDir,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let o=cn(this.baseDir,n.name),s=lo(o,"utf-8"),{meta:r,body:i}=po(s),a=nt.safeParse({...r,inputs:r.inputs||[],kpis:r.kpis||[],tags:r.tags||[],related:r.related||[]});a.success&&t.push({meta:a.data,body:i.trim(),path:ln(this.baseDir,o)})}return t.sort((n,o)=>n.meta.id.localeCompare(o.meta.id))}get(t){let n=this.pathFor(t);if(!an(n))return null;let o=lo(n,"utf-8"),{meta:s,body:r}=po(o),i=nt.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[]});return i.success?{meta:i.data,body:r.trim(),path:ln(this.baseDir,n)}:null}add(t,n){let o=nt.parse({...t,created:t.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(o.id);if(an(s))throw new Error(`Procedure already exists: ${o.id}`);return go(s,mo(o)+`
830
-
831
- `+n.trim()+`
832
- `),{meta:o,body:n.trim(),path:ln(this.baseDir,s)}}update(t,n,o){let s=this.get(t);if(!s)throw new Error(`Procedure not found: ${t}`);let r=nt.parse({...s.meta,...n,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),i=o!==void 0?o:s.body;return go(this.pathFor(t),mo(r)+`
833
-
834
- `+i.trim()+`
835
- `),{meta:r,body:i.trim(),path:s.path}}};var $t=new pr().name("procedure").description("procedures (SOPs) \u2014 list, add, show \xB7 delta extraction coming later");$t.command("list").description("list all procedures with their trigger line").action(()=>{let t=new qe().list();if(!t.length){console.log(V.dim(" no procedures yet. Add one with: agentx procedure add"));return}console.log();for(let n of t)console.log(` ${V.cyan(n.meta.id)} ${V.bold(n.meta.title)}`),console.log(` ${V.dim("trigger:")} ${n.meta.trigger}`),n.meta.kpis?.length&&console.log(` ${V.dim("kpis:")} ${n.meta.kpis.join(", ")}`);console.log(),console.log(V.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});$t.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-clawd)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,t=[])=>[...t,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,t=[])=>[...t,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,t=[])=>[...t,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,t=[])=>[...t,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let t=new qe,n=e.steps?String(e.steps):`## Steps
836
-
837
- 1. (fill in)
838
-
839
- ## Notes
840
-
841
- `;try{let o=t.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},n);console.log(V.green(` \u2713 procedure added: ${o.meta.id}`)),console.log(V.dim(` ${t.baseDir}/${o.path}`))}catch(o){console.log(V.red(` add failed: ${o.message}`)),process.exit(1)}});$t.command("show <id>").description("show a single procedure").action(e=>{let n=new qe().get(e);n||(console.log(V.yellow(` no procedure matches "${e}". Try: agentx procedure list`)),process.exit(1)),console.log(),console.log(V.bold(` ${n.meta.title}`)+V.dim(` (${n.meta.id})`)),console.log(V.dim(` trigger: ${n.meta.trigger}`)),n.meta.inputs?.length&&console.log(V.dim(` inputs: ${n.meta.inputs.join(", ")}`)),n.meta.expected&&console.log(V.dim(` expected: ${n.meta.expected}`)),n.meta.kpis?.length&&console.log(V.dim(` kpis: ${n.meta.kpis.join(", ")}`)),n.meta.owner&&console.log(V.dim(` owner: ${n.meta.owner}`)),n.meta.related?.length&&console.log(V.dim(` related: ${n.meta.related.join(", ")}`)),console.log(),console.log(n.body),console.log()});import{Command as mr}from"commander";import T from"chalk";import{resolve as ur}from"path";import{existsSync as hr,readFileSync as fr}from"fs";var be=new mr().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");be.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new xt().list();if(!t.length){console.log(T.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let n of t){let s=n.nodes.find(i=>i.type.startsWith("trigger."))?.config??{},r=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / ");console.log(` ${T.cyan(n.id)} ${T.bold(n.title)} ${T.dim(`v${n.version}`)}`),console.log(` ${T.dim("trigger:")} ${s.source??"?"}${r?` ${T.dim(r)}`:""}`),console.log(` ${T.dim("nodes: ")} ${n.nodes.length} (${n.nodes.map(i=>i.type).join(", ")})`)}console.log(),console.log(T.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});be.command("show <id>").description("show a single workflow's full definition").action(e=>{let n=new xt().get(e);n||(console.log(T.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1)),console.log(JSON.stringify(n,null,2))});be.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let r=ur(process.cwd(),e);hr(r)||(console.log(T.red(` file not found: ${r}`)),process.exit(1));try{let i=JSON.parse(fr(r,"utf-8")),a=Sn.safeParse(i);if(!a.success){console.log(T.red(` \u2717 ${r}`));for(let l of a.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}let c=An(a.data);if(c.length){console.log(T.yellow(` ! ${r} (lint)`));for(let l of c)console.log(` ${l}`);process.exit(1)}console.log(T.green(` \u2713 ${a.data.id} \u2014 valid`))}catch(i){console.log(T.red(` parse error: ${i.message}`)),process.exit(1)}return}let n=new xt().validateAll(),o=0,s=0;for(let r of n)if(r.isValid)console.log(T.green(` \u2713 ${r.workflow.id}`)),o++;else{let i=r.workflow?.id||r.id;console.log(T.red(` \u2717 ${i}`));for(let a of r.issues)console.log(` ${a}`);s++}console.log(),console.log(T.dim(` ${o} valid, ${s} invalid.`)),s>0&&process.exit(1)});be.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,t)=>{let n=t.node||process.env.WF_NODE_ID||"local",o=new ct({nodeId:n}).list({workflowId:e,limit:Number(t.limit)});if(!o.length){console.log(T.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of o){let r=s.history.at(-1),i=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?T.cyan:s.status==="failed"?T.red:T.green;console.log(` ${T.dim(s.id.slice(0,8))} ${T.bold(s.workflowId)} ${a(i)} ${T.dim(s.status)}`),console.log(` ${T.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${T.dim("home: ")} ${s.homeNode}`),console.log(` ${T.dim("updated: ")} ${s.updatedAt}`),r&&console.log(` ${T.dim("last: ")} ${r.nodeId} (${r.status})`)}console.log(),console.log(T.dim(` ${o.length} run${o.length===1?"":"s"}.`))});be.command("run <id>").description("manually trigger a workflow (trigger.manual by default; add --force for any)").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,t)=>{let n={};if(t.input)try{n=JSON.parse(t.input)}catch{console.log(T.red(" --input must be valid JSON")),process.exit(1)}let o=`${String(t.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(e)}/run`;try{let s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:n,force:!!t.force})});if(!s.ok){let i=await s.text();console.log(T.red(` run failed (${s.status}): ${i.slice(0,300)}`)),s.status===409&&console.log(T.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let r=await s.json();console.log(T.green(` \u2713 run started: ${r.runId||"(unknown id)"}${r.force?T.dim(` (forced, source=${r.source})`):""}`))}catch(s){console.log(T.red(` request to daemon failed: ${s.message}`)),process.exit(1)}});be.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,t)=>{let n=t.node||process.env.WF_NODE_ID||"local";new ct({nodeId:n}).setStatus(e,"paused")||(console.log(T.yellow(` no such run: ${e}`)),process.exit(1)),console.log(T.green(` \u2713 paused ${e}`))});be.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,t)=>{let n=t.node||process.env.WF_NODE_ID||"local";new ct({nodeId:n}).setStatus(e,"running")||(console.log(T.yellow(` no such run: ${e}`)),process.exit(1)),console.log(T.green(` \u2713 resumed ${e}`))});be.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,t)=>{let n=t.node||process.env.WF_NODE_ID||"local";new ct({nodeId:n}).setStatus(e,"canceled")||(console.log(T.yellow(` no such run: ${e}`)),process.exit(1)),console.log(T.green(` \u2713 canceled ${e}`))});import{Command as uo}from"commander";import L from"chalk";var ot=new uo().name("actor").description("manage actors (humans) that can be assigned to workflow userTasks");ot.command("add").description("add a new actor").argument("<id>","actor id (e.g. alice; 'actor:' prefix is added if missing)").requiredOption("--name <name>","human-readable name").option("--email <email>","email address").option("--telegram <handle>","Telegram user id (numeric)").option("--whatsapp <phone>","WhatsApp phone in E.164 (no +)").option("--slack <memberId>","Slack member id").option("--discord <userId>","Discord user id").option("--timezone <tz>","IANA timezone, e.g. Africa/Tunis").option("--prefer <channel>","mark this channel as preferred for task notifications","").action((e,t)=>{let n=e.startsWith("actor:")?e:`actor:${e}`,o=new fe;if(o.getActor(n)){console.error(L.red(` actor "${n}" already exists. Use 'actor remove' first.`)),process.exitCode=1;return}let s=[],r=(c,l)=>{l&&s.push({channel:c,handle:l,preferredForTasks:t.prefer===c||void 0})};if(r("telegram",t.telegram),r("whatsapp",t.whatsapp),r("slack",t.slack),r("discord",t.discord),t.email&&r("email",t.email),s.length===0){console.error(L.red(" at least one channel handle is required (--telegram, --whatsapp, --slack, --discord, --email)")),process.exitCode=1;return}let i={id:n,name:t.name,email:t.email,channels:s,timezone:t.timezone},a=o.saveActor(i);console.log(L.green(` \u2713 actor "${a.id}" saved (${a.channels.length} channel${a.channels.length===1?"":"s"})`))});ot.command("list").description("list all actors").action(()=>{let t=new fe().listActors();if(!t.length){console.log(L.dim(" no actors yet. Try: agentx actor add alice --name 'Alice' --telegram 12345"));return}console.log();for(let n of t){let o=n.channels.map(s=>`${s.channel}:${s.handle}${s.preferredForTasks?"*":""}`).join(", ");console.log(` ${L.cyan(n.id.padEnd(24))} ${L.bold(n.name)}`),console.log(` ${L.dim(o)}`)}console.log(),console.log(L.dim(` ${t.length} actor${t.length===1?"":"s"}. * = preferred for tasks.`))});ot.command("show").description("print full JSON for an actor").argument("<id>","actor id (with or without 'actor:' prefix)").action(e=>{let t=e.startsWith("actor:")?e:`actor:${e}`,o=new fe().getActor(t);if(!o){console.error(L.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(JSON.stringify(o,null,2))});ot.command("remove").alias("rm").description("remove an actor (does not clean up role memberships)").argument("<id>","actor id").action(e=>{let t=e.startsWith("actor:")?e:`actor:${e}`;if(!new fe().deleteActor(t)){console.error(L.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(L.green(` \u2713 actor "${t}" removed`))});var Je=new uo().name("role").description("manage roles (groups of actors) for workflow userTasks");Je.command("create").description("create a new role").argument("<id>","role id (e.g. reviewers; 'role:' prefix is added if missing)").requiredOption("--name <name>","human-readable name").option("--strategy <strategy>","first-available | round-robin | all | manager-of","first-available").action((e,t)=>{let n=e.startsWith("role:")?e:`role:${e}`,o=new fe;if(o.getRole(n)){console.error(L.red(` role "${n}" already exists`)),process.exitCode=1;return}let s=t.strategy,r=o.saveRole({id:n,name:t.name,members:[],assignmentStrategy:s,rotationCursor:0});console.log(L.green(` \u2713 role "${r.id}" created (strategy: ${r.assignmentStrategy})`))});Je.command("grant").description("add an actor (or nested role) to a role's members").argument("<roleId>","target role").argument("<memberId>","actor:<id> or role:<id>").action((e,t)=>{let n=e.startsWith("role:")?e:`role:${e}`,o=new fe,s=o.getRole(n);if(!s){console.error(L.red(` role "${n}" not found`)),process.exitCode=1;return}let r=t.startsWith("actor:")?{actor:t}:t.startsWith("role:")?{role:t}:null;if(!r){console.error(L.red(" member must be 'actor:<id>' or 'role:<id>'")),process.exitCode=1;return}if(s.members.some(a=>JSON.stringify(a)===JSON.stringify(r))){console.log(L.dim(" already a member"));return}let i=o.saveRole({...s,members:[...s.members,r]});console.log(L.green(` \u2713 ${t} granted to ${n} (${i.members.length} member${i.members.length===1?"":"s"})`))});Je.command("revoke").description("remove an actor or nested role from a role").argument("<roleId>","target role").argument("<memberId>","actor:<id> or role:<id>").action((e,t)=>{let n=e.startsWith("role:")?e:`role:${e}`,o=new fe,s=o.getRole(n);if(!s){console.error(L.red(` role "${n}" not found`)),process.exitCode=1;return}let r=s.members.length,i=s.members.filter(a=>"actor"in a?a.actor!==t:a.role!==t);if(i.length===r){console.log(L.dim(` "${t}" was not a member`));return}o.saveRole({...s,members:i}),console.log(L.green(` \u2713 ${t} revoked from ${n}`))});Je.command("list").description("list all roles with member counts").action(()=>{let t=new fe().listRoles();if(!t.length){console.log(L.dim(" no roles yet. Try: agentx role create reviewers --name 'Reviewers'"));return}console.log();for(let n of t){console.log(` ${L.cyan(n.id.padEnd(24))} ${L.bold(n.name)} ${L.dim(n.assignmentStrategy)}`);for(let o of n.members){let s="actor"in o?o.actor:o.role;console.log(` ${L.dim("\u2022")} ${s}`)}}console.log(),console.log(L.dim(` ${t.length} role${t.length===1?"":"s"}.`))});Je.command("show").description("print full JSON for a role, including resolved members").argument("<id>","role id").action(e=>{let t=e.startsWith("role:")?e:`role:${e}`,n=new fe,o=n.getRole(t);if(!o){console.error(L.red(` role "${t}" not found`)),process.exitCode=1;return}let s=n.resolveMembers({kind:"role",id:o.id});console.log(JSON.stringify({...o,_resolvedActors:s},null,2))});import dn from"chalk";import{Command as yr}from"commander";var ho=new yr().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{e.stdio!==!1?await bn():(ve.error("Only stdio transport is currently supported."),ve.info(`Usage: ${dn.green("agentx serve --stdio")} or configure in your MCP client.`),ve.break(),ve.info("Add to Claude Code:"),ve.info(dn.dim(" claude mcp add agentx -- npx agentx serve --stdio")),ve.break(),ve.info("Add to Cursor/MCP config:"),ve.info(dn.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(t){Cn(t)}});import{Command as wr}from"commander";import oe from"chalk";var gn=new wr().name("bench").description("benchmark harnesses (context strategies, ...)");gn.command("context").description("run the same message under 'layered' vs 'planner' strategies and compare").requiredOption("--agent <id>","agent id to send the message to").requiredOption("--message <text>","the user message to bench").option("--channel <name>","channel label for the request context","bench").option("--chat-id <id>","chatId for session scoping","bench-harness").option("--sender <name>","sender label for the request context","bench").option("--runs <n>","number of runs per strategy (averaged)","1").option("--preview <chars>","how many response chars to print","280").option("--url <url>","daemon URL override (default: from agentx.json)").action(async e=>{let t=Math.max(1,parseInt(e.runs,10)||1),n=Math.max(0,parseInt(e.preview,10)||280),o=e.url||vr();console.log(),console.log(oe.bold(" Context-strategy benchmark")),console.log(oe.dim(` agent=${e.agent}, channel=${e.channel}, chatId=${e.chatId}, runs=${t}`)),console.log(oe.dim(` daemon=${o}`)),console.log();let s=await fo(o,"layered",e,t),r=await fo(o,"planner",e,t);br(s,r,n)});async function fo(e,t,n,o){let s=0,r=0,i=0,a=0,c=0,l=0,d=0,p="",g;for(let f=0;f<o;f++){let y=Date.now();try{let b=await(await fetch(`${e}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:n.agent,message:n.message,contextStrategy:t,context:{channel:n.channel,chatId:n.chatId,sender:n.sender}}),signal:AbortSignal.timeout(6e5)})).json();if(b.error){d++,g=b.error;continue}s+=b.duration??Date.now()-y,r+=b.usage?.inputTokens??0,i+=b.usage?.outputTokens??0,a+=b.usage?.cacheReadTokens??0,c+=b.usage?.cacheCreateTokens??0,l+=$r(b.usage),p=b.content??""}catch(w){d++,g=w.message??String(w)}}let u=o-d||1;return{strategy:t,runs:o,errors:d,avgDurationMs:Math.round(s/u),avgInput:Math.round(r/u),avgOutput:Math.round(i/u),avgCacheRead:Math.round(a/u),avgCacheCreate:Math.round(c/u),avgTotalInput:Math.round((r+a+c)/u),avgCost:l/u,lastResponse:p,lastError:g}}function $r(e){if(!e)return 0;let t=3/1e6,n=15/1e6,o=.3/1e6,s=3.75/1e6;return(e.inputTokens??0)*t+(e.outputTokens??0)*n+(e.cacheReadTokens??0)*o+(e.cacheCreateTokens??0)*s}function br(e,t,n){let o=(a,c)=>a.length>=c?a:a+" ".repeat(c-a.length),s=a=>a.toLocaleString();console.log(oe.bold(" "+o("metric",22)+o("layered",18)+o("planner",18)+"delta")),console.log(oe.dim(" "+"-".repeat(74)));let r=[["input tokens",e.avgInput,t.avgInput,s],["output tokens",e.avgOutput,t.avgOutput,s],["cache read",e.avgCacheRead,t.avgCacheRead,s],["cache create",e.avgCacheCreate,t.avgCacheCreate,s],["total input",e.avgTotalInput,t.avgTotalInput,s],["est. cost ($)",e.avgCost,t.avgCost,a=>a.toFixed(4)],["duration (ms)",e.avgDurationMs,t.avgDurationMs,s]];for(let[a,c,l,d]of r){let p=l-c,g=c===0?0:p/c*100,u=p===0?oe.dim("\xB10"):p<0?oe.green(`${d(p)} (${g.toFixed(0)}%)`):oe.red(`+${d(p)} (+${g.toFixed(0)}%)`);console.log(" "+o(a,22)+o(d(c),18)+o(d(l),18)+u)}console.log(oe.dim(" "+"-".repeat(74))),(e.errors>0||t.errors>0)&&console.log(oe.yellow(` errors: layered=${e.errors} (${e.lastError??""}), planner=${t.errors} (${t.lastError??""})`)),console.log(),n>0&&(console.log(oe.bold(" Response preview (last run of each):")),console.log(oe.dim(" layered:")),console.log(" "+yo(e.lastResponse,n).split(`
842
- `).join(`
843
- `)),console.log(oe.dim(" planner:")),console.log(" "+yo(t.lastResponse,n).split(`
844
- `).join(`
845
- `)),console.log());let i=t.avgTotalInput-e.avgTotalInput;if(i<0){let a=e.avgTotalInput===0?0:Math.abs(i/e.avgTotalInput)*100;console.log(oe.green(` Planner saved ${s(Math.abs(i))} input tokens/run (${a.toFixed(0)}% less).`))}else i>0&&console.log(oe.yellow(` Planner used ${s(i)} MORE input tokens \u2014 investigate before enabling.`));console.log()}function yo(e,t){return e?e.length>t?e.slice(0,t)+"\u2026":e:"(empty)"}function vr(){try{let e=U(),[t,n]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${n||"19900"}`}catch{return"http://127.0.0.1:19900"}}import{Command as kr}from"commander";import Q from"chalk";var Te=new kr().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Te.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let n=(await bt("/whatsapp/chats")).chats??[];if(e.group&&(n=n.filter(o=>o.isGroup)),e.dm&&(n=n.filter(o=>!o.isGroup)),e.format==="json"){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(Q.dim(" no chats cached yet"));return}console.log(),console.log(Q.bold(` ${n.length} chat${n.length===1?"":"s"}`)),console.log();for(let o of n){let s=o.isGroup?Q.cyan("group"):Q.dim("dm"),r=o.lastMessageAt?new Date(o.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${o.name.padEnd(30)} ${Q.dim(o.jid.padEnd(40))} ${Q.dim(r)}`)}console.log()}catch(t){st(t)}});Te.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let n=(await bt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(Q.dim(" no contacts cached yet"));return}console.log(),console.log(Q.bold(` ${n.length} contact${n.length===1?"":"s"}`)),console.log();for(let o of n){let s=(o.name||o.pushName||o.phone||o.jid).padEnd(30),r=o.phone?`+${o.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Q.dim(r)} ${Q.dim(o.jid)}`)}console.log()}catch(t){st(t)}});Te.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let t={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(t.agent=e.agent);let n=await mn("/whatsapp/ingest",t);pn(n,!!e.dryRun)}catch(t){st(t)}});Te.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,t)=>{try{let n={dryRun:!!t.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};t.agent&&(n.agent=t.agent);let o=await mn("/whatsapp/ingest",n);pn(o,!!t.dryRun)}catch(n){st(n)}});Te.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,t)=>{try{let n={dryRun:!!t.dryRun,force:!0,onlyJid:e};t.agent&&(n.agent=t.agent),t.messages&&(n.forceMode="messages");let o=await mn("/whatsapp/ingest",n);pn(o,!!t.dryRun)}catch(n){st(n)}});Te.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await bt("/whatsapp/state"),t=await bt("/whatsapp/chats"),n=await bt("/whatsapp/contacts");console.log(),console.log(Q.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${t.chats?.length??0}`),console.log(` cached contacts: ${n.contacts?.length??0}`),console.log()}catch(e){st(e)}});function pn(e,t){if(console.log(),console.log(Q.bold(t?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Q.yellow(` errors: ${e.errors.length}`));for(let n of e.errors.slice(0,5))console.log(Q.yellow(` - [${n.kind}] ${n.jid}: ${n.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(Q.dim(" would-be entries:"));for(let n of e.dryRunEntries.slice(0,10))console.log(Q.dim(` - ${n.id} (${n.source}, ${n.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Q.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function wo(){try{let e=U(),[t,n]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${n||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function bt(e){let t=await fetch(`${wo()}${e}`,{signal:AbortSignal.timeout(1e4)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}async function mn(e,t){let n=await fetch(`${wo()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(6e5)}),o=await n.json().catch(()=>({}));if(!n.ok)throw new Error(o.error||`HTTP ${n.status}`);return o}function st(e){console.error(Q.red(` ${e.message||e}`)),process.exit(1)}import{Command as xr}from"commander";import X from"chalk";import{writeFileSync as Sr,mkdirSync as Ar,existsSync as Nt,readFileSync as $o,appendFileSync as bo}from"fs";import{resolve as rt,dirname as xo}from"path";import{homedir as hn}from"os";var So=new xr().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-2MDELQLX.js"),n=await t(),o=String(e.shell||"zsh").toLowerCase(),s;switch(o){case"zsh":s=Rr(n);break;case"bash":s=Dr(n);break;case"fish":s=Pr(n);break;default:console.error(X.red(`unsupported shell: ${o}`)),console.error(X.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?rt(String(e.output)):Cr(o);Ar(xo(r),{recursive:!0}),Sr(r,s),console.log(X.green(`\u2713 Wrote ${o} completion to:`)),console.log(` ${r}`),console.log(),jr(o,r,!!e.yes)});function Cr(e){let t=hn();switch(e){case"zsh":return rt(t,".zsh","completions","_agentx");case"bash":return rt(t,".bash_completion.d","agentx.bash");case"fish":return rt(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function jr(e,t,n){if(e==="zsh"){let o=rt(hn(),".zshrc"),s=xo(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Nt(o)?$o(o,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(X.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(n&&Nt(o)){let d=["","# agentx completion"];c&&d.push(r),l&&d.push(i),bo(o,d.join(`
846
- `)+`
847
- `),console.log(X.green("\u2713 Patched ~/.zshrc")),console.log(X.dim("Reload your shell: exec zsh"));return}console.log(X.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(X.cyan(` ${r}`)),l&&console.log(X.cyan(` ${i}`)),console.log(),console.log(X.dim("Then reload: exec zsh")),console.log(X.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let o=rt(hn(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Nt(o)?$o(o,"utf-8"):"").includes(t)){console.log(X.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(n&&Nt(o)){bo(o,`
848
- # agentx completion
849
- ${s}
850
- `),console.log(X.green("\u2713 Patched ~/.bashrc")),console.log(X.dim("Reload your shell: exec bash"));return}console.log(X.dim("Add this to ~/.bashrc:")),console.log(X.cyan(` ${s}`)),console.log(),console.log(X.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(X.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function ie(e){return e._name||e.name()||""}function De(e){return e.commands.filter(t=>{let n=ie(t);return!(!n||n==="help"||t._hidden)})}function vt(e){return e.options.filter(t=>!t.hidden)}function Rr(e){let t=[];return t.push("#compdef agentx"),t.push(""),Ao(e,[],t),t.push("compdef _agentx_root_completion agentx"),t.push(""),t.join(`
851
- `)}function vo(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Ao(e,t,n){let o=De(e),r=vt(e).map(Or).filter(c=>!!c),i=vo(t);if(n.push(`${i}() {`),n.push(" local -a commands"),n.push(" local -a options"),n.push(" "),r.length===0&&o.length===0){n.push(" return 0"),n.push("}"),n.push("");return}let a=[];for(let c of r)a.push(c);if(o.length>0){let c=o.map(Tr).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}n.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;n.push(`${a[c]}${l?"":" \\"}`)}if(o.length>0){n.push(""),n.push(" case $state in"),n.push(" (args)"),n.push(" case $line[1] in");for(let c of o){let l=vo([...t,ie(c)]);n.push(` (${ie(c)}) ${l} ;;`)}n.push(" esac"),n.push(" ;;"),n.push(" esac")}n.push("}"),n.push("");for(let c of o)Ao(c,[...t,ie(c)],n)}function Ir(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Er(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Or(e){let t=e.short||void 0,n=e.long||void 0;if(!t&&!n)return null;let o=Ir(e.description||"");return t&&n?` "(${n} ${t})"{${n},${t}}"[${o}]"`:` "${n||t}[${o}]"`}function Tr(e){let t=Er(e.description()||"");return`'${ie(e)}[${t}]'`}function Dr(e){let t=De(e),n=[];n.push("# bash completion for agentx"),n.push("_agentx_complete() {"),n.push(" local cur prev words cword"),n.push(" COMPREPLY=()"),n.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),n.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),n.push(""),n.push(` local top="${t.map(ie).join(" ")}"`),n.push(""),n.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),n.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),n.push(" return 0"),n.push(" fi"),n.push(""),n.push(' local cmd="${COMP_WORDS[1]}"'),n.push(' local sub2="${COMP_WORDS[2]:-}"'),n.push(' case "$cmd" in');for(let o of t){let s=De(o).map(ie),r=ko(o);if(n.push(` ${ie(o)})`),s.length>0){n.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),n.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${r}" -- "$cur") )`),n.push(" return 0"),n.push(" fi"),n.push(' case "$sub2" in');for(let i of De(o)){let a=ko(i);n.push(` ${ie(i)})`),n.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),n.push(" return 0"),n.push(" ;;")}n.push(" esac")}else n.push(` COMPREPLY=( $(compgen -W "${r}" -- "$cur") )`);n.push(" ;;")}return n.push(" esac"),n.push("}"),n.push(""),n.push("complete -F _agentx_complete agentx"),n.push(""),n.join(`
852
- `)}function ko(e){let t=[];for(let n of vt(e))n.long&&t.push(n.long),n.short&&t.push(n.short);return t.join(" ")}function Pr(e){let t=[];t.push("# fish completion for agentx"),t.push(""),t.push("complete -c agentx -f"),t.push(""),t.push("# top-level commands");for(let n of De(e)){let o=fn(n.description()||"");t.push(`complete -c agentx -n "__fish_use_subcommand" -a "${ie(n)}" -d "${o}"`)}t.push("");for(let n of vt(e)){let o=un(n,["__fish_use_subcommand"]);o&&t.push(o)}t.push("");for(let n of De(e)){let o=ie(n);t.push(`# ${o}`);for(let s of vt(n)){let r=un(s,[`__fish_seen_subcommand_from ${o}`]);r&&t.push(r)}for(let s of De(n)){let r=fn(s.description()||"");t.push(`complete -c agentx -n "__fish_seen_subcommand_from ${o}; and not __fish_seen_subcommand_from ${De(n).map(ie).join(" ")}" -a "${ie(s)}" -d "${r}"`);for(let i of vt(s)){let a=un(i,[`__fish_seen_subcommand_from ${ie(s)}`]);a&&t.push(a)}}t.push("")}return t.join(`
853
- `)}function fn(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function un(e,t){let n=e.short?e.short.replace(/^-/,""):"",o=e.long?e.long.replace(/^--/,""):"";if(!n&&!o)return null;let s=fn(e.description||""),i=["complete -c agentx",t.map(a=>`-n "${a}"`).join(" ")];return n&&i.push(`-s ${n}`),o&&i.push(`-l ${o}`),i.push(`-d "${s}"`),i.join(" ")}async function dl(){let e=await jn(),t=new Nr().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");return t.addCommand(ye).addCommand(Wn).addCommand(Dn).addCommand(pt).addCommand(Ct).addCommand(Ue).addCommand(Xe).addCommand(Oe).addCommand(mt).addCommand(Ze).addCommand(ut).addCommand(xe).addCommand(Yt).addCommand(Gt).addCommand(Ne).addCommand(ft).addCommand(et).addCommand(K).addCommand(Pt).addCommand($t).addCommand(be).addCommand(ot).addCommand(Je).addCommand(gt).addCommand(Mn).addCommand(ho).addCommand(gn).addCommand(Te).addCommand(So),t}export{dl as a};
854
- //# sourceMappingURL=chunk-BLUXL6HR.js.map