agentix-cli 0.52.0 → 0.52.1

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 (99) hide show
  1. package/dist/{App-QVNQ5BQK.js → App-X6FGYBLX.js} +2 -2
  2. package/dist/{ChatApp-CC57XC23.js → ChatApp-XMUOXQ2M.js} +2 -2
  3. package/dist/{agent-ILH6ANOM.js → agent-KKVMU3VB.js} +2 -2
  4. package/dist/{board-dashboard-WG4ZZV4A.js → board-dashboard-KETIFTBD.js} +4 -4
  5. package/dist/{chunk-SRCXUZM2.js → chunk-3IUU4YFI.js} +2 -2
  6. package/dist/chunk-3IUU4YFI.js.map +1 -0
  7. package/dist/chunk-64UYAWAK.js +150 -0
  8. package/dist/chunk-64UYAWAK.js.map +1 -0
  9. package/dist/{chunk-CAA546XN.js → chunk-6BXKZY76.js} +2 -2
  10. package/dist/{chunk-6HAZ6YWI.js → chunk-76NNONUJ.js} +2 -2
  11. package/dist/{chunk-VMS3HVTT.js → chunk-7BQQWI4T.js} +2 -2
  12. package/dist/{chunk-XZTR5MBJ.js → chunk-7M7VJMGP.js} +2 -2
  13. package/dist/{chunk-H2TWRZC2.js → chunk-7NF45XCM.js} +2 -2
  14. package/dist/{chunk-NTG5ZXRI.js → chunk-7PK32QT5.js} +3 -3
  15. package/dist/{chunk-UL4E2CV4.js → chunk-AKAM4BNC.js} +13 -13
  16. package/dist/{chunk-U67EG5IF.js → chunk-AWRRBNWQ.js} +2 -2
  17. package/dist/{chunk-WDQ3BPFS.js → chunk-B5UA3X6E.js} +2 -2
  18. package/dist/{chunk-PSDCRZZM.js → chunk-E57WKMRR.js} +2 -2
  19. package/dist/{chunk-2KQTE4XI.js → chunk-H7R3F2CO.js} +2 -2
  20. package/dist/{chunk-JQR3NTHI.js → chunk-MHBUAU2B.js} +2 -2
  21. package/dist/{chunk-QP6XNTBB.js → chunk-NKSCUCVZ.js} +2 -2
  22. package/dist/{chunk-KFALP5NO.js → chunk-QDPLR3SB.js} +2 -2
  23. package/dist/{chunk-F7WY24UZ.js → chunk-QZ4M2KAC.js} +2 -2
  24. package/dist/{chunk-YE2BUU3Z.js → chunk-WCNKTV6G.js} +2 -2
  25. package/dist/{chunk-V7XZN3MQ.js → chunk-XOUIZBAQ.js} +2 -2
  26. package/dist/{chunk-ROCUOXCW.js → chunk-YPPTPBBV.js} +2 -2
  27. package/dist/{chunk-BNVF66YL.js → chunk-YS3Z2Z64.js} +2 -2
  28. package/dist/cli.js +1 -1
  29. package/dist/client-AVQSLPIZ.js +2 -0
  30. package/dist/{config-TVW7UCKG.js → config-FGCJVXYX.js} +2 -2
  31. package/dist/config-mutator-5JSG3CHW.js +2 -0
  32. package/dist/doctor-VITHTLEC.js +2 -0
  33. package/dist/index.d.ts +24 -1
  34. package/dist/index.js +1 -1
  35. package/dist/program-MNFDOQGQ.js +2 -0
  36. package/dist/{promote-4T64VW5K.js → promote-NBFF7ZIW.js} +2 -2
  37. package/dist/query-XCXR57IV.js +2 -0
  38. package/dist/{registry-E4QUXHMQ.js → registry-5ZP3ZNSH.js} +2 -2
  39. package/dist/{request-planner-BRLDCYU5.js → request-planner-ZEXFARZE.js} +2 -2
  40. package/dist/{review-candidates-QWW5PDUU.js → review-candidates-F2HNH2TZ.js} +2 -2
  41. package/dist/{routing-DP6S7OJL.js → routing-XSRZ7V23.js} +2 -2
  42. package/dist/schedule-tool-AKCVLCWK.js +2 -0
  43. package/dist/scheduler-BEGZJWJU.js +2 -0
  44. package/dist/{seat-3KUNRM5Z.js → seat-IPDLEUI5.js} +2 -2
  45. package/dist/{select-ILXHYJGD.js → select-BYOX63CR.js} +2 -2
  46. package/dist/{tool-SF3BCY55.js → tool-WW4YCMSP.js} +2 -2
  47. package/dist/wiki-IVJJQUKB.js +2 -0
  48. package/package.json +1 -1
  49. package/dist/chunk-SRCXUZM2.js.map +0 -1
  50. package/dist/chunk-YEV6W34S.js +0 -150
  51. package/dist/chunk-YEV6W34S.js.map +0 -1
  52. package/dist/client-I7GAAM3T.js +0 -2
  53. package/dist/config-mutator-JHM53P5A.js +0 -2
  54. package/dist/doctor-CXFMV6PT.js +0 -2
  55. package/dist/program-UXJWH5JG.js +0 -2
  56. package/dist/query-6IKL52WT.js +0 -2
  57. package/dist/schedule-tool-TPJ6GR47.js +0 -2
  58. package/dist/scheduler-7QPG6OTY.js +0 -2
  59. package/dist/wiki-WETANN3W.js +0 -2
  60. /package/dist/{App-QVNQ5BQK.js.map → App-X6FGYBLX.js.map} +0 -0
  61. /package/dist/{ChatApp-CC57XC23.js.map → ChatApp-XMUOXQ2M.js.map} +0 -0
  62. /package/dist/{agent-ILH6ANOM.js.map → agent-KKVMU3VB.js.map} +0 -0
  63. /package/dist/{board-dashboard-WG4ZZV4A.js.map → board-dashboard-KETIFTBD.js.map} +0 -0
  64. /package/dist/{chunk-CAA546XN.js.map → chunk-6BXKZY76.js.map} +0 -0
  65. /package/dist/{chunk-6HAZ6YWI.js.map → chunk-76NNONUJ.js.map} +0 -0
  66. /package/dist/{chunk-VMS3HVTT.js.map → chunk-7BQQWI4T.js.map} +0 -0
  67. /package/dist/{chunk-XZTR5MBJ.js.map → chunk-7M7VJMGP.js.map} +0 -0
  68. /package/dist/{chunk-H2TWRZC2.js.map → chunk-7NF45XCM.js.map} +0 -0
  69. /package/dist/{chunk-NTG5ZXRI.js.map → chunk-7PK32QT5.js.map} +0 -0
  70. /package/dist/{chunk-UL4E2CV4.js.map → chunk-AKAM4BNC.js.map} +0 -0
  71. /package/dist/{chunk-U67EG5IF.js.map → chunk-AWRRBNWQ.js.map} +0 -0
  72. /package/dist/{chunk-WDQ3BPFS.js.map → chunk-B5UA3X6E.js.map} +0 -0
  73. /package/dist/{chunk-PSDCRZZM.js.map → chunk-E57WKMRR.js.map} +0 -0
  74. /package/dist/{chunk-2KQTE4XI.js.map → chunk-H7R3F2CO.js.map} +0 -0
  75. /package/dist/{chunk-JQR3NTHI.js.map → chunk-MHBUAU2B.js.map} +0 -0
  76. /package/dist/{chunk-QP6XNTBB.js.map → chunk-NKSCUCVZ.js.map} +0 -0
  77. /package/dist/{chunk-KFALP5NO.js.map → chunk-QDPLR3SB.js.map} +0 -0
  78. /package/dist/{chunk-F7WY24UZ.js.map → chunk-QZ4M2KAC.js.map} +0 -0
  79. /package/dist/{chunk-YE2BUU3Z.js.map → chunk-WCNKTV6G.js.map} +0 -0
  80. /package/dist/{chunk-V7XZN3MQ.js.map → chunk-XOUIZBAQ.js.map} +0 -0
  81. /package/dist/{chunk-ROCUOXCW.js.map → chunk-YPPTPBBV.js.map} +0 -0
  82. /package/dist/{chunk-BNVF66YL.js.map → chunk-YS3Z2Z64.js.map} +0 -0
  83. /package/dist/{client-I7GAAM3T.js.map → client-AVQSLPIZ.js.map} +0 -0
  84. /package/dist/{config-TVW7UCKG.js.map → config-FGCJVXYX.js.map} +0 -0
  85. /package/dist/{config-mutator-JHM53P5A.js.map → config-mutator-5JSG3CHW.js.map} +0 -0
  86. /package/dist/{doctor-CXFMV6PT.js.map → doctor-VITHTLEC.js.map} +0 -0
  87. /package/dist/{program-UXJWH5JG.js.map → program-MNFDOQGQ.js.map} +0 -0
  88. /package/dist/{promote-4T64VW5K.js.map → promote-NBFF7ZIW.js.map} +0 -0
  89. /package/dist/{query-6IKL52WT.js.map → query-XCXR57IV.js.map} +0 -0
  90. /package/dist/{registry-E4QUXHMQ.js.map → registry-5ZP3ZNSH.js.map} +0 -0
  91. /package/dist/{request-planner-BRLDCYU5.js.map → request-planner-ZEXFARZE.js.map} +0 -0
  92. /package/dist/{review-candidates-QWW5PDUU.js.map → review-candidates-F2HNH2TZ.js.map} +0 -0
  93. /package/dist/{routing-DP6S7OJL.js.map → routing-XSRZ7V23.js.map} +0 -0
  94. /package/dist/{schedule-tool-TPJ6GR47.js.map → schedule-tool-AKCVLCWK.js.map} +0 -0
  95. /package/dist/{scheduler-7QPG6OTY.js.map → scheduler-BEGZJWJU.js.map} +0 -0
  96. /package/dist/{seat-3KUNRM5Z.js.map → seat-IPDLEUI5.js.map} +0 -0
  97. /package/dist/{select-ILXHYJGD.js.map → select-BYOX63CR.js.map} +0 -0
  98. /package/dist/{tool-SF3BCY55.js.map → tool-WW4YCMSP.js.map} +0 -0
  99. /package/dist/{wiki-WETANN3W.js.map → wiki-IVJJQUKB.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as gc,b as Wn,g as mc}from"./chunk-KFALP5NO.js";import{a as uo,b as oc,f as So,i as qn,j as sc,k as ic,l as Qs,m as lc,o as dc}from"./chunk-BNVF66YL.js";import{a as rc,c as ac,d as cc}from"./chunk-Z3IP66SL.js";import{a as tc,c as nc}from"./chunk-CAA546XN.js";import{a as Us,b as Wr}from"./chunk-RKPAVWXF.js";import{a as mt}from"./chunk-GV7S5BAX.js";import{e as Nr}from"./chunk-GSX4NK2N.js";import{c as Rr}from"./chunk-SZDACK6O.js";import{$ as za,A as _a,B as Da,C as Pa,D as Yt,E as Js,F as _n,G as Ma,H as xo,I as La,J as Gs,K as Hs,L as Fa,M as Ua,N as Vt,O as Dn,P as qa,Q as Wa,R as Ba,S as Ja,T as ut,U as ft,V as Ga,W as Ha,X as Ce,Y as Pn,Z as Kt,_ as zs,a as Kr,aa as Mn,b as Xr,ba as Ln,ca as Ka,da as Ks,ea as Qa,fa as Fn,ga as ht,h as oa,ha as Un,i as zt,ia as Xs,j as jn,ja as Za,k as sa,ka as ec,l as ia,m as ra,n as aa,o as ya,p as wa,q as xa,r as Aa,s as Ta,t as Oa,u as Ia,v as ja,w as Bs,x as Ca,y as Na,z as Ra}from"./chunk-NTG5ZXRI.js";import{E as Ya,F as Ys,G as Va,H as Vs,V as io,X as Xa,k as ba,n as $a,u as ka,v as va}from"./chunk-YE2BUU3Z.js";import{a as Qr,d as Zr,e as ea}from"./chunk-QP6XNTBB.js";import{a as Ws,b as Cn,c as Nn,d as ca,e as la,f as da,i as ga,j as ma,k as pa,l as ua,o as Rn,q as fa,r as ha}from"./chunk-S7CVSKOX.js";import{a as ta,p as na}from"./chunk-WDQ3BPFS.js";import{a as Sa,b as Ea}from"./chunk-L53FTKEP.js";import{E as Ur,O as qr,h as Tr,q as Or,v as Ms,w as jr,y as vo}from"./chunk-YEV6W34S.js";import{b as Gt,c as dt,d as On,e as In,f as gt,g as Cr,h as Jo,i as Ht}from"./chunk-U67EG5IF.js";import{a as Ar}from"./chunk-N6EWZGIX.js";import{e as Mr,f as Fs,k as Lr}from"./chunk-WP6KLXTP.js";import{b as lt}from"./chunk-DP7RTNDM.js";import{a as qs,e as Br,f as Jr,h as Gr,i as Hr,k as zr,l as Yr,m as Vr}from"./chunk-F7WY24UZ.js";import{a as Ir,k as Pr}from"./chunk-V7XZN3MQ.js";import{f as _r,g as Dr,h as Ls}from"./chunk-76Z4VHDX.js";import{b as he,c as Ae,d as pt,e as Fr}from"./chunk-VMS3HVTT.js";import{h as Er}from"./chunk-DWADWDMU.js";import{a as Ps}from"./chunk-XZTR5MBJ.js";import{b as ko,d as Tn}from"./chunk-ROCUOXCW.js";import{b as ct,d as Sr}from"./chunk-2GIDVZ4H.js";import{a as Ds,b as mr,c as cg,d as En,e as pr,f as wr,g as dg,h as br,i as gg,m as at,n as kr,o as vr,s as xr,v as so,w as Jt}from"./chunk-JQR3NTHI.js";import{a as po,b as rt,e as fr,f as Bt}from"./chunk-72SZI2UW.js";import{a as $r,b as mg}from"./chunk-FX3D7YON.js";import{a as mo,b as ag}from"./chunk-7I7IEX4S.js";import{l as ur,m as R,n as An,p as re}from"./chunk-SRCXUZM2.js";import{g as hr,k as yr,l as lg}from"./chunk-RGDKHYY2.js";import{Command as pg}from"commander";var pc=new pg().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Xr({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});re();import{Command as ug}from"commander";import{execFileSync as ro}from"node:child_process";import{cpSync as uc,existsSync as ei,mkdirSync as Zs,mkdtempSync as fg,rmSync as hg,writeFileSync as fc}from"node:fs";import{dirname as hc,join as Me}from"node:path";import{homedir as Bn,release as yg,tmpdir as wg}from"node:os";import{setTimeout as bg}from"node:timers/promises";function Jn(){let e=ca(process.platform,process.arch,yg());if(e)throw new Error(e)}function Xt(){return`gui/${process.getuid()}/${Ws}`}function yt(){return Me(Bn(),"Library/LaunchAgents",`${Ws}.plist`)}async function yc(){try{ro("launchctl",["bootout",Xt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ro("launchctl",["print",Xt()],{stdio:"pipe"})}catch{return}await bg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function wc(){if(!ei(yt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ro("launchctl",["print",Xt()],{stdio:"pipe"})}catch{e=!1}e||ro("launchctl",["bootstrap",`gui/${process.getuid()}`,yt()],{stdio:"pipe"}),ro("launchctl",["kickstart",Xt()],{stdio:"pipe"})}function $g(){let e=ua();if(e&&ei(Me(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var wt=new ug("desktop").description("install and control the macOS desktop assistant");wt.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Jn();let o=R(),t=la(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=$g(),r=Me(Bn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Me(r,Cn)}
1
+ import{a as gc,b as Wn,g as mc}from"./chunk-QDPLR3SB.js";import{a as uo,b as oc,f as So,i as qn,j as sc,k as ic,l as Qs,m as lc,o as dc}from"./chunk-YS3Z2Z64.js";import{a as rc,c as ac,d as cc}from"./chunk-Z3IP66SL.js";import{a as tc,c as nc}from"./chunk-6BXKZY76.js";import{a as Us,b as Wr}from"./chunk-RKPAVWXF.js";import{a as mt}from"./chunk-GV7S5BAX.js";import{e as Nr}from"./chunk-GSX4NK2N.js";import{c as Rr}from"./chunk-SZDACK6O.js";import{$ as za,A as _a,B as Da,C as Pa,D as Yt,E as Js,F as _n,G as Ma,H as xo,I as La,J as Gs,K as Hs,L as Fa,M as Ua,N as Vt,O as Dn,P as qa,Q as Wa,R as Ba,S as Ja,T as ut,U as ft,V as Ga,W as Ha,X as Ce,Y as Pn,Z as Kt,_ as zs,a as Kr,aa as Mn,b as Xr,ba as Ln,ca as Ka,da as Ks,ea as Qa,fa as Fn,ga as ht,h as oa,ha as Un,i as zt,ia as Xs,j as jn,ja as Za,k as sa,ka as ec,l as ia,m as ra,n as aa,o as ya,p as wa,q as xa,r as Aa,s as Ta,t as Oa,u as Ia,v as ja,w as Bs,x as Ca,y as Na,z as Ra}from"./chunk-7PK32QT5.js";import{E as Ya,F as Ys,G as Va,H as Vs,V as io,X as Xa,k as ba,n as $a,u as ka,v as va}from"./chunk-WCNKTV6G.js";import{a as Qr,d as Zr,e as ea}from"./chunk-NKSCUCVZ.js";import{a as Ws,b as Cn,c as Nn,d as ca,e as la,f as da,i as ga,j as ma,k as pa,l as ua,o as Rn,q as fa,r as ha}from"./chunk-S7CVSKOX.js";import{a as ta,p as na}from"./chunk-B5UA3X6E.js";import{a as Sa,b as Ea}from"./chunk-L53FTKEP.js";import{E as Ur,O as qr,h as Tr,q as Or,v as Ms,w as jr,y as vo}from"./chunk-64UYAWAK.js";import{b as Gt,c as dt,d as On,e as In,f as gt,g as Cr,h as Jo,i as Ht}from"./chunk-AWRRBNWQ.js";import{a as Ar}from"./chunk-N6EWZGIX.js";import{e as Mr,f as Fs,k as Lr}from"./chunk-WP6KLXTP.js";import{b as lt}from"./chunk-DP7RTNDM.js";import{a as qs,e as Br,f as Jr,h as Gr,i as Hr,k as zr,l as Yr,m as Vr}from"./chunk-QZ4M2KAC.js";import{a as Ir,k as Pr}from"./chunk-XOUIZBAQ.js";import{f as _r,g as Dr,h as Ls}from"./chunk-76Z4VHDX.js";import{b as he,c as Ae,d as pt,e as Fr}from"./chunk-7BQQWI4T.js";import{h as Er}from"./chunk-DWADWDMU.js";import{a as Ps}from"./chunk-7M7VJMGP.js";import{b as ko,d as Tn}from"./chunk-YPPTPBBV.js";import{b as ct,d as Sr}from"./chunk-2GIDVZ4H.js";import{a as Ds,b as mr,c as cg,d as En,e as pr,f as wr,g as dg,h as br,i as gg,m as at,n as kr,o as vr,s as xr,v as so,w as Jt}from"./chunk-MHBUAU2B.js";import{a as po,b as rt,e as fr,f as Bt}from"./chunk-72SZI2UW.js";import{a as $r,b as mg}from"./chunk-FX3D7YON.js";import{a as mo,b as ag}from"./chunk-7I7IEX4S.js";import{l as ur,m as R,n as An,p as re}from"./chunk-3IUU4YFI.js";import{g as hr,k as yr,l as lg}from"./chunk-RGDKHYY2.js";import{Command as pg}from"commander";var pc=new pg().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Xr({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});re();import{Command as ug}from"commander";import{execFileSync as ro}from"node:child_process";import{cpSync as uc,existsSync as ei,mkdirSync as Zs,mkdtempSync as fg,rmSync as hg,writeFileSync as fc}from"node:fs";import{dirname as hc,join as Me}from"node:path";import{homedir as Bn,release as yg,tmpdir as wg}from"node:os";import{setTimeout as bg}from"node:timers/promises";function Jn(){let e=ca(process.platform,process.arch,yg());if(e)throw new Error(e)}function Xt(){return`gui/${process.getuid()}/${Ws}`}function yt(){return Me(Bn(),"Library/LaunchAgents",`${Ws}.plist`)}async function yc(){try{ro("launchctl",["bootout",Xt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ro("launchctl",["print",Xt()],{stdio:"pipe"})}catch{return}await bg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function wc(){if(!ei(yt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ro("launchctl",["print",Xt()],{stdio:"pipe"})}catch{e=!1}e||ro("launchctl",["bootstrap",`gui/${process.getuid()}`,yt()],{stdio:"pipe"}),ro("launchctl",["kickstart",Xt()],{stdio:"pipe"})}function $g(){let e=ua();if(e&&ei(Me(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var wt=new ug("desktop").description("install and control the macOS desktop assistant");wt.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Jn();let o=R(),t=la(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=$g(),r=Me(Bn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Me(r,Cn)}
2
2
  Computer-use helper \u2192 ${Me(r,Nn)}
3
3
  Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -22,7 +22,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
22
22
  `))});function em(){let e;try{e=JSON.parse(Mc("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let o=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!o)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${o}`}var om=new Set(["/app","/api/app"]);function tm(e,o){let t=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of t)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===o&&!om.has(g)&&n.push(`${i}${a}`)}return n}function nm(){try{return JSON.parse(Mc("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function ri(){try{return R().dashboard.port||4202}catch{return 4202}}re();import{Command as co}from"commander";import h from"chalk";import Ne from"prompts";import{readFileSync as Ao,writeFileSync as kt,existsSync as ue,mkdirSync as ao,cpSync as ai,readdirSync as li}from"fs";import{resolve as G,join as Eo,dirname as sm}from"path";import{fileURLToPath as im}from"url";function ae(){let e=G(process.cwd(),"agentx.json");if(!ue(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ao(e,"utf-8"))}function Le(e){return he(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var zo=new co().name("agent").description("manage agents \u2014 add, list, remove");zo.command("list").alias("ls").description("list configured agents").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});zo.command("add").description("add a new agent interactively").action(async()=>{let e=ae(),o=await Ne([{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:G(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{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(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Eo(o.workspace,o.id);ao(G(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=G(process.cwd(),"src/wiki/SKILL.md"),a=G(sm(im(import.meta.url)),"../wiki/SKILL.md"),c=ue(r)?r:a;ue(c)&&(ao(G(t,".claude/skills/wiki"),{recursive:!0}),ai(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Le(e),console.log(h.green(`
23
23
  Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});zo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ae();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Le(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});zo.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=ae(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Le(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var tn=new co().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");tn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ae().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
24
24
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
25
- `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});tn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ae();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-TVW7UCKG.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ne({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ne({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await Ne({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await Ne({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(l=((await Ne({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Ne({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Le(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});tn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ae(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Le(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});tn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ae().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});zo.addCommand(tn);var Xn=new co().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Xn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ae();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Xn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ae(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Ne({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:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Ne([{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:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Le(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ne([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{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. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Le(e),ao(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ne([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Le(e),console.log(h.green(` GitLab enabled (${i.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 vt=new co().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");vt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});vt.command("add").description("add a cron job").action(async()=>{let e=ae(),o=Object.keys(e.agents||{}),t=await Ne([{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:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Le(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});vt.command("enable <id>").description("enable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Le(o),console.log(h.green(` Cron "${e}" enabled`))});vt.command("disable <id>").description("disable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Le(o),console.log(h.green(` Cron "${e}" disabled`))});var xt=new co().name("mesh").description("manage mesh peers \u2014 add, list, remove");xt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ae();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});xt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ae(),o=await Ne([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.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:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Le(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});xt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ae();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Le(o),console.log(h.green(` Peer "${e}" removed`)))});xt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ae();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Le(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Yo=new co().name("skill").description("manage skills \u2014 add to agent(s), list");Yo.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,o)=>{let t=ae(),n=G(e);if(!ue(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ue(Eo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Ne({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=G(a.workspace,".claude/skills",s);ao(c,{recursive:!0}),ue(Eo(n,"SKILL.md"))?ai(n,c,{recursive:!0}):n.endsWith(".md")&&ai(n,Eo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Yo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=ue(n)?li(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Yo.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,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>ue(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=Ao(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=R()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!ue(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=G(v,".claude/skills",e),S=G(A,"SKILL.md");if(!ue(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(ao(A,{recursive:!0}),kt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let x=Ao(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let C=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||kt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${C} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Yo.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:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ae().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let p=ae();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of d)p[f.verdict]++;console.log();for(let f of d){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Yo.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ae(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-ILXHYJGD.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
25
+ `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});tn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=ae();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-FGCJVXYX.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ne({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ne({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await Ne({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await Ne({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(l=((await Ne({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let p of String(o.metadata).split(",")){let[f,...u]=p.split("=");f&&(g[f.trim()]=u.join("=").trim())}else if(n){let p=await Ne({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[u,...w]=f.split("=");u&&(g[u.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(p=>p.kind===i&&p.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Le(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});tn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ae(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Le(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});tn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ae().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});zo.addCommand(tn);var Xn=new co().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Xn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ae();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Xn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ae(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Ne({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:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Ne([{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:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Le(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ne([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{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. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Le(e),ao(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ne([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Le(e),console.log(h.green(` GitLab enabled (${i.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 vt=new co().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");vt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});vt.command("add").description("add a cron job").action(async()=>{let e=ae(),o=Object.keys(e.agents||{}),t=await Ne([{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:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Le(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});vt.command("enable <id>").description("enable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Le(o),console.log(h.green(` Cron "${e}" enabled`))});vt.command("disable <id>").description("disable a cron job").action(async e=>{let o=ae();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Le(o),console.log(h.green(` Cron "${e}" disabled`))});var xt=new co().name("mesh").description("manage mesh peers \u2014 add, list, remove");xt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ae();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});xt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ae(),o=await Ne([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.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:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Le(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});xt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ae();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Le(o),console.log(h.green(` Peer "${e}" removed`)))});xt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=ae();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Le(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Yo=new co().name("skill").description("manage skills \u2014 add to agent(s), list");Yo.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,o)=>{let t=ae(),n=G(e);if(!ue(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ue(Eo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Ne({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=G(a.workspace,".claude/skills",s);ao(c,{recursive:!0}),ue(Eo(n,"SKILL.md"))?ai(n,c,{recursive:!0}):n.endsWith(".md")&&ai(n,Eo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Yo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ae();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=ue(n)?li(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Yo.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,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>ue(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=Ao(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=R()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,u=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!ue(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=G(v,".claude/skills",e),S=G(A,"SKILL.md");if(!ue(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(ao(A,{recursive:!0}),kt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),p++;continue}let x=Ao(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),u++;continue}let C=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||kt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${C} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${u} already current, ${w} skipped.`)),o.dryRun&&(p>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Yo.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:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ae().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let p=ae();for(let f of Object.values(p.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(p=>o(p)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of d)p[f.verdict]++;console.log();for(let f of d){let u=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${u} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${p.PASS} PASS`)} ${h.yellow(`${p.REVIEW} REVIEW`)} ${h.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Yo.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=ae(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-BYOX63CR.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
26
26
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
27
27
  (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var nn=new co().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");nn.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,o)=>{/^[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 t=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");ue(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");ao(i,{recursive:!0}),ao(r,{recursive:!0});let a=li(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let p=Eo(i,d);if(ue(p)&&!o.force){console.log(h.dim(` skip ${p} (exists; --force to overwrite)`)),l++;continue}let u=Ao(Eo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);kt(p,u),console.log(h.green(` + ${p}`)),c++}let g=Eo(r,`${e}.yaml`);if(ue(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(ue(s)){let d=Ao(s,"utf-8").replaceAll("example.",`${e}.`);kt(g,d),console.log(h.green(` + ${g}`)),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()});nn.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.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[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:t}=await import("./loader-EVHZ2R73.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=G(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),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(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=G(o.referencesCwd||o.cwd),p=G(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
28
28
  --- ${w} ---`)),console.log(y.split(`
@@ -31,7 +31,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
31
31
  `).length>30&&console.log(h.dim(` \u2026 (${y.split(`
32
32
  `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}ao(p,{recursive:!0});let f=0,u=0;for(let[w,y]of Object.entries(g)){let k=Eo(p,w);if(ue(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),u++;continue}kt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${u} 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()});nn.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:o}=await import("./loader-KKMG24O5.js"),t=await o(G(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var di=new co().name("hook").description("manage hooks \u2014 add to agent workspace");di.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ae().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=G(t.workspace,".claude/settings.json"),s=ue(n)?JSON.parse(Ao(n,"utf-8")):{},i=await Ne([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),ao(G(t.workspace,".claude"),{recursive:!0}),kt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var gi=new co().name("migrate").description("import configuration from OpenClaw or other tools");gi.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,o)=>{let t=[e,G(process.env.HOME||"",".openclaw/openclaw.json"),G(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ue(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(Ao(n,"utf-8")),i=ue(G(process.cwd(),"agentx.json"))?ae():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let u=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===u)||w.push(u),i.agents[u]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){ao(G(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-42ARC42I.js");y(u,i.agents[u])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:u.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let p=G(n,"../cron/jobs.json");if(ue(p)){let f=JSON.parse(Ao(p,"utf-8")),u=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${h.green(u)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
33
33
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Le(i),console.log(h.green(`
34
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var To=new co().name("config").description("validate and inspect configuration");To.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 o=R(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=An(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ue(G(r,".claude")),c=ue(G(r,"CLAUDE.md")),l=ue(G(r,".claude/settings.json")),g=ue(G(r,".claude/skills"))?li(G(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,d=[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",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});To.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=R(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function rm(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function ci(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}To.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,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-JHM53P5A.js"),{expandEnvVars:r}=await import("./config-TVW7UCKG.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(ci(g))});To.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,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-JHM53P5A.js"),r=rm(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${ci(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${ci(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})`)))});To.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,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-JHM53P5A.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});To.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=R(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as am}from"commander";import Oo from"chalk";import{resolve as Io}from"path";import{existsSync as cm}from"fs";var fo=new am().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Vo(e){let o=Io(e,".agentx/db.sqlite");cm(o)||(console.log(Oo.red(` No SQLite at ${o}`)),console.log(Oo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Ar({path:o});return t||(console.log(Oo.red(` Could not open ${o}`)),console.log(Oo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Ko(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Oo.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}fo.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 o=Vo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
34
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var To=new co().name("config").description("validate and inspect configuration");To.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 o=R(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=An(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ue(G(r,".claude")),c=ue(G(r,"CLAUDE.md")),l=ue(G(r,".claude/settings.json")),g=ue(G(r,".claude/skills"))?li(G(r,".claude/skills")).filter(p=>!p.startsWith(".")).length:0,d=[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",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});To.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=R(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function rm(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function ci(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}To.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,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-5JSG3CHW.js"),{expandEnvVars:r}=await import("./config-FGCJVXYX.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(ci(g))});To.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,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-5JSG3CHW.js"),r=rm(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${ci(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${ci(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})`)))});To.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,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-5JSG3CHW.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});To.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=R(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as am}from"commander";import Oo from"chalk";import{resolve as Io}from"path";import{existsSync as cm}from"fs";var fo=new am().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Vo(e){let o=Io(e,".agentx/db.sqlite");cm(o)||(console.log(Oo.red(` No SQLite at ${o}`)),console.log(Oo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Ar({path:o});return t||(console.log(Oo.red(` Could not open ${o}`)),console.log(Oo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Ko(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Oo.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}fo.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 o=Vo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
35
35
  SELECT agent_id, channel, status, duration_ms,
36
36
  input_tokens, output_tokens,
37
37
  substr(message_preview, 1, 60) AS message,
@@ -392,7 +392,7 @@ return aid ?? null`}function eu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
392
392
  settings \u2014 without this an attached production identity would be less
393
393
  guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});ot.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=xc({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});re();import{Command as Pu}from"commander";import ye from"chalk";var ms=new Pu().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ql(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=R(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Zl(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Xl(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Mu(e){return e==="busy"?ye.magenta:e==="warm-hot"?ye.green:e==="warm-cold"?ye.cyan:e==="idle"?ye.yellow:e==="dead"?ye.red:ye.dim}ms.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Ql(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Zl(t)})}catch(r){console.log(ye.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ye.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ye.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(ye.dim(" (no processes)"));return}for(let r of i){let a=Mu(r.state)(r.state.padEnd(9)),c=Xl(r.spawnedAt),l=r.lastTurnAt?Xl(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?ye.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?ye.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ye.dim("sess=\u2014"),p=r.pendingTaskId?ye.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ye.bold(r.key.agentId)}${ye.dim(":"+r.key.channel+":"+r.key.chatId)} ${ye.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${p}`),r.deadReason&&console.log(` ${ye.red("dead:")} ${r.deadReason}`)}});ms.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Ql(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Zl(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ye.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ye.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(ye.red(` ${a}`)),process.exit(1)}console.log(ye.green(` killed ${e}:${o}:${t}`))});import{Command as Lu}from"commander";import _e from"chalk";import{existsSync as Ri,rmSync as Fu}from"fs";import{resolve as _i}from"path";var It=new Lu().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");It.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(_e.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await _r(e,o,{verbose:n}),r=Date.now()-s;console.log(_e.green(` \u2713 indexed ${i.docs} doc(s) for ${_e.bold(e)} in ${r}ms`)),console.log(_e.dim(` \u2192 ${i.path}`))});It.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=_i(e.cwd,".agentx","rag");if(!Ri(o)){console.log(_e.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Ri(_i(o,s,"index.json")));if(n.length===0){console.log(_e.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ls(s);console.log(` ${_e.bold(s)} ${i.docs} doc(s) ${_e.dim(i.path)}`)}});It.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=Dr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ls(e);i.exists?console.log(_e.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(_e.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${_e.bold(i.title)} ${_e.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${_e.dim(i.path)}`),console.log(` ${_e.dim(i.snippet.slice(0,200))}`)});It.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=_i(process.cwd(),".agentx","rag",e);if(!Ri(o)){console.log(_e.dim(` no index for ${e} \u2014 nothing to clear`));return}Fu(o,{recursive:!0,force:!0}),console.log(_e.green(` \u2713 cleared index for ${e}`))});re();import{Command as Uu}from"commander";import K from"chalk";import jt from"prompts";var tt=new Uu().name("backlog").description("manage the local backlog used by business workSource=backlog");function gn(e){let o=R(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Ya(n)}}function qu(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function Wu(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}tt.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=gn(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${Wu(n.status).padEnd(7)} ${qu(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});tt.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=gn(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Va([o],i.source,n.config),a=await Vs(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});tt.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=gn(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await Vs(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});tt.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=gn(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});tt.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=gn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await jt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Ju(o.config):Gu(o.config);y.length?(i=(await jt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await jt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await jt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await jt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Hu(o.config,i,a):await zu(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=Ys({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await jt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let u=f.map(y=>{let k={type:s,host:s==="gitlab"?Bu(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Ys(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(u);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function Bu(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ju(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function Gu(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Hu(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function zu(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(ed)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(ed):[]}function ed(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Yu}from"commander";import W from"chalk";import{existsSync as Vu,readFileSync as Ku}from"fs";import{resolve as Xu}from"path";import Qu from"prompts";re();function od(e){let o=e||Xu(process.cwd(),"agentx.json");return Vu(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Ku(o,"utf-8"))}async function Zu(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Qu([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var yo=new Yu().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');yo.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: ${qs})`,qs).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,o)=>{if(!e){yo.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Us(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=od(o.config),s=ur(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Zu(o.notify,s),r=o.id||Wr(t.matched,o.agent),a=Jr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Br(o.onError),enabled:!o.disabled}),c=a.onError,l=await he(d=>Ae(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});yo.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 t=od(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Hr(Gr(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])yo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Vr(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});yo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await he(t=>{if(!pt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Fr(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",zr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Yr,"reject an agent's pending create/delete request (drops the request)"]])yo.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});yo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Us(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as ef}from"commander";import ve from"chalk";var Do=new ef("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),of={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function td(){return{root:process.cwd()}}function Di(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function tf(e){console.log(` ${ve.cyan(e.key)} ${ve.dim(`[${of[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ve.dim(` (later: until ${Di(e.snoozed_until)})`):""}`),console.log(` ${ve.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ve.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(ve.yellow(` Expires ${Di(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ve.dim(` ${e.detail}`)),e.source&&console.log(ve.dim(` ${e.source}`)),console.log(ve.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Do.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let o=ka(td(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ve.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ve.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)tf(t),console.log();console.log(ve.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Pi(e,o,t){let n=qn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ve.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await va(td(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(ve.red(` ${i.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 ${i.message}`))}Do.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,o)=>Pi(e,"yes",o));Do.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,o)=>Pi(e,"no",o));Do.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,o)=>Pi(e,"later",o));Do.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${ba.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let o=qn(),t=$a(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:o});if(!t.ok){console.error(ve.red(` ${t.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 card:${t.card.id} raised; expires ${Di(t.card.expires)}, then: ${t.card.if_silent}`))});Do.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let o={},t=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let a=sc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(ve.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await ic(o);if(!a.success){console.error(ve.red(` ${a.error}`)),process.exitCode=1;return}console.log(ve.green(" \u2713 saved")+(a.reloaded?ve.dim(" (daemon reloaded)"):""))}let i=qn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as Af}from"commander";import Ct from"chalk";import te from"chalk";import pn from"prompts";import{readFileSync as nf,writeFileSync as sf,existsSync as rf}from"fs";import{resolve as nd}from"path";var af=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function cf(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Mi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function sd(e=".env"){let o=nd(e);if(!rf(o))return[];let t=nf(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(af);i?n.push({kind:"kv",key:i[1],value:cf(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function lf(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Mi(o.value)}`:o.raw).join(`
394
394
  `)+`
395
- `}function mn(e,o,t=".env"){let n=nd(t),s=sd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Mi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Mi(o)}`})),sf(n,lf(s))}function Li(e,o=".env"){return sd(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var id="https://t.me/BotFather";async function df(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function gf(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function rd(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${id}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await pn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[id],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await pn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await df(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.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(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await pn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await pn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(te.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;mn(f,t.trim()),process.env[f]=t.trim();let u=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let v=pt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(te.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${f}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await pn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await gf(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Fi from"prompts";import{existsSync as qi,mkdirSync as mf,readdirSync as pf,readFileSync as ad}from"fs";import{resolve as Ui}from"path";var uf=".agentx/whatsapp-sessions";function ff(){let e=Ui(process.cwd(),".agentx/daemon.pid");if(!qi(e))return!1;try{let o=parseInt(ad(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function hf(e){if(!qi(e))return!1;try{return pf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function yf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;mf(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function cd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),ff()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Fi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Ui(process.cwd(),"agentx.json");qi(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(ad(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||uf,s=Ui(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Fi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(hf(s)&&a){let{keep:l}=await Fi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await yf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as wf}from"crypto";import xe from"chalk";import ld from"prompts";var ps="agentx-mesh:",us="//join/";function bf(e){return Buffer.from(e,"utf-8").toString("base64url")}function $f(e){return Buffer.from(e,"base64url").toString("utf-8")}function kf(e){return`${ps}${us}${bf(JSON.stringify(e))}`}function vf(e){if(!e.startsWith(`${ps}${us}`))throw new Error(`Not a mesh invite link \u2014 expected ${ps}${us}\u2026`);let o=e.slice(ps.length+us.length),t=JSON.parse($f(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function xf(){return wf(32).toString("hex")}function Sf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Ef(e){return e?.node?.name||e?.node?.id||"node"}async function dd(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Li("MESH_TOKEN");r||(r=xf(),mn("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Sf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await ld({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=kf({url:a,token:r,name:Ef(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function gd(e,o={}){let t;try{t=vf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Li("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await ld({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}mn("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=pt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Nt=new Af().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Nt.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 rd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Nt.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 cd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var md=Nt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");md.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 dd({url:e.url,configPath:e.config})});md.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await gd(e,{configPath:o.config})});Nt.action(()=>{console.log(),console.log(Ct.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ct.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ct.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ct.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ct.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ct.dim(" GitLab connect is the next slice.")),console.log()});re();import{Command as Tf}from"commander";import pe from"chalk";var un=new Tf().name("usage").description("token usage analysis and reporting");un.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=R(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});un.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});un.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-UXJWH5JG.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),l(f,u)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Of}from"commander";import be from"chalk";import{readFileSync as If}from"fs";import{resolve as jf}from"path";re();var Po=new Of().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Po.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{try{Sr(jf(process.cwd(),".env"))}catch{}let o=Cf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-WG4ZZV4A.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function Cf(e,o){try{let t=R();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
395
+ `}function mn(e,o,t=".env"){let n=nd(t),s=sd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Mi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Mi(o)}`})),sf(n,lf(s))}function Li(e,o=".env"){return sd(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var id="https://t.me/BotFather";async function df(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function gf(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function rd(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${id}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await pn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[id],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await pn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await df(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.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(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await pn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await pn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(te.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;mn(f,t.trim()),process.env[f]=t.trim();let u=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:g});let v=pt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(te.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${f}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await pn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await gf(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Fi from"prompts";import{existsSync as qi,mkdirSync as mf,readdirSync as pf,readFileSync as ad}from"fs";import{resolve as Ui}from"path";var uf=".agentx/whatsapp-sessions";function ff(){let e=Ui(process.cwd(),".agentx/daemon.pid");if(!qi(e))return!1;try{let o=parseInt(ad(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function hf(e){if(!qi(e))return!1;try{return pf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function yf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;mf(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function cd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),ff()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Fi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Ui(process.cwd(),"agentx.json");qi(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(ad(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||uf,s=Ui(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Fi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(hf(s)&&a){let{keep:l}=await Fi({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await yf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as wf}from"crypto";import xe from"chalk";import ld from"prompts";var ps="agentx-mesh:",us="//join/";function bf(e){return Buffer.from(e,"utf-8").toString("base64url")}function $f(e){return Buffer.from(e,"base64url").toString("utf-8")}function kf(e){return`${ps}${us}${bf(JSON.stringify(e))}`}function vf(e){if(!e.startsWith(`${ps}${us}`))throw new Error(`Not a mesh invite link \u2014 expected ${ps}${us}\u2026`);let o=e.slice(ps.length+us.length),t=JSON.parse($f(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function xf(){return wf(32).toString("hex")}function Sf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Ef(e){return e?.node?.name||e?.node?.id||"node"}async function dd(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Li("MESH_TOKEN");r||(r=xf(),mn("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Sf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await ld({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=kf({url:a,token:r,name:Ef(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function gd(e,o={}){let t;try{t=vf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Li("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await ld({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}mn("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=pt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Nt=new Af().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Nt.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 rd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Nt.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 cd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var md=Nt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");md.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 dd({url:e.url,configPath:e.config})});md.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await gd(e,{configPath:o.config})});Nt.action(()=>{console.log(),console.log(Ct.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ct.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ct.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ct.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ct.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ct.dim(" GitLab connect is the next slice.")),console.log()});re();import{Command as Tf}from"commander";import pe from"chalk";var un=new Tf().name("usage").description("token usage analysis and reporting");un.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=R(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});un.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});un.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-MNFDOQGQ.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),l(f,u)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Of}from"commander";import be from"chalk";import{readFileSync as If}from"fs";import{resolve as jf}from"path";re();var Po=new Of().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Po.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{try{Sr(jf(process.cwd(),".env"))}catch{}let o=Cf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-KETIFTBD.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function Cf(e,o){try{let t=R();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
396
396
  `)),{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:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Po.command("list").description("list configured boards").action(()=>{try{let e=R();if(!e.boards?.length){console.log(be.dim(`
397
397
  No boards configured.
398
398
  `));return}console.log();for(let o of e.boards){console.log(` ${be.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(be.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(be.dim(` primary label: ${o.primaryToolLabel}`)),console.log(be.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(be.red(` ${e.message}`)),process.exit(1)}});Po.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. 'globex/system,globex/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,o)=>{try{fn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});Po.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{fn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});var Wi=Po.command("column").description("manage a board's columns (add / remove / edit / list)");Wi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(If("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(be.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${be.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${be.dim(i)}`)}}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});Wi.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{fn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(be.red(` ${n.message}`)),process.exit(1)}});Wi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{fn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});Po.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{fn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});function fn(e){let{summary:o,backupPath:t}=uo(n=>e(n));console.log(be.green(`
@@ -402,9 +402,9 @@ return aid ?? null`}function eu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
402
402
  ${$.content}
403
403
  --- END ENTRY ---`).join(`
404
404
 
405
- `),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:I,installPrompts:D,defaultSources:B,recordsFromEntries:M}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Ee of t.listAgents())for(let $e of t.getAgentWiki(Ee).listArticles(Ee))$e.meta.type==="person"&&J.add($e.meta.title);a=[...J]}let H=$(u.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),ge=M(u);if(H.length>0||ge.length>0){let J=B(),{records:Ee,results:$e}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=j([...ge,...Ee]);v=I(P);let He=[...ge.length>0?[`entries:${ge.length}`]:[],...$e.filter(ke=>ke.records.length>0).map(ke=>`${ke.source}:${ke.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${P.length} resolved${He.length?` (${He.join(" ")})`:""}`));for(let ke of D($e,J))console.log(m.yellow(` ! ${ke.source} ${ke.kind} \u2014 would supply ${ke.provides.join(", ")}`)),console.log(m.dim(` ${ke.hint}`))}}let A=ta(o,p,k,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${Ji(o)}`));let S=F(w.baseDir,"_tmp");wo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");st(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=nt(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:ct({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(P){if($=P.stdout||"",!$)throw P}let C=$;try{let P=JSON.parse($);C=P.result||P.content||"",C||(console.log(m.dim(` Claude envelope keys: ${Object.keys(P).join(", ")}`)),console.log(m.dim(` is_error: ${P.is_error}, stop_reason: ${P.stop_reason}`)))}catch{}let j,I=[],D=C.indexOf("{"),B=C.indexOf("["),M=D>=0&&(B<0||D<B)?D:B;if(M===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let H=C[M],ge=H==="{"?"}":"]",J=0,Ee=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===ge&&(J--,J===0)){Ee=P+1;break}if(Ee===-1){console.log(m.red(" Unbalanced JSON"));continue}let $e=C.slice(M,Ee);try{let P=JSON.parse($e);Array.isArray(P)?j=P:(j=P.articles||[],I=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${$e.slice(0,300)}`));continue}for(let P of j){let He=new Date().toISOString().slice(0,10),ke=l(P.sources||[],u);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:p,access:"public",created:He,lastUpdated:He,sources:P.sources||[],graphPath:ke},P.content,p);let Bo=P.type?m.magenta(`[${P.type}]`)+" ":"",N=Array.isArray(P.related)&&P.related.length?` \u2192 ${P.related.slice(0,3).join(", ")}${P.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Bo}${P.path}: ${P.title}${m.dim(N)}`);let fe=(P.tags||[]).slice(0,4).join(", ");fe&&console.log(m.dim(` tags: ${fe}`)),ke?.length&&(console.log(m.dim(` graphPath: ${ke.join(" \u203A ")}`)),d++),g++}if(I.length>0){console.log(),console.log(m.yellow(` Gaps detected (${I.length} missing pieces):`));for(let P of I)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-2V2VGIT4.js"),He=new P(yn(e.dir)).add(I.map(ke=>({kind:"article",agentId:p,path:"",subject:String(ke).slice(0,120),question:`No article yet for: ${String(ke).slice(0,160)}`})));He.added>0&&console.log(m.dim(` queued ${He.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Q.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=Df(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-QWW5PDUU.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!ze(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new g(d,{readonly:!0});try{let f=c(p,{since:Date.now()-(o??6048e5)}),u=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${u.length} failure(s) seen in ${a}+ sessions`));let w=u[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...u]}finally{p.close()}}}let r=await na({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var hs=Q.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ys(e){return e?F(e):F(process.cwd(),".agentx","wiki")}hs.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(ys(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});hs.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(ys(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
405
+ `),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:C,mergeRecords:j,renderFactsBlock:I,installPrompts:D,defaultSources:B,recordsFromEntries:M}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Ee of t.listAgents())for(let $e of t.getAgentWiki(Ee).listArticles(Ee))$e.meta.type==="person"&&J.add($e.meta.title);a=[...J]}let H=$(u.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),ge=M(u);if(H.length>0||ge.length>0){let J=B(),{records:Ee,results:$e}=H.length>0?await C(H,{sources:J}):{records:[],results:[]},P=j([...ge,...Ee]);v=I(P);let He=[...ge.length>0?[`entries:${ge.length}`]:[],...$e.filter(ke=>ke.records.length>0).map(ke=>`${ke.source}:${ke.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${P.length} resolved${He.length?` (${He.join(" ")})`:""}`));for(let ke of D($e,J))console.log(m.yellow(` ! ${ke.source} ${ke.kind} \u2014 would supply ${ke.provides.join(", ")}`)),console.log(m.dim(` ${ke.hint}`))}}let A=ta(o,p,k,y.articles,b,u.length,v);console.log(m.dim(` Mode: ${Ji(o)}`));let S=F(w.baseDir,"_tmp");wo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");st(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=nt(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:ct({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(P){if($=P.stdout||"",!$)throw P}let C=$;try{let P=JSON.parse($);C=P.result||P.content||"",C||(console.log(m.dim(` Claude envelope keys: ${Object.keys(P).join(", ")}`)),console.log(m.dim(` is_error: ${P.is_error}, stop_reason: ${P.stop_reason}`)))}catch{}let j,I=[],D=C.indexOf("{"),B=C.indexOf("["),M=D>=0&&(B<0||D<B)?D:B;if(M===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(C.slice(0,500)));continue}let H=C[M],ge=H==="{"?"}":"]",J=0,Ee=-1;for(let P=M;P<C.length;P++)if(C[P]===H)J++;else if(C[P]===ge&&(J--,J===0)){Ee=P+1;break}if(Ee===-1){console.log(m.red(" Unbalanced JSON"));continue}let $e=C.slice(M,Ee);try{let P=JSON.parse($e);Array.isArray(P)?j=P:(j=P.articles||[],I=P.gaps||[])}catch(P){console.log(m.red(` JSON parse error: ${P.message}`)),console.log(m.dim(` First 300 chars: ${$e.slice(0,300)}`));continue}for(let P of j){let He=new Date().toISOString().slice(0,10),ke=l(P.sources||[],u);w.writeArticle(P.path,{title:P.title,type:P.type,related:Array.isArray(P.related)?P.related:void 0,tags:P.tags||[],owner:p,access:"public",created:He,lastUpdated:He,sources:P.sources||[],graphPath:ke},P.content,p);let Bo=P.type?m.magenta(`[${P.type}]`)+" ":"",N=Array.isArray(P.related)&&P.related.length?` \u2192 ${P.related.slice(0,3).join(", ")}${P.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Bo}${P.path}: ${P.title}${m.dim(N)}`);let fe=(P.tags||[]).slice(0,4).join(", ");fe&&console.log(m.dim(` tags: ${fe}`)),ke?.length&&(console.log(m.dim(` graphPath: ${ke.join(" \u203A ")}`)),d++),g++}if(I.length>0){console.log(),console.log(m.yellow(` Gaps detected (${I.length} missing pieces):`));for(let P of I)console.log(m.yellow(` ? ${P}`));try{let{QuestionStore:P}=await import("./questions-2V2VGIT4.js"),He=new P(yn(e.dir)).add(I.map(ke=>({kind:"article",agentId:p,path:"",subject:String(ke).slice(0,120),question:`No article yet for: ${String(ke).slice(0,160)}`})));He.added>0&&console.log(m.dim(` queued ${He.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let p=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${p}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Q.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=Df(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-F2HNH2TZ.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(u=>u.trim()).filter(Boolean)});let p=i.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${p} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!ze(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new g(d,{readonly:!0});try{let f=c(p,{since:Date.now()-(o??6048e5)}),u=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${u.length} failure(s) seen in ${a}+ sessions`));let w=u[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...u]}finally{p.close()}}}let r=await na({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var hs=Q.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ys(e){return e?F(e):F(process.cwd(),".agentx","wiki")}hs.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(ys(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});hs.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(ys(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
406
406
  `).map(s=>` ${s}`).join(`
407
- `)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});hs.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-4T64VW5K.js"),n=t(ys(o.dir),e,{force:o.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});hs.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{rejectProposal:t}=await import("./promote-4T64VW5K.js"),n=t(ys(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Df(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Q.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",F(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:o}=await import("./query-6IKL52WT.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Se(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let p=[],f=t(d).sort().reverse();for(let y of f){let k=r(d,y),b=[];try{b=t(k).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=g)break;try{let A=JSON.parse(n(r(k,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.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 u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let k=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let v=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
407
+ `)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});hs.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-NBFF7ZIW.js"),n=t(ys(o.dir),e,{force:o.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});hs.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{rejectProposal:t}=await import("./promote-NBFF7ZIW.js"),n=t(ys(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Df(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Q.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",F(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:o}=await import("./query-XCXR57IV.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Se(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let p=[],f=t(d).sort().reverse();for(let y of f){let k=r(d,y),b=[];try{b=t(k).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=g)break;try{let A=JSON.parse(n(r(k,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(p.length>=g)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.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 u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let k=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let v=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
408
408
  `)||"_(none returned)_",A;try{let S=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
409
409
 
410
410
  ${S.answer}
@@ -421,7 +421,7 @@ Q: ${N.q}
421
421
  A: ${N.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
422
422
  `),A=F(a.baseDir,"_tmp");wo(A,{recursive:!0});let S=F(A,`interview-${t().slice(0,8)}.txt`);st(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let N=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=nt(N,{env:ct({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ye=JSON.parse(fe);x=String(Ye.result||Ye.content||"")}catch{x=fe}}catch(N){console.log(m.red(` synthesis failed: ${N.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let $=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(x=$[1].trim());let C=x.indexOf("---");C>0&&(x=x.slice(C));let j=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!j){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let I={};for(let N of j[1].split(`
423
423
  `)){let fe=N.match(/^(\w+):\s*(.+)$/);fe&&(I[fe[1]]=fe[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],B=I.title||g,M=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ge=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${M}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ge}`)),console.log(),console.log(x),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/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 ${S} (prompt only; no article file)`));return}let Ee=D,$e={title:B,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let N=process.env.EDITOR||"vi",fe=F(A,`draft-${t().slice(0,8)}.md`);st(fe,x);try{nt(`${N} '${fe}'`,{stdio:"inherit"});let Rs=hn(fe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Rs){let $o={};for(let Wt of Rs[1].split(`
424
- `)){let _s=Wt.match(/^(\w+):\s*(.+)$/);_s&&($o[_s[1]]=_s[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=Rs[2],$e={...$e,title:$o.title||$e.title,type:$o.type||$e.type,access:$o.access||$e.access,related:$o.related?$o.related.replace(/^\[|\]$/g,"").split(",").map(Wt=>Wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:$o.tags?$o.tags.replace(/^\[|\]$/g,"").split(",").map(Wt=>Wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(Ye){console.log(m.red(` editor failed: ${Ye.message}`));return}}if(!a.writeArticle(ge,$e,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ge} saved.`));let He=a.extractWikilinks(Ee),ke=new Map;for(let N of a.listArticles(e.agent))ke.set(N.meta.title.toLowerCase(),!0);let Bo=He.filter(N=>!ke.has(N.toLowerCase()));if(Bo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of Bo.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Q.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-6IKL52WT.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Se(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=hn(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],p=0;for(let f=0;f<l;f++){let u,w;if(r){let H=r[f];if(!H)break;u=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(H){console.log(m.red(`failed: ${H.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let H=y.citations.map(ge=>`${ge.title} [${ge.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
424
+ `)){let _s=Wt.match(/^(\w+):\s*(.+)$/);_s&&($o[_s[1]]=_s[2].trim().replace(/^"(.*)"$/,"$1"))}Ee=Rs[2],$e={...$e,title:$o.title||$e.title,type:$o.type||$e.type,access:$o.access||$e.access,related:$o.related?$o.related.replace(/^\[|\]$/g,"").split(",").map(Wt=>Wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:$o.tags?$o.tags.replace(/^\[|\]$/g,"").split(",").map(Wt=>Wt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(Ye){console.log(m.red(` editor failed: ${Ye.message}`));return}}if(!a.writeArticle(ge,$e,Ee,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ge} saved.`));let He=a.extractWikilinks(Ee),ke=new Map;for(let N of a.listArticles(e.agent))ke.set(N.meta.title.toLowerCase(),!0);let Bo=He.filter(N=>!ke.has(N.toLowerCase()));if(Bo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of Bo.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Q.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-XCXR57IV.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Se(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let u=hn(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of u){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],p=0;for(let f=0;f<l;f++){let u,w;if(r){let H=r[f];if(!H)break;u=H.q,w=H.verdict,console.log(m.cyan(` [${f+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${f+1}] Q: `)),!u||u==="/done"||u==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(H){console.log(m.red(`failed: ${H.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let H=y.citations.map(ge=>`${ge.title} [${ge.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
425
425
  `)),console.log(m.dim(" citations: "+H))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:u,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let $=Mf(x.content,v,A,x.meta.title,x.meta.type),C=F(i.baseDir,"_tmp");wo(C,{recursive:!0});let j=F(C,`quiz-patch-${t().slice(0,8)}.txt`);st(j,$);let I="";try{let H=`cat '${j}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ge=nt(H,{env:ct({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ee=JSON.parse(ge);I=String(Ee.result||Ee.content||"")}catch{I=ge}let J=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(I=J[1].trim()),I=I.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=x.content.split(`
426
426
  `).length,B=I.split(`
427
427
  `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${B} lines (${B-D>=0?"+":""}${B-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),p>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${p} patches_`,""];for(let u=0;u<d.length;u++){let w=d[u];f.push(`## ${u+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}st(e.out,f.join(`
@@ -482,14 +482,14 @@ Output (JSON array, one entry per input article, same order):
482
482
  [
483
483
  {"path": "path/to/article.md", "type": "project"},
484
484
  ...
485
- ]`}Q.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Se(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});Q.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-TVW7UCKG.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),dc(o,t,e.agent,n,e.mode)});Q.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-3KUNRM5Z.js"),c=Se(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),p=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(p.length>=g)break e;let v=k.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),$=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!($&&!$.fit)||p.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map(k=>y[k])));if(e.fields){let y=p.filter(k=>k.missing!=="-").length;console.log(m.dim(`
485
+ ]`}Q.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Se(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});Q.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-FGCJVXYX.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),dc(o,t,e.agent,n,e.mode)});Q.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-IPDLEUI5.js"),c=Se(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),p=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(p.length>=g)break e;let v=k.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),$=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!($&&!$.fit)||p.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=f.map(y=>Math.max(y.length,...p.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(u[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of p)console.log(w(f.map(k=>y[k])));if(e.fields){let y=p.filter(k=>k.missing!=="-").length;console.log(m.dim(`
486
486
  ${p.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
487
- ${p.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});Q.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-6IKL52WT.js"),n=Se(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \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(o.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(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Q.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Se(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));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()});Q.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new ko({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,p]of Object.entries(i.entries))r.set(d,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let p=o.getAgentWiki(d),f=p.listArticles(d),u=o.getSharedStore().listEntries(),w=new Map(u.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let C=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:C}),I=r.get(j);if(!I?.length)continue;let D=I.join("/"),B=A.get(D);B?B.n++:A.set(D,{path:I,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Q.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Se(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-TVW7UCKG.js");n=(r().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.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/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||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let p of l)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});Q.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Ps(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),p=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])u.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Ji(c),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Q.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Uf(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Q.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-3KUNRM5Z.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Se(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let C of $.listArticles(x)){if(f>=p)break e;let j=$.readArticle(C.path);if(!j||e.type&&j.meta.type!==e.type)continue;f++;let I=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:x,type:j.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,I.answers);for(let B of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:C.path,subject:j.meta.title,field:B.field,tier:B.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${B.label}?`}),u.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(yn(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...u.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of u)console.log(y.map(($,C)=>v(x[$],C)).join(" "));let A=u.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,C=g.filter(j=>(x[j.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-TVW7UCKG.js"),I=j(),D=I?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=C.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
487
+ ${p.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});Q.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-XCXR57IV.js"),n=Se(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \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(o.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(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Q.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Se(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));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()});Q.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Se(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new ko({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,p]of Object.entries(i.entries))r.set(d,p.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let p=o.getAgentWiki(d),f=p.listArticles(d),u=o.getSharedStore().listEntries(),w=new Map(u.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let C=String($.meta?.sender??""),j=s.fingerprint({text:$.content,channel:$.source,sender:C}),I=r.get(j);if(!I?.length)continue;let D=I.join("/"),B=A.get(D);B?B.n++:A.set(D,{path:I,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Q.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Se(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-FGCJVXYX.js");n=(r().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.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/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||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let p of l)s.has(p.id)||(e.dryRun||(t.addEntry({id:p.id,date:p.date,agentId:p.agentId,source:`${p.source}@${g}`,sourceContext:p.sourceContext,content:p.content}),s.add(p.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let p=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(p.ok){let f=await p.json();for(let u of f.agents||[])u.totalEntries>0&&console.log(m.dim(` ${u.agentId}: ${u.totalEntries} entries, ${u.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});Q.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Ps(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),p=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),u=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])u.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Ji(c),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:u.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===g).map(p=>p.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Q.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Uf(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Q.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-IPDLEUI5.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Se(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),f=0,u=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let C of $.listArticles(x)){if(f>=p)break e;let j=$.readArticle(C.path);if(!j||e.type&&j.meta.type!==e.type)continue;f++;let I=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:x,type:j.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,I.answers);for(let B of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:C.path,subject:j.meta.title,field:B.field,tier:B.tier,question:`${j.meta.title} (${j.meta.type??"?"}) \u2014 ${B.label}?`}),u.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(yn(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...u.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of u)console.log(y.map(($,C)=>v(x[$],C)).join(" "));let A=u.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${u.length-A} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,C=g.filter(j=>(x[j.tier??"furniture"]??9)<=$);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-FGCJVXYX.js"),I=j(),D=I?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=C.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
488
488
  `),M=C.length>10?`
489
489
  \u2026and ${C.length-10} more`:"",H=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
490
490
  ${B}${M}
491
491
 
492
- agentx wiki questions`,ge=I?.daemon?.port??I?.port??18800;try{let J=await fetch(`http://127.0.0.1:${ge}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(J.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Q.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-3KUNRM5Z.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=Se(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(I=>[I.name.toLowerCase().trim(),I])),v=0,A=0,S=[],x=!1;e:for(let I of u){let D=f.getAgentWiki(I);for(let B of D.listArticles(I)){if(v>=w)break e;if(B.meta.type!=="person")continue;let M=D.readArticle(B.path);if(!M)continue;v++;let H=await r(s,n({title:M.meta.title,type:M.meta.type,body:M.content}),o(M.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:I,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(M.meta.type,H.answers).missing.filter(N=>i.includes(N));if(J.length===0)continue;let{records:Ee,results:$e}=await a([{name:M.meta.title,type:"person"}],{sources:y}),P=b.get(M.meta.title.toLowerCase().trim());if(!x){for(let N of l($e,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));x=!0}let He=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,fe])=>[N,fe.value]))}]:[],...Ee]);if(He.length===0)continue;let{content:ke,edits:Bo}=p(M.content,He[0],J);if(Bo.length!==0){for(let N of Bo)S.push({agent:I,article:M.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(B.path,M.meta,ke,I)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(I=>Math.max(I.length,...S.map(D=>String(D[I]).length))),j=I=>I.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(j($)));for(let I of S)console.log(j($.map(D=>I[D])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Q.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(yn(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Q.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(yn(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Se(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Q.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-3KUNRM5Z.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Se(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(M=>M.id)),{labeled:y,backlog:k}=r(u,w),b=a(y,M=>M.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:M}=await import("fs");A.push(...JSON.parse(M(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let M of e.load?[]:b){let H=await i(o,n(M),t,{features:{source:M.source??"",absorbed:M.absorbed}});if(!H){S++;continue}let ge=H.answers;A.push({entry:M,verdict:s(H.answers,v),citeWorthy:ge.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:M}=await import("fs");M(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),C=l(A,"seat","seat"),j=d(C,{minN:50}),I=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:S,elapsed:I},null,2));return}let D=M=>`${(M*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let M=$.droppedBy;console.log(m.dim(` dropped by: type ${M.type} \xB7 worth ${M.worth} \xB7 durability ${M.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let M=parseFloat(e.minRecall),{best:H,points:ge}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${ge.length} policies, recall floor ${D(M)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(H.precision)} \xB7 lost ${H.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(M)} recall \u2014 not even keeping everything typed.`));let J=ge.slice().sort((Ee,$e)=>$e.recall-Ee.recall)[0];J&&console.log(m.dim(` Best recall available: ${D(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${D(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Q.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=F(process.cwd(),e);ze(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Uf(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}mg();import{Command as qf}from"commander";import _ from"chalk";import{resolve as ws}from"path";import{existsSync as Wf}from"fs";re();var Rt=new qf().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Rt.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 o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(_.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(_.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new ko({baseDir:ws(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(_.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(_.bold(` Graph review \u2014 ${r.length} pending`)),console.log(_.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=Tn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${_.cyan(w.msgHash.slice(0,8))} ${_.dim(y)} ... `);let k=Bf(w,a,c),b=null;try{b=await Jf(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(_.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(_.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(_.green("APPROVE")+" "+_.dim(A)),e.dryRun)l++;else try{Gf(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(_.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(_.red("REJECT")+" "+_.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(_.yellow("SKIP")+" "+_.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(_.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Rt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=R();if(!o.graph){console.log(_.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=ws(process.cwd(),o.graph.baseDir);if(!Wf(t)){console.log(_.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new ko({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(_.dim(" "),...a)});console.log(),console.log(_.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(_.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Rt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com: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 o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new ko({baseDir:ws(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(_.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let I=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch($){console.log(_.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),u=p===f;u?console.log(_.dim(` schema matches (${r.levels.length} levels)`)):(console.log(_.yellow(" \u26A0 schema levels differ:")),console.log(_.dim(` local: ${p}`)),console.log(_.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(_.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(_.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:l,y=new Map;w.levels.forEach(($,C)=>y.set($.id,C));let k=[...g].sort(($,C)=>(y.get($.level)??99)-(y.get(C.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(C){A++,console.log(_.yellow(` skip node ${$.id}: ${C.message?.slice(0,100)}`))}}console.log(_.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(_.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` \u2713 pulled from ${t}`)),console.log()});function Bf(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
492
+ agentx wiki questions`,ge=I?.daemon?.port??I?.port??18800;try{let J=await fetch(`http://127.0.0.1:${ge}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(J.ok?m.cyan(` Pushed ${C.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Q.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-IPDLEUI5.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=Se(e.dir,e.mode),u=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(I=>[I.name.toLowerCase().trim(),I])),v=0,A=0,S=[],x=!1;e:for(let I of u){let D=f.getAgentWiki(I);for(let B of D.listArticles(I)){if(v>=w)break e;if(B.meta.type!=="person")continue;let M=D.readArticle(B.path);if(!M)continue;v++;let H=await r(s,n({title:M.meta.title,type:M.meta.type,body:M.content}),o(M.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:I,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(M.meta.type,H.answers).missing.filter(N=>i.includes(N));if(J.length===0)continue;let{records:Ee,results:$e}=await a([{name:M.meta.title,type:"person"}],{sources:y}),P=b.get(M.meta.title.toLowerCase().trim());if(!x){for(let N of l($e,y))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));x=!0}let He=c([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([N,fe])=>[N,fe.value]))}]:[],...Ee]);if(He.length===0)continue;let{content:ke,edits:Bo}=p(M.content,He[0],J);if(Bo.length!==0){for(let N of Bo)S.push({agent:I,article:M.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(B.path,M.meta,ke,I)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],C=$.map(I=>Math.max(I.length,...S.map(D=>String(D[I]).length))),j=I=>I.map((D,B)=>String(D).padEnd(C[B])).join(" ");console.log(),console.log(m.bold(j($)));for(let I of S)console.log(j($.map(D=>I[D])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Q.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(yn(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Q.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(yn(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Se(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(p?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Q.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-IPDLEUI5.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Se(e.dir,"graph").getSharedStore(),u=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(M=>M.id)),{labeled:y,backlog:k}=r(u,w),b=a(y,M=>M.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:M}=await import("fs");A.push(...JSON.parse(M(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let M of e.load?[]:b){let H=await i(o,n(M),t,{features:{source:M.source??"",absorbed:M.absorbed}});if(!H){S++;continue}let ge=H.answers;A.push({entry:M,verdict:s(H.answers,v),citeWorthy:ge.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:M}=await import("fs");M(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),C=l(A,"seat","seat"),j=d(C,{minN:50}),I=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:S,elapsed:I},null,2));return}let D=M=>`${(M*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in j)||!j.insufficient)&&console.log(` ECE ${j.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let M=$.droppedBy;console.log(m.dim(` dropped by: type ${M.type} \xB7 worth ${M.worth} \xB7 durability ${M.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let M=parseFloat(e.minRecall),{best:H,points:ge}=g(A,{minRecall:M});if(console.log(),console.log(m.bold(` threshold sweep (${ge.length} policies, recall floor ${D(M)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(H.precision)} \xB7 lost ${H.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(M)} recall \u2014 not even keeping everything typed.`));let J=ge.slice().sort((Ee,$e)=>$e.recall-Ee.recall)[0];J&&console.log(m.dim(` Best recall available: ${D(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${D(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Q.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=F(process.cwd(),e);ze(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");ze(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Uf(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}mg();import{Command as qf}from"commander";import _ from"chalk";import{resolve as ws}from"path";import{existsSync as Wf}from"fs";re();var Rt=new qf().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Rt.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 o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(_.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(_.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new ko({baseDir:ws(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(_.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(_.bold(` Graph review \u2014 ${r.length} pending`)),console.log(_.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,p=0;for(let u=0;u<r.length;u++){let w=r[u],y=Tn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${u+1}/${r.length}] ${_.cyan(w.msgHash.slice(0,8))} ${_.dim(y)} ... `);let k=Bf(w,a,c),b=null;try{b=await Jf(n,t,k,o.dashboard?.token)}catch(S){p++,console.log(_.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(_.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(_.green("APPROVE")+" "+_.dim(A)),e.dryRun)l++;else try{Gf(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(_.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(_.red("REJECT")+" "+_.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(_.yellow("SKIP")+" "+_.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(_.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Rt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=R();if(!o.graph){console.log(_.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=ws(process.cwd(),o.graph.baseDir);if(!Wf(t)){console.log(_.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new ko({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(_.dim(" "),...a)});console.log(),console.log(_.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(_.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Rt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com: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 o=R();if(!o.graph?.enabled){console.log(_.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new ko({baseDir:ws(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(_.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);g=(await j.json()).nodes||[];let I=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch($){console.log(_.red(` fetch failed: ${$.message}`));return}let p=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.id).join(","),u=p===f;u?console.log(_.dim(` schema matches (${r.levels.length} levels)`)):(console.log(_.yellow(" \u26A0 schema levels differ:")),console.log(_.dim(` local: ${p}`)),console.log(_.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(_.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(_.yellow(" keeping local schema; node import may fail if levels disagree")));let w=u?r:l,y=new Map;w.levels.forEach(($,C)=>y.set($.id,C));let k=[...g].sort(($,C)=>(y.get($.level)??99)-(y.get(C.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(C){A++,console.log(_.yellow(` skip node ${$.id}: ${C.message?.slice(0,100)}`))}}console.log(_.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(_.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(_.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(_.green(` \u2713 pulled from ${t}`)),console.log()});function Bf(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
493
493
  `),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
494
494
  `)}async function Jf(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return $r((c?.content||"").toString())}finally{clearTimeout(r)}}function Gf(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Gi(){let e=R();if(!e.graph?.baseDir)return console.log(_.red(" graph.baseDir is not configured")),null;let o=ws(process.cwd(),e.graph.baseDir);return{store:new ko({baseDir:o}),baseDir:o}}var Hi=Rt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Hi.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=Gi();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(_.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):_.dim("cache");console.log(` ${_.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${_.bold(Tn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(_.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(_.dim(` ${r.length} to check (${e.strategy}).`)),console.log(_.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Hi.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(_.red(" verdict must be correct | wrong | unsure"));return}let n=Gi();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(_.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(_.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(_.green(` ${o}: ${Tn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(_.dim(` should have been: ${t.path}`))});Hi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Gi();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${_.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(_.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?_.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(_.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(_.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as Xf}from"commander";import Y from"chalk";import{Command as bd}from"commander";import ce from"chalk";import{existsSync as Hf}from"fs";import{resolve as zf}from"path";import Yf from"better-sqlite3";function Vf(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(ce.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Kf(e){let o=zf(process.cwd(),e);return Hf(o)||(console.log(ce.red(` No db at ${o}`)),process.exit(1)),new Yf(o,{readonly:!0})}var $d=new bd().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(zt)).option("--max <n>","max clusters distilled per run",String(jn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(ce.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Kf(e.path),t=await sa(o,{since:Vf(e.since),agentId:e.agent,sessions:new Or(process.cwd()),minOccurrences:Number(e.minOccurrences)||zt,max:Number(e.max)||jn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ce.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${ce.cyan(n.key)} ${ce.bold(`\xD7${n.count}`)} ${ce.dim(n.status)}`),n.sampleMessage&&console.log(ce.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ce.dim(`
495
495
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ce.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ce.green(` \u2713 draft written: ${n.id}`)+ce.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ce.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ce.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ce.dim(`
@@ -522,7 +522,7 @@ agentx wiki questions`,ge=I?.daemon?.port??I?.port??18800;try{let J=await fetch(
522
522
  `))});Fo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new mt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Fo.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new mt().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Rr(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});Fo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function wh(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}re();import{Command as bh}from"commander";import ee from"chalk";var Pd=new bh().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=R(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(ee.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(ee.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(ee.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let p;for(;(p=l.indexOf(`
523
523
 
524
524
  `))>=0;){let f=l.slice(0,p);l=l.slice(p+2),$h(f)}}}catch(r){console.error(ee.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function $h(e){let o="message",t="";for(let i of e.split(`
525
- `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ee.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ee.cyan(n.phase?.padEnd(9)??"run"),r=ee.bold(n.workflowId??""),a=ee.dim((n.runId??"").slice(0,8)),c=n.nodeId?ee.yellow(n.nodeId):"",l=n.note?ee.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ee.magenta(`task.${n.phase}`.padEnd(14)),r=ee.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ee.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ee.cyan(a)} ${c}`);break}case"signal":{let i=ee.green("signal".padEnd(9)),r=ee.bold(n.name),a=ee.dim(`(${n.scope})`),c=n.workflowId?ee.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ee.blue("mesh".padEnd(9)),r=ee.bold(n.peer),a=n.healthy?ee.green("\u2713 healthy"):ee.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ee.dim(n.delta??"")}`);break}case"channel":{let i=ee.yellow("channel".padEnd(9)),r=n.direction==="in"?ee.cyan("\u2190"):ee.magenta("\u2192"),a=ee.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ee.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ee.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as vh}from"commander";import Es from"chalk";import{spawn as xh}from"node:child_process";import{execFileSync as kh}from"node:child_process";function Md(e=()=>kh("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var Ld=new vh().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(Es.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-I7GAAM3T.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Md();if(n?.ok){let{fetchAgents:l}=await import("./client-I7GAAM3T.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${d}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Es.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=xh("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Es.yellow(n.reason)),console.error(Es.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-QVNQ5BQK.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as Sh}from"commander";import V from"chalk";import{randomUUID as qd}from"crypto";import{createInterface as Eh}from"node:readline/promises";import Ah from"ora";import As from"chalk";function Fd(e){console.error(),console.error(As.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(As.dim(` ${e.why}`)),console.error(),console.error(` Use ${As.cyan(e.instead)} instead.`),e.note&&console.error(As.dim(` ${e.note}`)),console.error()}var Ud={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var Wd=new Sh().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{Fd({what:"agentx chat",...Ud});let t=gc({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${qd().slice(0,12)}`,r=[];try{r=await Wn(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-CC57XC23.js"),p=(await import("react")).default;await g(p.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Oh(t.baseUrl,n,i,s);let a=Eh({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(V.dim(`
525
+ `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ee.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ee.cyan(n.phase?.padEnd(9)??"run"),r=ee.bold(n.workflowId??""),a=ee.dim((n.runId??"").slice(0,8)),c=n.nodeId?ee.yellow(n.nodeId):"",l=n.note?ee.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ee.magenta(`task.${n.phase}`.padEnd(14)),r=ee.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ee.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ee.cyan(a)} ${c}`);break}case"signal":{let i=ee.green("signal".padEnd(9)),r=ee.bold(n.name),a=ee.dim(`(${n.scope})`),c=n.workflowId?ee.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ee.blue("mesh".padEnd(9)),r=ee.bold(n.peer),a=n.healthy?ee.green("\u2713 healthy"):ee.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ee.dim(n.delta??"")}`);break}case"channel":{let i=ee.yellow("channel".padEnd(9)),r=n.direction==="in"?ee.cyan("\u2190"):ee.magenta("\u2192"),a=ee.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ee.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ee.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as vh}from"commander";import Es from"chalk";import{spawn as xh}from"node:child_process";import{execFileSync as kh}from"node:child_process";function Md(e=()=>kh("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var Ld=new vh().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(Es.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-AVQSLPIZ.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Md();if(n?.ok){let{fetchAgents:l}=await import("./client-AVQSLPIZ.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${d}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Es.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=xh("opencode",["--standalone"],{stdio:"inherit",env:u});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Es.yellow(n.reason)),console.error(Es.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-X6FGYBLX.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as Sh}from"commander";import V from"chalk";import{randomUUID as qd}from"crypto";import{createInterface as Eh}from"node:readline/promises";import Ah from"ora";import As from"chalk";function Fd(e){console.error(),console.error(As.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(As.dim(` ${e.why}`)),console.error(),console.error(` Use ${As.cyan(e.instead)} instead.`),e.note&&console.error(As.dim(` ${e.note}`)),console.error()}var Ud={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var Wd=new Sh().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{Fd({what:"agentx chat",...Ud});let t=gc({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${qd().slice(0,12)}`,r=[];try{r=await Wn(t)}catch(g){console.error(V.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(V.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(V.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(V.red(` unknown agent: @${n}`)),console.error(V.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(V.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-XMUOXQ2M.js"),p=(await import("react")).default;await g(p.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Oh(t.baseUrl,n,i,s);let a=Eh({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(V.dim(`
526
526
  bye`)),process.exit(0)});;){let g;try{g=(await a.question(V.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(V.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${qd().slice(0,12)}`,console.log(V.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await Wn(t);for(let w of u){let y=w.id===n?V.green("\u25CF"):V.dim("\u25CB");console.log(` ${y} @${w.id} ${V.dim(w.tier)} ${w.model??""}`)}}catch(u){console.error(V.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(V.red(" usage: /agent <id>"));continue}try{if(!(await Wn(t)).find(y=>y.id===u)){console.log(V.red(` unknown agent: @${u}`));continue}n=u,console.log(V.dim(` now talking to @${n}`))}catch(w){console.error(V.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(V.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(V.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=Ah({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Th(n);try{let u=await mc(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-p)/100)/10;u.error?f.finishError(u.error):f.finish(w,u.usage)}catch(u){d.stop(),f.finishError(u?.message||String(u))}finally{c=!1}if(l){console.log(V.dim(" bye"));return}}});function Th(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${V.green(`@${e}`)}
527
527
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
528
528
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
@@ -615,7 +615,7 @@ Restart the daemon to activate.
615
615
  dist/
616
616
  *.log
617
617
  .env
618
- `}import{Command as cy}from"commander";import je from"chalk";import{writeFileSync as ly,mkdirSync as dy,existsSync as Ns,readFileSync as Zd,appendFileSync as eg}from"fs";import{resolve as qt,dirname as ng}from"path";import{homedir as dr}from"os";var sg=new cy().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:o}=await import("./program-UXJWH5JG.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=py(t);break;case"bash":s=wy(t);break;case"fish":s=by(t);break;default:console.error(je.red(`unsupported shell: ${n}`)),console.error(je.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?qt(String(e.output)):gy(n);dy(ng(i),{recursive:!0}),ly(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),my(n,i,!!e.yes)});function gy(e){let o=dr();switch(e){case"zsh":return qt(o,".zsh","completions","_agentx");case"bash":return qt(o,".bash_completion.d","agentx.bash");case"fish":return qt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function my(e,o,t){if(e==="zsh"){let n=qt(dr(),".zshrc"),s=ng(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ns(n)?Zd(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(je.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ns(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),eg(n,g.join(`
618
+ `}import{Command as cy}from"commander";import je from"chalk";import{writeFileSync as ly,mkdirSync as dy,existsSync as Ns,readFileSync as Zd,appendFileSync as eg}from"fs";import{resolve as qt,dirname as ng}from"path";import{homedir as dr}from"os";var sg=new cy().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:o}=await import("./program-MNFDOQGQ.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=py(t);break;case"bash":s=wy(t);break;case"fish":s=by(t);break;default:console.error(je.red(`unsupported shell: ${n}`)),console.error(je.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?qt(String(e.output)):gy(n);dy(ng(i),{recursive:!0}),ly(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),my(n,i,!!e.yes)});function gy(e){let o=dr();switch(e){case"zsh":return qt(o,".zsh","completions","_agentx");case"bash":return qt(o,".bash_completion.d","agentx.bash");case"fish":return qt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function my(e,o,t){if(e==="zsh"){let n=qt(dr(),".zshrc"),s=ng(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ns(n)?Zd(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(je.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ns(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),eg(n,g.join(`
619
619
  `)+`
620
620
  `),console.log(je.green("\u2713 Patched ~/.zshrc")),console.log(je.dim("Reload your shell: exec zsh"));return}console.log(je.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(je.cyan(` ${i}`)),l&&console.log(je.cyan(` ${r}`)),console.log(),console.log(je.dim("Then reload: exec zsh")),console.log(je.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=qt(dr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ns(n)?Zd(n,"utf-8"):"").includes(o)){console.log(je.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ns(n)){eg(n,`
621
621
  # agentx completion
@@ -626,4 +626,4 @@ ${s}
626
626
  `)}function gr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function lr(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=gr(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function YA(){let e=await ec(),o=new $y().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");o.hook("preAction",(t,n)=>{let s=ac(n);cc(s)&&rc("cli",s)});for(let t of[Pc,Rc,Nt,wt,on,Ve,nc,zo,Xn,yo,Do,ot,Kn,Ld,No,ol,dl,ln,kl,El,Al,Bl,zl,Yl,gs,un,Bd,en,To,sg])o.addCommand(t);for(let t of rg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=rg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,ky(t,74," "),""].join(`
627
627
  `)}),o}var rg=[Q,Rt,Uo,no,nn,It,Je,bo,Po,tt,Mt,Lt,jo,qe,Et,ms,Pd,fo,xt,pc,Yo,xn,di,Fo,vt,gi,Ss,Mo,qo,Yd,Kd,Wd];function ky(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
628
628
  `)}export{YA as a};
629
- //# sourceMappingURL=chunk-UL4E2CV4.js.map
629
+ //# sourceMappingURL=chunk-AKAM4BNC.js.map