agentix-cli 0.78.0 → 0.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/{App-UNWLWLH5.js → App-NZQQXETO.js} +2 -2
  2. package/dist/{ChatApp-UBSOVFRK.js → ChatApp-CSVN3PRK.js} +2 -2
  3. package/dist/{agent-XWWWL5RV.js → agent-RTZDVG5B.js} +2 -2
  4. package/dist/{board-dashboard-ABEIELBC.js → board-dashboard-SI5GP3XR.js} +4 -4
  5. package/dist/{board-dashboard-ABEIELBC.js.map → board-dashboard-SI5GP3XR.js.map} +1 -1
  6. package/dist/{chunk-H4RCKWJA.js → chunk-2WRWBPDL.js} +2 -2
  7. package/dist/{chunk-SLQZ4AHG.js → chunk-2XSVV3M3.js} +2 -2
  8. package/dist/chunk-2YIWQ57T.js +22 -0
  9. package/dist/chunk-2YIWQ57T.js.map +1 -0
  10. package/dist/{chunk-U6XM4M5V.js → chunk-3AFZBXNX.js} +2 -2
  11. package/dist/{chunk-JVJYCR67.js → chunk-3OIFSKSR.js} +2 -2
  12. package/dist/{chunk-FWDWHZ6H.js → chunk-B5VRY4NI.js} +2 -2
  13. package/dist/{chunk-4EJ65BMF.js → chunk-DTKTEQPC.js} +194 -194
  14. package/dist/chunk-DTKTEQPC.js.map +1 -0
  15. package/dist/{chunk-2XICJMS6.js → chunk-EOBFJGTV.js} +30 -30
  16. package/dist/chunk-EOBFJGTV.js.map +1 -0
  17. package/dist/{chunk-4STRKIUA.js → chunk-IWQURDYO.js} +2 -2
  18. package/dist/{chunk-WEUF5WRR.js → chunk-IXWPA6WM.js} +2 -2
  19. package/dist/chunk-KH4PKJGD.js +15 -0
  20. package/dist/chunk-KH4PKJGD.js.map +1 -0
  21. package/dist/{chunk-53J2D2ZJ.js → chunk-N2A3KIVY.js} +2 -2
  22. package/dist/{chunk-NWP44FEW.js → chunk-P5KHF46N.js} +2 -2
  23. package/dist/{chunk-GTZDTKDW.js → chunk-PF5ZXMEG.js} +2 -2
  24. package/dist/{chunk-TVORP6BW.js → chunk-QAKL2D7O.js} +2 -2
  25. package/dist/{chunk-GX4U2ILS.js → chunk-QIMIARFO.js} +2 -2
  26. package/dist/{chunk-R7AS5M32.js → chunk-SYXAEWFN.js} +5 -5
  27. package/dist/{chunk-IMVW5ZSY.js → chunk-THZOPGSP.js} +2 -2
  28. package/dist/{chunk-KEPK7ZZ2.js → chunk-TQT4XDNN.js} +2 -2
  29. package/dist/{chunk-JQXP3JWF.js → chunk-VIUCCUJ4.js} +2 -2
  30. package/dist/{chunk-FSVUSXJB.js → chunk-YX5S4FHR.js} +17 -17
  31. package/dist/{chunk-FSVUSXJB.js.map → chunk-YX5S4FHR.js.map} +1 -1
  32. package/dist/{chunk-6HUDHMAC.js → chunk-ZBRZ5T2G.js} +2 -2
  33. package/dist/cli.js +1 -1
  34. package/dist/client-TZPRACLX.js +2 -0
  35. package/dist/{config-44LINWKG.js → config-OQVGSZWB.js} +2 -2
  36. package/dist/config-mutator-BA7YVYJY.js +2 -0
  37. package/dist/{doctor-OXR3VXX6.js → doctor-NHEB7IMW.js} +2 -2
  38. package/dist/{editor-chat-V24MXQIB.js → editor-chat-4MLCP5D2.js} +5 -3
  39. package/dist/editor-chat-4MLCP5D2.js.map +1 -0
  40. package/dist/index.d.ts +13 -3
  41. package/dist/index.js +1 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/program-N3AVBQMK.js +2 -0
  44. package/dist/{promote-72BY34SI.js → promote-O6Y2RG4K.js} +2 -2
  45. package/dist/{query-AJO3NOO6.js → query-J3XX5U3P.js} +2 -2
  46. package/dist/registry-DBLLSQ75.js +2 -0
  47. package/dist/{request-planner-Q74NYFRJ.js → request-planner-NP2XHSMV.js} +2 -2
  48. package/dist/{review-candidates-ZBBIPFJT.js → review-candidates-J3OBF4GM.js} +2 -2
  49. package/dist/{routing-7VU524EZ.js → routing-VTQBG767.js} +2 -2
  50. package/dist/schedule-tool-RQBVG3ZJ.js +2 -0
  51. package/dist/scheduler-BHXA74R6.js +2 -0
  52. package/dist/{seat-MKY332GD.js → seat-NBQOUDGU.js} +2 -2
  53. package/dist/{select-FZX63JK5.js → select-T5FEWTZA.js} +2 -2
  54. package/dist/{set-enabled-RNDSUIYU.js → set-enabled-2GHZXDEA.js} +2 -2
  55. package/dist/{tool-XBSFEGWW.js → tool-6WLJTCE5.js} +2 -2
  56. package/dist/web/workflow-editor.global.js +10 -10
  57. package/dist/web/workflow-editor.global.js.map +1 -1
  58. package/dist/wiki-ZB6KMJKX.js +2 -0
  59. package/package.json +1 -1
  60. package/dist/chunk-2XICJMS6.js.map +0 -1
  61. package/dist/chunk-4EJ65BMF.js.map +0 -1
  62. package/dist/chunk-DBXN7I2X.js +0 -15
  63. package/dist/chunk-DBXN7I2X.js.map +0 -1
  64. package/dist/chunk-LQJNRSCT.js +0 -21
  65. package/dist/chunk-LQJNRSCT.js.map +0 -1
  66. package/dist/client-OAAE3KM5.js +0 -2
  67. package/dist/config-mutator-P6QEABPU.js +0 -2
  68. package/dist/editor-chat-V24MXQIB.js.map +0 -1
  69. package/dist/program-X7ROPRQP.js +0 -2
  70. package/dist/registry-AFNYREN2.js +0 -2
  71. package/dist/schedule-tool-6RRXRW5K.js +0 -2
  72. package/dist/scheduler-WA4KTCCU.js +0 -2
  73. package/dist/wiki-ZOK6XGIX.js +0 -2
  74. /package/dist/{App-UNWLWLH5.js.map → App-NZQQXETO.js.map} +0 -0
  75. /package/dist/{ChatApp-UBSOVFRK.js.map → ChatApp-CSVN3PRK.js.map} +0 -0
  76. /package/dist/{agent-XWWWL5RV.js.map → agent-RTZDVG5B.js.map} +0 -0
  77. /package/dist/{chunk-H4RCKWJA.js.map → chunk-2WRWBPDL.js.map} +0 -0
  78. /package/dist/{chunk-SLQZ4AHG.js.map → chunk-2XSVV3M3.js.map} +0 -0
  79. /package/dist/{chunk-U6XM4M5V.js.map → chunk-3AFZBXNX.js.map} +0 -0
  80. /package/dist/{chunk-JVJYCR67.js.map → chunk-3OIFSKSR.js.map} +0 -0
  81. /package/dist/{chunk-FWDWHZ6H.js.map → chunk-B5VRY4NI.js.map} +0 -0
  82. /package/dist/{chunk-4STRKIUA.js.map → chunk-IWQURDYO.js.map} +0 -0
  83. /package/dist/{chunk-WEUF5WRR.js.map → chunk-IXWPA6WM.js.map} +0 -0
  84. /package/dist/{chunk-53J2D2ZJ.js.map → chunk-N2A3KIVY.js.map} +0 -0
  85. /package/dist/{chunk-NWP44FEW.js.map → chunk-P5KHF46N.js.map} +0 -0
  86. /package/dist/{chunk-GTZDTKDW.js.map → chunk-PF5ZXMEG.js.map} +0 -0
  87. /package/dist/{chunk-TVORP6BW.js.map → chunk-QAKL2D7O.js.map} +0 -0
  88. /package/dist/{chunk-GX4U2ILS.js.map → chunk-QIMIARFO.js.map} +0 -0
  89. /package/dist/{chunk-R7AS5M32.js.map → chunk-SYXAEWFN.js.map} +0 -0
  90. /package/dist/{chunk-IMVW5ZSY.js.map → chunk-THZOPGSP.js.map} +0 -0
  91. /package/dist/{chunk-KEPK7ZZ2.js.map → chunk-TQT4XDNN.js.map} +0 -0
  92. /package/dist/{chunk-JQXP3JWF.js.map → chunk-VIUCCUJ4.js.map} +0 -0
  93. /package/dist/{chunk-6HUDHMAC.js.map → chunk-ZBRZ5T2G.js.map} +0 -0
  94. /package/dist/{client-OAAE3KM5.js.map → client-TZPRACLX.js.map} +0 -0
  95. /package/dist/{config-44LINWKG.js.map → config-OQVGSZWB.js.map} +0 -0
  96. /package/dist/{config-mutator-P6QEABPU.js.map → config-mutator-BA7YVYJY.js.map} +0 -0
  97. /package/dist/{doctor-OXR3VXX6.js.map → doctor-NHEB7IMW.js.map} +0 -0
  98. /package/dist/{program-X7ROPRQP.js.map → program-N3AVBQMK.js.map} +0 -0
  99. /package/dist/{promote-72BY34SI.js.map → promote-O6Y2RG4K.js.map} +0 -0
  100. /package/dist/{query-AJO3NOO6.js.map → query-J3XX5U3P.js.map} +0 -0
  101. /package/dist/{registry-AFNYREN2.js.map → registry-DBLLSQ75.js.map} +0 -0
  102. /package/dist/{request-planner-Q74NYFRJ.js.map → request-planner-NP2XHSMV.js.map} +0 -0
  103. /package/dist/{review-candidates-ZBBIPFJT.js.map → review-candidates-J3OBF4GM.js.map} +0 -0
  104. /package/dist/{routing-7VU524EZ.js.map → routing-VTQBG767.js.map} +0 -0
  105. /package/dist/{schedule-tool-6RRXRW5K.js.map → schedule-tool-RQBVG3ZJ.js.map} +0 -0
  106. /package/dist/{scheduler-WA4KTCCU.js.map → scheduler-BHXA74R6.js.map} +0 -0
  107. /package/dist/{seat-MKY332GD.js.map → seat-NBQOUDGU.js.map} +0 -0
  108. /package/dist/{select-FZX63JK5.js.map → select-T5FEWTZA.js.map} +0 -0
  109. /package/dist/{set-enabled-RNDSUIYU.js.map → set-enabled-2GHZXDEA.js.map} +0 -0
  110. /package/dist/{tool-XBSFEGWW.js.map → tool-6WLJTCE5.js.map} +0 -0
  111. /package/dist/{wiki-ZOK6XGIX.js.map → wiki-ZB6KMJKX.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as fl,b as us,g as hl}from"./chunk-KEPK7ZZ2.js";import{a as rl,c as al}from"./chunk-H4RCKWJA.js";import{a as Qe,b as tl,f as nl,g as sl,h as il,i as jt,j as cl,k as ll,l as Ii,m as pl,o as ul}from"./chunk-SLQZ4AHG.js";import{a as dl,c as gl,d as ml}from"./chunk-Z3IP66SL.js";import{a as yi,b as Ra}from"./chunk-RKPAVWXF.js";import{c as va}from"./chunk-SZDACK6O.js";import{a as xt}from"./chunk-GV7S5BAX.js";import{e as ka}from"./chunk-GSX4NK2N.js";import{$ as Yc,A as Ac,B as Tc,C as bi,D as Oc,E as jc,F as Cc,G as Ic,H as Nc,I as Rc,J as Fc,K as qc,L as Wc,M as Et,N as ds,O as Ei,P as Bc,Q as Jc,R as Hc,S as Gc,T as At,U as Tt,V as zc,W as Vc,X as _e,Y as gs,Z as wn,_ as Ai,a as Ia,aa as Qc,b as Na,ba as ji,c as un,ca as el,d as qa,da as ms,e as Wa,ea as Ot,fa as ps,ga as Ci,ha as ol,k as os,l as Ga,m as fn,n as ts,o as Ya,p as Ka,q as cc,r as lc,s as rs,t as $i,u as uc,v as $c,w as bc,x as xc,y as Sc,z as Ec}from"./chunk-4EJ65BMF.js";import{Aa as Si,L as wc,M as as,Ra as Kc,Sa as Ti,Ta as Xc,Ua as Oi,Z as hn,aa as ki,ba as cs,ca as _c,gb as po,ib as Zc,ja as Ro,ka as Dc,la as vi,na as xi,p as No,pa as Pc,qa as Mc,ra as yn,t as fc,va as ls,w as hc,y as yc,ya as Lc,za as Uc}from"./chunk-2XICJMS6.js";import{a as Ba,d as Ja,e as Ha}from"./chunk-WEUF5WRR.js";import{a as ns,b as ss,c as Xa,d as Qa,e as Za,g as ec,h as oc,j as tc,k as nc,l as sc,m as ic,p as is,s as rc,t as ac}from"./chunk-S2GAEH2F.js";import{a as za,p as Va}from"./chunk-JVJYCR67.js";import{a as dc,b as gc,c as mc,d as pc}from"./chunk-2D3RYIDU.js";import{a as kc,b as vc}from"./chunk-EKJG63EJ.js";import{C as Io,I as ja,T as Ca,g as ua,p as fa,w as ui,x as $a}from"./chunk-R7AS5M32.js";import{b as $t,g as kt,h as Zn,i as es,j as vt,k as ba,l as Xo,m as pn}from"./chunk-LQJNRSCT.js";import{e as Aa,f as hi,k as Ta}from"./chunk-WP6KLXTP.js";import{a as Xn}from"./chunk-N6EWZGIX.js";import{b as bt}from"./chunk-DP7RTNDM.js";import{a as wi,e as _a,f as Da,h as Pa,i as Ma,k as La,l as Ua,m as Fa}from"./chunk-4STRKIUA.js";import{f as xa,g as Sa,h as fi}from"./chunk-76Z4VHDX.js";import{a as ya,k as Ea}from"./chunk-FWDWHZ6H.js";import{b as pe,c as je,d as St,e as Oa}from"./chunk-53J2D2ZJ.js";import{a as mi}from"./chunk-NWP44FEW.js";import{a as pi,b as ha}from"./chunk-GQ76J72O.js";import{j as wa}from"./chunk-X5C5W3E4.js";import{h as pa}from"./chunk-DWADWDMU.js";import{g as Co,i as Qn}from"./chunk-JQXP3JWF.js";import{b as wt,d as ma}from"./chunk-2GIDVZ4H.js";import{a as gi,b as Kr,c as Lm,d as Yn,e as Xr,f as ra,g as qm,h as aa,i as Wm,m as yt,n as la,o as da,s as ga,v as mo,w as mn}from"./chunk-TVORP6BW.js";import{a as ca,b as Bm}from"./chunk-FX3D7YON.js";import{a as bo,b as ht,e as na,f as gn}from"./chunk-72SZI2UW.js";import{a as $o,b as Mm}from"./chunk-7I7IEX4S.js";import{A as C,B as Kn,D as ne,m as Qr,n as Zr,p as ea,q as Um,y as oa,z as ta}from"./chunk-DBXN7I2X.js";import{g as sa,k as ia,l as Fm}from"./chunk-RGDKHYY2.js";import{Command as Jm}from"commander";var yl=new Jm().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 Wa({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()});ne();import{Command as Hm}from"commander";import{execFileSync as eo}from"node:child_process";import{cpSync as wl,existsSync as _i,mkdirSync as Ni,mkdtempSync as Gm,readdirSync as zm,rmSync as $l,writeFileSync as bl}from"node:fs";import{dirname as kl,join as Pe}from"node:path";import{homedir as fs,release as Vm,tmpdir as Ym}from"node:os";import{setTimeout as Km}from"node:timers/promises";function hs(){let e=Xa(process.platform,process.arch,Vm());if(e)throw new Error(e)}function ys(){let e=Pe(fs(),"Library/LaunchAgents"),o=[];try{o=zm(e).filter(ec)}catch{}let t=o.flatMap(n=>{let s=Pe(e,n);try{return[{file:s,plist:eo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return oc(e,t)}function $n(e){return`gui/${process.getuid()}/${e.label}`}async function Ri(e){try{eo("launchctl",["bootout",$n(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{eo("launchctl",["print",$n(e)],{stdio:"pipe"})}catch{return}await Km(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function vl(e){if(!_i(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{eo("launchctl",["print",$n(e)],{stdio:"pipe"})}catch{o=!1}o||eo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),eo("launchctl",["kickstart",$n(e)],{stdio:"pipe"})}function Xm(){let e=ic();if(e&&_i(Pe(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 Ct=new Hm("desktop").description("install and control the macOS desktop assistant");Ct.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=>{hs();let o=C(),t=Qa(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=Xm(),r=Pe(fs(),"Applications"),{keep:a,remove:c}=ys();if(console.log(`Desktop assistant \u2192 ${Pe(r,ns)}
1
+ import{a as fl,b as us,g as hl}from"./chunk-TQT4XDNN.js";import{a as rl,c as al}from"./chunk-2WRWBPDL.js";import{a as Qe,b as tl,f as nl,g as sl,h as il,i as jt,j as cl,k as ll,l as Ii,m as pl,o as ul}from"./chunk-2XSVV3M3.js";import{a as dl,c as gl,d as ml}from"./chunk-Z3IP66SL.js";import{a as yi,b as Ra}from"./chunk-RKPAVWXF.js";import{$ as Yc,A as Ac,B as Tc,C as bi,D as Oc,E as jc,F as Cc,G as Ic,H as Nc,I as Rc,J as Fc,K as Et,L as ds,M as Ei,N as qc,O as Wc,P as Bc,Q as Jc,R as Hc,S as Gc,T as At,U as Tt,V as zc,W as Vc,X as _e,Y as gs,Z as wn,_ as Ai,a as Ia,aa as Qc,b as Na,ba as ji,c as un,ca as el,d as qa,da as ms,e as Wa,ea as Ot,fa as ps,ga as Ci,ha as ol,k as os,l as Ga,m as fn,n as ts,o as Ya,p as Ka,q as cc,r as lc,s as rs,t as $i,u as uc,v as $c,w as bc,x as xc,y as Sc,z as Ec}from"./chunk-DTKTEQPC.js";import{Aa as Si,L as wc,M as as,Qa as Kc,Ra as Ti,Sa as Xc,Ta as Oi,Z as hn,aa as ki,ba as cs,ca as _c,fb as po,hb as Zc,ja as Ro,ka as Dc,la as vi,na as xi,p as No,pa as Pc,qa as Mc,ra as yn,t as fc,va as ls,w as hc,y as yc,ya as Lc,za as Uc}from"./chunk-EOBFJGTV.js";import{a as Ba,d as Ja,e as Ha}from"./chunk-IXWPA6WM.js";import{a as ns,b as ss,c as Xa,d as Qa,e as Za,g as ec,h as oc,j as tc,k as nc,l as sc,m as ic,p as is,s as rc,t as ac}from"./chunk-S2GAEH2F.js";import{a as za,p as Va}from"./chunk-3OIFSKSR.js";import{a as dc,b as gc,c as mc,d as pc}from"./chunk-2D3RYIDU.js";import{a as kc,b as vc}from"./chunk-EKJG63EJ.js";import{C as Io,I as ja,T as Ca,g as ua,p as fa,w as ui,x as $a}from"./chunk-SYXAEWFN.js";import{b as $t,g as kt,h as Zn,i as es,j as vt,k as ba,l as Xo,m as pn}from"./chunk-2YIWQ57T.js";import{e as Aa,f as hi,k as Ta}from"./chunk-WP6KLXTP.js";import{a as Xn}from"./chunk-N6EWZGIX.js";import{b as bt}from"./chunk-DP7RTNDM.js";import{a as wi,e as _a,f as Da,h as Pa,i as Ma,k as La,l as Ua,m as Fa}from"./chunk-IWQURDYO.js";import{c as va}from"./chunk-SZDACK6O.js";import{f as xa,g as Sa,h as fi}from"./chunk-76Z4VHDX.js";import{a as ya,k as Ea}from"./chunk-B5VRY4NI.js";import{b as pe,c as je,d as St,e as Oa}from"./chunk-N2A3KIVY.js";import{a as mi}from"./chunk-P5KHF46N.js";import{a as pi,b as ha}from"./chunk-GQ76J72O.js";import{j as wa}from"./chunk-X5C5W3E4.js";import{a as xt}from"./chunk-GV7S5BAX.js";import{e as ka}from"./chunk-GSX4NK2N.js";import{h as pa}from"./chunk-DWADWDMU.js";import{g as Co,i as Qn}from"./chunk-VIUCCUJ4.js";import{b as wt,d as ma}from"./chunk-2GIDVZ4H.js";import{a as gi,b as Kr,c as Lm,d as Yn,e as Xr,f as ra,g as qm,h as aa,i as Wm,m as yt,n as la,o as da,s as ga,v as mo,w as mn}from"./chunk-QAKL2D7O.js";import{a as ca,b as Bm}from"./chunk-FX3D7YON.js";import{a as bo,b as ht,e as na,f as gn}from"./chunk-72SZI2UW.js";import{a as $o,b as Mm}from"./chunk-7I7IEX4S.js";import{C as oa,D as ta,E as C,F as Kn,H as ne,m as Qr,n as Zr,p as ea,q as Um}from"./chunk-KH4PKJGD.js";import{g as sa,k as ia,l as Fm}from"./chunk-RGDKHYY2.js";import{Command as Jm}from"commander";var yl=new Jm().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 Wa({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()});ne();import{Command as Hm}from"commander";import{execFileSync as eo}from"node:child_process";import{cpSync as wl,existsSync as _i,mkdirSync as Ni,mkdtempSync as Gm,readdirSync as zm,rmSync as $l,writeFileSync as bl}from"node:fs";import{dirname as kl,join as Pe}from"node:path";import{homedir as fs,release as Vm,tmpdir as Ym}from"node:os";import{setTimeout as Km}from"node:timers/promises";function hs(){let e=Xa(process.platform,process.arch,Vm());if(e)throw new Error(e)}function ys(){let e=Pe(fs(),"Library/LaunchAgents"),o=[];try{o=zm(e).filter(ec)}catch{}let t=o.flatMap(n=>{let s=Pe(e,n);try{return[{file:s,plist:eo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return oc(e,t)}function $n(e){return`gui/${process.getuid()}/${e.label}`}async function Ri(e){try{eo("launchctl",["bootout",$n(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{eo("launchctl",["print",$n(e)],{stdio:"pipe"})}catch{return}await Km(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function vl(e){if(!_i(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{eo("launchctl",["print",$n(e)],{stdio:"pipe"})}catch{o=!1}o||eo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),eo("launchctl",["kickstart",$n(e)],{stdio:"pipe"})}function Xm(){let e=ic();if(e&&_i(Pe(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 Ct=new Hm("desktop").description("install and control the macOS desktop assistant");Ct.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=>{hs();let o=C(),t=Qa(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=Xm(),r=Pe(fs(),"Applications"),{keep:a,remove:c}=ys();if(console.log(`Desktop assistant \u2192 ${Pe(r,ns)}
2
2
  Computer-use helper \u2192 ${Pe(r,ss)}
3
3
  Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -27,7 +27,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
27
27
  `))});function Ip(e){let o=Math.round(nl/6e4),t=[` Pairing code: ${Ee.bold.cyan(sl(e.code))}`,Ee.dim(` Open the app from the phone's home screen and type this code. It works once, for ${o} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Ee.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Ee.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||t.push(Ee.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function Np(){let e;try{e=JSON.parse(Wl("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 Rp=new Set(["/app","/api/app"]);function _p(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&&!Rp.has(g)&&n.push(`${i}${a}`)}return n}function Dp(){try{return JSON.parse(Wl("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Fi(){try{return C().dashboard.port||4202}catch{return 4202}}ne();import{Command as fo}from"commander";import y from"chalk";import De from"prompts";import{readFileSync as Do,writeFileSync as _t,existsSync as he,mkdirSync as uo,cpSync as qi,readdirSync as Bi}from"fs";import{resolve as H,join as _o,dirname as Pp}from"path";import{fileURLToPath as Mp}from"url";function le(){let e=H(process.cwd(),"agentx.json");if(!he(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Do(e,"utf-8"))}function qe(e){return pe(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(y.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var et=new fo().name("agent").description("manage agents \u2014 add, list, remove");et.command("list").alias("ls").description("list configured agents").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${y.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(y.dim(` workspace: ${t.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});et.command("add").description("add a new agent interactively").action(async()=>{let e=le(),o=await De([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:H(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:_o(o.workspace,o.id);uo(H(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(y.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Pp(Mp(import.meta.url)),"../wiki/SKILL.md"),c=he(r)?r:a;he(c)&&(uo(H(t,".claude/skills/wiki"),{recursive:!0}),qi(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await qe(e),console.log(y.green(`
28
28
  Agent "${o.id}" added`)),console.log(y.dim(` Workspace: ${t}`)),console.log(y.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});et.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=le();if(!o.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete o.agents[e],await qe(o),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});et.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=le(),n=t.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.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(y.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(y.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(y.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(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await qe(t),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Sn=new fo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Sn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=le().agents?.[e];n||(console.log(y.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(y.dim(`
29
29
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
30
- `));return}console.log(),console.log(y.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]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?y.cyan(i.kind.padEnd(14)):y.dim(i.kind.padEnd(14))} ${y.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),r||console.log(` ${y.dim("(disabled)")}`)}console.log()});Sn.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=le();t.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-44LINWKG.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await De({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(y.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await De({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(y.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 u=await De({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"}]});u.scheme==="tokenEnv"?a=((await De({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await De({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await De({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...h]=f.split("=");p&&(g[p.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.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(y.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(u=>u.kind===i&&u.label===r)&&(console.log(y.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 qe(t),console.log(y.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Sn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=le(),n=t.agents?.[e];n||(console.log(y.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(y.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await qe(t),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Sn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=le().agents?.[e];n||(console.log(y.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(y.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(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});et.addCommand(Sn);var xs=new fo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");xs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=le();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(y.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${y.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(y.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(y.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(y.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(y.dim(" GitLab: disabled"));console.log()});xs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=le(),o=Object.keys(e.agents||{});if(!o.length){console.log(y.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 De({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await De([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices: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(y.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(y.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 qe(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await De([{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 De([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +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 qe(e),uo(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await De([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await De([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices: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 qe(e),console.log(y.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Dt=new fo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Dt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(y.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});Dt.command("add").description("add a cron job").action(async()=>{let e=le(),o=Object.keys(e.agents||{}),t=await De([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices: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 qe(e),console.log(y.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Dt.command("enable <id>").description("enable a cron job").action(async e=>{let o=le();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await qe(o),console.log(y.green(` Cron "${e}" enabled`))});Dt.command("disable <id>").description("disable a cron job").action(async e=>{let o=le();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await qe(o),console.log(y.green(` Cron "${e}" disabled`))});var ot=new fo().name("mesh").description("manage mesh peers \u2014 add, list, remove");ot.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=le();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=y.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(o.name)} ${y.dim(o.url)} ${t}`)}}console.log()});ot.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=le(),o=await De([{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(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.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 qe(e),console.log(y.green(` Peer "${o.name}" added`)),console.log()}});ot.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=le();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await qe(o),console.log(y.green(` Peer "${e}" removed`)))});ot.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=le();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(y.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(y.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(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await qe(o),console.log(y.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});ot.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=C().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(y.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+y.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(y.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var tt=new fo().name("skill").description("manage skills \u2014 add to agent(s), list");tt.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=le(),n=H(e);if(!he(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=he(_o(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 De({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(y.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);uo(c,{recursive:!0}),he(_o(n,"SKILL.md"))?qi(n,c,{recursive:!0}):n.endsWith(".md")&&qi(n,_o(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});tt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=he(n)?Bi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(o)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});tt.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]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>he(k));if(!i){console.log(y.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(y.dim(` ${k}`));return}let r=Do(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=C()}catch(k){console.log(y.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(y.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${i}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,h=0;for(let[k,b]of d){let $=b.workspace;if(!$||!he($)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+($||"undefined")+")")}`),h++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!he(S)){if(!o.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}o.dryRun||(uo(E,{recursive:!0}),_t(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Do(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${k.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||_t(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});tt.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-YFVSSYSL.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=le().agents?.[e.workspace];f||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=le();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).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(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?y.green("PASS "):f.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${p} ${y.bold(f.name)}${f.skill?.path?y.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${u.PASS} PASS`)} ${y.yellow(`${u.REVIEW} REVIEW`)} ${y.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});tt.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=le(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(y.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-FZX63JK5.js"),c=await r(i.workspace);if(c.length===0){console.log(y.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(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
30
+ `));return}console.log(),console.log(y.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]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?y.cyan(i.kind.padEnd(14)):y.dim(i.kind.padEnd(14))} ${y.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),r||console.log(` ${y.dim("(disabled)")}`)}console.log()});Sn.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=le();t.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-OQVGSZWB.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await De({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(y.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await De({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(y.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 u=await De({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"}]});u.scheme==="tokenEnv"?a=((await De({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await De({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await De({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...h]=f.split("=");p&&(g[p.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.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(y.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(u=>u.kind===i&&u.label===r)&&(console.log(y.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 qe(t),console.log(y.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Sn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=le(),n=t.agents?.[e];n||(console.log(y.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(y.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await qe(t),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Sn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=le().agents?.[e];n||(console.log(y.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(y.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(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});et.addCommand(Sn);var xs=new fo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");xs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=le();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(y.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${y.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(y.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(y.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(y.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(y.dim(" GitLab: disabled"));console.log()});xs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=le(),o=Object.keys(e.agents||{});if(!o.length){console.log(y.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 De({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await De([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices: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(y.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(y.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 qe(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await De([{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 De([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +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 qe(e),uo(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await De([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await De([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices: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 qe(e),console.log(y.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Dt=new fo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Dt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(y.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});Dt.command("add").description("add a cron job").action(async()=>{let e=le(),o=Object.keys(e.agents||{}),t=await De([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices: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 qe(e),console.log(y.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Dt.command("enable <id>").description("enable a cron job").action(async e=>{let o=le();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await qe(o),console.log(y.green(` Cron "${e}" enabled`))});Dt.command("disable <id>").description("disable a cron job").action(async e=>{let o=le();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await qe(o),console.log(y.green(` Cron "${e}" disabled`))});var ot=new fo().name("mesh").description("manage mesh peers \u2014 add, list, remove");ot.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=le();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=y.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(o.name)} ${y.dim(o.url)} ${t}`)}}console.log()});ot.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=le(),o=await De([{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(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.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 qe(e),console.log(y.green(` Peer "${o.name}" added`)),console.log()}});ot.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=le();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await qe(o),console.log(y.green(` Peer "${e}" removed`)))});ot.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=le();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(y.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(y.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(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await qe(o),console.log(y.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});ot.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=C().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(y.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+y.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(y.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var tt=new fo().name("skill").description("manage skills \u2014 add to agent(s), list");tt.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=le(),n=H(e);if(!he(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=he(_o(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 De({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(y.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);uo(c,{recursive:!0}),he(_o(n,"SKILL.md"))?qi(n,c,{recursive:!0}):n.endsWith(".md")&&qi(n,_o(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});tt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=he(n)?Bi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(o)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});tt.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]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>he(k));if(!i){console.log(y.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(y.dim(` ${k}`));return}let r=Do(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=C()}catch(k){console.log(y.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(y.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${i}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,h=0;for(let[k,b]of d){let $=b.workspace;if(!$||!he($)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+($||"undefined")+")")}`),h++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!he(S)){if(!o.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}o.dryRun||(uo(E,{recursive:!0}),_t(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Do(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${k.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||_t(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});tt.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-YFVSSYSL.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=le().agents?.[e.workspace];f||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=le();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).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(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?y.green("PASS "):f.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${p} ${y.bold(f.name)}${f.skill?.path?y.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${u.PASS} PASS`)} ${y.yellow(`${u.REVIEW} REVIEW`)} ${y.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});tt.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=le(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(y.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-T5FEWTZA.js"),c=await r(i.workspace);if(c.length===0){console.log(y.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(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
31
31
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(y.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(y.dim(`
32
32
  (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var En=new fo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");En.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(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=H(o.cwd),n=H(t,"references/example"),s=H(t,"references/recipes/example.yaml");he(n)||(console.log(y.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(t,".agentx/references",e),r=H(t,".agentx/references/recipes");uo(i,{recursive:!0}),uo(r,{recursive:!0});let a=Bi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=_o(i,d);if(he(u)&&!o.force){console.log(y.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Do(_o(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);_t(u,p),console.log(y.green(` + ${u}`)),c++}let g=_o(r,`${e}.yaml`);if(he(g)&&!o.force)console.log(y.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(he(s)){let d=Do(s,"utf-8").replaceAll("example.",`${e}.`);_t(g,d),console.log(y.green(` + ${g}`)),c++}console.log(),console.log(y.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(y.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(y.dim(" 2. agentx skill audit # verify references resolve")),console.log(y.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});En.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(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(o.cwd),r=o.from?String(o.from).split(",").map(h=>h.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(y.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(y.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(y.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,w])=>[h,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(o.referencesCwd||o.cwd),u=H(d,".agentx/references",e);if(!o.write){console.log(),console.log(y.dim(` Dry-run \u2014 would write to ${u}/`));for(let[h,w]of Object.entries(g))console.log(y.cyan(`
33
33
  --- ${h} ---`)),console.log(w.split(`
@@ -36,7 +36,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
36
36
  `).length>30&&console.log(y.dim(` \u2026 (${w.split(`
37
37
  `).length-30} more lines truncated in preview)`));console.log(),console.log(y.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}uo(u,{recursive:!0});let f=0,p=0;for(let[h,w]of Object.entries(g)){let k=_o(u,h);if(he(k)&&!o.force){console.log(y.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}_t(k,w),console.log(y.green(` + ${k}`)),f++}console.log(),console.log(y.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(y.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});En.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(H(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(y.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(` ${y.cyan(s.id)} ${y.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(y.dim(` ${i}`))}console.log(),console.log(y.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Ji=new fo().name("hook").description("manage hooks \u2014 add to agent workspace");Ji.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=le().agents?.[e];if(!t){console.log(y.red(` Agent "${e}" not found`));return}let n=H(t.workspace,".claude/settings.json"),s=he(n)?JSON.parse(Do(n,"utf-8")):{},i=await De([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!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),uo(H(t.workspace,".claude"),{recursive:!0}),_t(n,JSON.stringify(s,null,2)),console.log(y.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Hi=new fo().name("migrate").description("import configuration from OpenClaw or other tools");Hi.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,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&he(f)){n=f;break}if(!n){console.log(y.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(y.dim(` Reading: ${n}`));let s=JSON.parse(Do(n,"utf-8")),i=he(H(process.cwd(),"agentx.json"))?le():{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 p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(w=>w===p)||h.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){uo(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-42ARC42I.js");w(p,i.agents[p])}}console.log(` ${y.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let w=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:w},i.channels.telegram.enabled=!0,d++}console.log(` ${y.green(d)} Telegram accounts imported`);let u=H(n,"../cron/jobs.json");if(he(u)){let f=JSON.parse(Do(u,"utf-8")),p=0;for(let h of f.jobs||[]){let w=h.name||h.id,k=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:k,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${y.green(p)} cron jobs imported`)}o.dryRun?(console.log(y.yellow(`
38
38
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await qe(i),console.log(y.green(`
39
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Po=new fo().name("config").description("validate and inspect configuration");Po.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=C(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(y.dim(` Bind: ${o.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(y.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Kn(o);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=he(H(r,".claude")),c=he(H(r,"CLAUDE.md")),l=he(H(r,".claude/settings.json")),g=he(H(r,".claude/skills"))?Bi(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(y.red(` \u2717 ${o.message}`))}console.log()});Po.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=C(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(y.red(o.message))}});function Lp(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 Wi(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Po.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-P6QEABPU.js"),{expandEnvVars:r}=await import("./config-44LINWKG.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.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(Wi(g))});Po.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-P6QEABPU.js"),r=Lp(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${Wi(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${Wi(c)}`)),a.reloaded?console.log(y.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(y.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Po.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-P6QEABPU.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(y.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),i.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});Po.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=C(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(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):r?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${o?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${t}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Up}from"commander";import Mo from"chalk";import{resolve as Lo}from"path";import{existsSync as Fp}from"fs";var ko=new Up().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function nt(e){let o=Lo(e,".agentx/db.sqlite");Fp(o)||(console.log(Mo.red(` No SQLite at ${o}`)),console.log(Mo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Xn({path:o});return t||(console.log(Mo.red(` Could not open ${o}`)),console.log(Mo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function st(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Mo.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])))}ko.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=nt(Lo(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=`
39
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Po=new fo().name("config").description("validate and inspect configuration");Po.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=C(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(y.dim(` Bind: ${o.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(y.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Kn(o);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=he(H(r,".claude")),c=he(H(r,"CLAUDE.md")),l=he(H(r,".claude/settings.json")),g=he(H(r,".claude/skills"))?Bi(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(y.red(` \u2717 ${o.message}`))}console.log()});Po.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=C(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(y.red(o.message))}});function Lp(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 Wi(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Po.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-BA7YVYJY.js"),{expandEnvVars:r}=await import("./config-OQVGSZWB.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.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(Wi(g))});Po.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-BA7YVYJY.js"),r=Lp(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${Wi(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${Wi(c)}`)),a.reloaded?console.log(y.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(y.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Po.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-BA7YVYJY.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(y.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),i.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});Po.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=C(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(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):r?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${o?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${t}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Up}from"commander";import Mo from"chalk";import{resolve as Lo}from"path";import{existsSync as Fp}from"fs";var ko=new Up().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function nt(e){let o=Lo(e,".agentx/db.sqlite");Fp(o)||(console.log(Mo.red(` No SQLite at ${o}`)),console.log(Mo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Xn({path:o});return t||(console.log(Mo.red(` Could not open ${o}`)),console.log(Mo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function st(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Mo.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])))}ko.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=nt(Lo(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=`
40
40
  SELECT agent_id, channel, status, duration_ms,
41
41
  input_tokens, output_tokens,
42
42
  substr(message_preview, 1, 60) AS message,
@@ -387,7 +387,7 @@ return aid ?? null`}function Bf(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
387
387
  `)),process.exitCode=3;return}console.log(oe.green(`
388
388
  done.
389
389
  `))});function ch(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Zd(ah(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function Ps(e){let o=await jn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function lr(e){try{let{stdout:o}=await dr(_e,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function lh(e,o=[]){try{let t=await gs({max:45});if(t.candidates.length<2)return null;let n=await mo(Tn,Os({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),js(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Cs(n.answers,t.candidates);return s.present<.5?null:wn(t,s.id)}catch{return null}}function dh(e,o){if(e?.trim().toLowerCase()===Ro)return{provider:"system",elevenlabs:yn(),system:null,fallback:!0};let t=e?cs(e,hn()):null;if(t)return{provider:"system",elevenlabs:yn(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=C(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(oe.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Mc(Dc(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:yn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(oe.dim(` no agent voice (${String(n?.message??n).split(`
390
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:yn(),system:null,fallback:!0}}}var gh=new At;async function mh(e,o){o&&await gh.say({voice:o,text:e})}var Bo=e=>new Promise(o=>setTimeout(o,e));ne();import{Command as og}from"commander";import ze from"chalk";import{createInterface as tg}from"readline";var ph=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Wt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(ph()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function uh(e){e.type==="line"?console.log(`${ze.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(ze.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(ze.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(ze.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(ze.dim(" \xB7 hushed")):e.type==="error"?console.log(ze.red(` error: ${e.error}`)):e.type==="end"&&console.log(ze.dim(` \xB7 ended (${e.reason})`))}function ng(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function fh(e,o,t){let n=C(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await Wt("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Wc(()=>n,()=>d),i.usePool(await qc(_c()))}let r=e.map(d=>s[d]?ls(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,u)=>!r[u]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new Gc({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new At,listener:n.voice.listener,model:(d,u)=>Tt({system:u})});l.on(uh),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(ze.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=tg({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(ze.dim(` ${ng(l.gaps)}`))}async function hh(e,o,t){let n=await Wt("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=tg({input:process.stdin});s.on("line",a=>{a.trim()&&Wt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Wt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Wt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${ze.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(ze.dim(` ${ng(r)}`))}var sg=new og().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?fh:hh)([e,o],s,n),process.exit(0)}catch(i){console.error(ze.red(` ${i?.message??i}`)),process.exit(1)}}),ig=new og().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(ze.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await Wt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(ze.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ne();import{Command as yh}from"commander";import X from"chalk";import{existsSync as wh,readFileSync as ag,writeFileSync as cg}from"fs";import{resolve as rg}from"path";Um();var Bt=new yh().name("voice").description("list installed system voices and pick each agent's voice");function gr(e){let o=e?[e]:[rg(process.cwd(),"agentx.json"),rg(process.cwd(),".agentx/config.json")],t=o.find(n=>wh(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function $h(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=h=>{if(!a){l.system=h;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:h}},f=a?` for ${a}`:"";if(t){let h=t.trim().toLowerCase()===Ro,w=h?null:cs(t,s,a??e?.voice?.locale),k=w?`system voice ${vi(w)}`:"the OS default voice";if((w||h)&&g==="system")u(h?Ro:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!h&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||h)u(h?Ro:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}Bt.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=hn(),t;try{t=C(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Pc(t.agents,t.voice,o):new Map;if(t)for(let[a,c]of Object.entries(t.agents)){let l=i.get(a),g=Object.values(xi(a,c.voice?.system,c.voice?.gender,t.voice,o));for(let d of new Set([l,...g]))d&&s.set(d.id,[...s.get(d.id)??[],a])}if(!o.length)console.log(X.yellow(`
390
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:yn(),system:null,fallback:!0}}}var gh=new At;async function mh(e,o){o&&await gh.say({voice:o,text:e})}var Bo=e=>new Promise(o=>setTimeout(o,e));ne();import{Command as og}from"commander";import ze from"chalk";import{createInterface as tg}from"readline";var ph=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Wt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(ph()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function uh(e){e.type==="line"?console.log(`${ze.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(ze.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(ze.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(ze.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(ze.dim(" \xB7 hushed")):e.type==="error"?console.log(ze.red(` error: ${e.error}`)):e.type==="end"&&console.log(ze.dim(` \xB7 ended (${e.reason})`))}function ng(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function fh(e,o,t){let n=C(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await Wt("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Jc(()=>n,()=>d),i.usePool(await Bc(_c()))}let r=e.map(d=>s[d]?ls(d,s,!0):i?.speaker(d,!0)),a=e.filter((d,u)=>!r[u]);if(a.length)throw new Error(`Unknown agent: ${a.join(", ")}`);let c=Date.now(),l=new Gc({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new At,listener:n.voice.listener,model:(d,u)=>Tt({system:u})});l.on(uh),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(ze.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=tg({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(ze.dim(` ${ng(l.gaps)}`))}async function hh(e,o,t){let n=await Wt("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=tg({input:process.stdin});s.on("line",a=>{a.trim()&&Wt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Wt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Wt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${ze.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(ze.dim(` ${ng(r)}`))}var sg=new og().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?fh:hh)([e,o],s,n),process.exit(0)}catch(i){console.error(ze.red(` ${i?.message??i}`)),process.exit(1)}}),ig=new og().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(ze.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await Wt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(ze.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ne();import{Command as yh}from"commander";import X from"chalk";import{existsSync as wh,readFileSync as ag,writeFileSync as cg}from"fs";import{resolve as rg}from"path";Um();var Bt=new yh().name("voice").description("list installed system voices and pick each agent's voice");function gr(e){let o=e?[e]:[rg(process.cwd(),"agentx.json"),rg(process.cwd(),".agentx/config.json")],t=o.find(n=>wh(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function $h(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=h=>{if(!a){l.system=h;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:h}},f=a?` for ${a}`:"";if(t){let h=t.trim().toLowerCase()===Ro,w=h?null:cs(t,s,a??e?.voice?.locale),k=w?`system voice ${vi(w)}`:"the OS default voice";if((w||h)&&g==="system")u(h?Ro:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!h&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||h)u(h?Ro:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}Bt.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=hn(),t;try{t=C(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Pc(t.agents,t.voice,o):new Map;if(t)for(let[a,c]of Object.entries(t.agents)){let l=i.get(a),g=Object.values(xi(a,c.voice?.system,c.voice?.gender,t.voice,o));for(let d of new Set([l,...g]))d&&s.set(d.id,[...s.get(d.id)??[],a])}if(!o.length)console.log(X.yellow(`
391
391
  No system voices found (system voices need macOS).
392
392
  `));else{let a=e.all?ki(o,""):ki(o,n);console.log(X.bold(`
393
393
  System voices${e.all?"":` (${n})`}, best first
@@ -398,8 +398,8 @@ return aid ?? null`}function Bf(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
398
398
  Reinstall in ${Lc}.`)),console.log(X.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(t){console.log(X.bold(`
399
399
  Agents
400
400
  `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=h=>h?vi(h):X.dim("system default"),d=Object.entries(xi(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,h])=>(h?.id??null)!==(i.get(a)?.id??null)).map(([h,w])=>`${X.dim(`${h}:`)} ${g(w)}`).join(X.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??X.dim("(default voice)")}`:`system ${g(i.get(a))}${d?X.dim(" \xB7 ")+d:""}`,f=r.filter(h=>h.agents.includes(a)).map(h=>Si(h.voice)),p=f.length?X.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?X.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});Bt.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Ro}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=gr(t.config),{raw:s,summary:i}=$h(JSON.parse(ag(n,"utf8")),e,o,t,hn());cg(n,JSON.stringify(s,null,2)+`
401
- `),console.log(X.green(` ${e}: ${i}`)),console.log(X.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});function lg(e,o){let t=Bc(o,C(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
402
- `));let n=JSON.parse(ag(e,"utf8"));Jc(n,o),cg(e,JSON.stringify(n,null,2)+`
401
+ `),console.log(X.green(` ${e}: ${i}`)),console.log(X.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});function lg(e,o){let t=qc(o,C(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
402
+ `));let n=JSON.parse(ag(e,"utf8"));Wc(n,o),cg(e,JSON.stringify(n,null,2)+`
403
403
  `)}Bt.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${Zr.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=gr(t.config);if(e&&o){let i=o==="default"?null:o;lg(n,{agents:{[e]:{palette:i}}}),console.log(X.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(X.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=C(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(X.bold(`
404
404
  Orb palettes
405
405
  `));for(let i of Qr)console.log(` ${i.id.padEnd(10)} ${X.dim(i.colors.join(" "))}`);console.log(X.bold(`
@@ -409,7 +409,7 @@ return aid ?? null`}function Bf(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
409
409
  settings \u2014 without this an attached production identity would be less
410
410
  guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(N.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Jo.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=Tl({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(o.path)} (${o.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(N.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ne();import{Command as Eh}from"commander";import we from"chalk";var qs=new Eh().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function pg(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=C(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 ug(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function mg(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 Ah(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}qs.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}=pg(e),n;try{n=await fetch(`${o}/api/processes`,{headers:ug(t)})}catch(r){console.log(we.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.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(we.dim(" (no processes)"));return}for(let r of i){let a=Ah(r.state)(r.state.padEnd(9)),c=mg(r.spawnedAt),l=r.lastTurnAt?mg(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});qs.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}=pg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:ug(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.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(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${o}:${t}`))});import{Command as Th}from"commander";import Le from"chalk";import{existsSync as mr,rmSync as Oh}from"fs";import{resolve as pr}from"path";var Jt=new Th().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Jt.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(Le.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await xa(e,o,{verbose:n}),r=Date.now()-s;console.log(Le.green(` \u2713 indexed ${i.docs} doc(s) for ${Le.bold(e)} in ${r}ms`)),console.log(Le.dim(` \u2192 ${i.path}`))});Jt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=pr(e.cwd,".agentx","rag");if(!mr(o)){console.log(Le.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>mr(pr(o,s,"index.json")));if(n.length===0){console.log(Le.dim(" (no indexes)"));return}for(let s of n.sort()){let i=fi(s);console.log(` ${Le.bold(s)} ${i.docs} doc(s) ${Le.dim(i.path)}`)}});Jt.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=Sa(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=fi(e);i.exists?console.log(Le.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Le.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Le.bold(i.title)} ${Le.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Le.dim(i.path)}`),console.log(` ${Le.dim(i.snippet.slice(0,200))}`)});Jt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=pr(process.cwd(),".agentx","rag",e);if(!mr(o)){console.log(Le.dim(` no index for ${e} \u2014 nothing to clear`));return}Oh(o,{recursive:!0,force:!0}),console.log(Le.green(` \u2713 cleared index for ${e}`))});ne();import{Command as jh}from"commander";import Q from"chalk";import Ht from"prompts";var dt=new jh().name("backlog").description("manage the local backlog used by business workSource=backlog");function Rn(e){let o=C(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Kc(n)}}function Ch(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function Ih(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}dt.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}=Rn(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(Q.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${Ih(n.status).padEnd(7)} ${Ch(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});dt.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=Rn(t.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Xc([o],i.source,n.config),a=await Oi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Q.dim(" sync:"),...c));console.log(a.ok?Q.dim(` synced -> ${a.url??i.source.type}`):Q.yellow(` sync failed: ${a.error}`))}});dt.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=Rn(o.config);t.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await Oi(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});dt.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}=Rn(o.config);t.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});dt.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=Rn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(Q.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let w=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Ht({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Rh(o.config):_h(o.config);w.length?(i=(await Ht({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Ht({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Ht({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Ht({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Q.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Dh(o.config,i,a):await Ph(o.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(w=>w.id)),d=c.map(w=>{let k=Ti({type:s,project:l,iid:w.iid,url:w.url}),b=g.has(k),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${b?Q.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Ht({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(Q.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?Nh(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Ti(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=o.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function Nh(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Rh(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 _h(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 Dh(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 Ph(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(fg)}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(fg):[]}function fg(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 Mh}from"commander";import W from"chalk";import{existsSync as Lh,readFileSync as Uh}from"fs";import{resolve as Fh}from"path";import qh from"prompts";ne();function hg(e){let o=e||Fh(process.cwd(),"agentx.json");return Lh(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Uh(o,"utf-8"))}async function Wh(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 qh([{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 xo=new Mh().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');xo.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: ${wi})`,wi).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){xo.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=yi(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=hg(o.config),s=ta(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 Wh(o.notify,s),r=o.id||Ra(t.matched,o.agent),a=Da({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:_a(o.onError),enabled:!o.disabled}),c=a.onError,l=await pe(d=>je(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."))});xo.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=hg(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=Ma(Pa(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]])xo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Fa(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."))});xo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await pe(t=>{if(!St(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Oa(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",La,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Ua,"reject an agent's pending create/delete request (drops the request)"]])xo.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."))});xo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=yi(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 Bh}from"commander";import $e from"chalk";import So from"chalk";function yg(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var wg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function $g(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(o,t)=>{if(process.platform!=="darwin"){console.error(So.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?yg():n?hc(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(So.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={...jt().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await $c(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(So.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(So.dim(" not answered; the card is still waiting"));return}let a=await as({root:process.cwd()},`card:${s.id}`,r.action,{by:"operator (popup)",...r.action==="yes"?{choice:r.choice,text:r.text}:{}});if(!a.ok){console.error(So.red(` ${a.error}`)),process.exitCode=1;return}console.log(So.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async o=>{let t={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(t.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${wg()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(So.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(So.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(So.red(` couldn't reach the daemon at ${wg()}: ${n?.message??n}`)),process.exitCode=1}})}var Eo=new Bh("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Jh={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp"};function bg(){return{root:process.cwd()}}function ur(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Hh(e){console.log(` ${$e.cyan(e.key)} ${$e.dim(`[${Jh[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?$e.dim(` (later: until ${ur(e.snoozed_until)})`):""}`),console.log(` ${$e.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${$e.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,t)=>console.log(` ${$e.magenta(`${t+1}.`)} ${o}`)),e.expires&&console.log($e.yellow(` Expires ${ur(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log($e.dim(` ${e.detail}`)),e.source&&console.log($e.dim(` ${e.source}`)),console.log($e.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Eo.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=wc(bg(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log($e.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log($e.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Hh(t),console.log();console.log($e.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function fr(e,o,t){let n=jt(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error($e.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await as(bg(),e,o,{force:t.force,note:t.note,laterHours:s,choice:t.choice,text:t.text});if(!i.ok){console.error($e.red(` ${i.error}`)),process.exitCode=1;return}console.log($e.green(` \u2713 ${i.message}`))}Eo.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").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message: the message as you want it sent").action((e,o)=>fr(e,"yes",o));Eo.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)=>fr(e,"no",o));Eo.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)=>fr(e,"later",o));Eo.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: ${fc.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").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,o=[])=>[...o,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(e=>{let o=jt(),t=yc(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,choices:e.choice,draft:e.draft,say:e.say,context:e.context},{settings:o});if(!t.ok){console.error($e.red(` ${t.error}`)),process.exitCode=1;return}console.log($e.green(` \u2713 card:${t.card.id} raised; expires ${ur(t.card.expires)}, then: ${t.card.if_silent}`))});$g(Eo);Eo.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').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let o={},t=(l,g)=>{if(g===void 0)return;let d=Number(g);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,g)=>{if(g!==void 0){if(g==="on")return!0;if(g==="off")return!1;throw new Error(`${l} takes on or off`)}};try{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),o.popupEnabled=n("--popup",e.popup),o.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(o.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(o.popupSound=e.popupSound==="none"?"":e.popupSound),o.popupTimeoutSeconds=t("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(o.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(o.popupTheme=e.popupTheme),o.checkinEnabled=n("--checkin",e.checkin);let l=g=>g?.split(",").map(d=>d.trim()).filter(Boolean);if(o.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(o.checkinDailyAt=e.checkinDaily),o.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(o.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),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 g=cl(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=g}}catch(l){console.error($e.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(o).some(l=>l!==void 0)){let l=await ll(o);if(!l.success){console.error($e.red(` ${l.error}`)),process.exitCode=1;return}console.log($e.green(" \u2713 saved")+(l.reloaded?$e.dim(" (daemon reloaded)"):""))}let i=jt(),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"}`);let a=i.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=i.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as uy}from"commander";import Gt from"chalk";import ie from"chalk";import Dn from"prompts";import{readFileSync as Gh,writeFileSync as zh,existsSync as Vh}from"fs";import{resolve as kg}from"path";var Yh=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Kh(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function hr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function vg(e=".env"){let o=kg(e);if(!Vh(o))return[];let t=Gh(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(Yh);i?n.push({kind:"kv",key:i[1],value:Kh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Xh(e){return e.map(o=>o.kind==="kv"?`${o.key}=${hr(o.value)}`:o.raw).join(`
411
411
  `)+`
412
- `}function _n(e,o,t=".env"){let n=kg(t),s=vg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`})),zh(n,Xh(s))}function yr(e,o=".env"){return vg(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var xg="https://t.me/BotFather";async function Qh(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 Zh(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 Sg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${xg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[xg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Dn({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(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Qh(t.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.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(ie.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(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Dn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Dn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;_n(f,t.trim()),process.env[f]=t.trim();let p=await pe(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=St(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),je(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await Zh(t.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import be from"chalk";import wr from"prompts";import{existsSync as br,mkdirSync as ey,readdirSync as oy,readFileSync as Eg}from"fs";import{resolve as $r}from"path";var ty=".agentx/whatsapp-sessions";function ny(){let e=$r(process.cwd(),".agentx/daemon.pid");if(!br(e))return!1;try{let o=parseInt(Eg(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function sy(e){if(!br(e))return!1;try{return oy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function iy(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;ey(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 u=setTimeout(()=>{o(be.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(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Ag(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),ny()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await wr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||$r(process.cwd(),"agentx.json");br(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Eg(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||ty,s=$r(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await wr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(sy(s)&&a){let{keep:l}=await wr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await iy(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ry}from"crypto";import Ae from"chalk";import Tg from"prompts";var Ws="agentx-mesh:",Bs="//join/";function ay(e){return Buffer.from(e,"utf-8").toString("base64url")}function cy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ly(e){return`${Ws}${Bs}${ay(JSON.stringify(e))}`}function dy(e){if(!e.startsWith(`${Ws}${Bs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ws}${Bs}\u2026`);let o=e.slice(Ws.length+Bs.length),t=JSON.parse(cy(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 gy(){return ry(32).toString("hex")}function my(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function py(e){return e?.node?.name||e?.node?.id||"node"}async function Og(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(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=yr("MESH_TOKEN");r||(r=gy(),_n("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||my(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Tg({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ly({url:a,token:r,name:py(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jg(e,o={}){let t;try{t=dy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=yr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Tg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}_n("MESH_TOKEN",t.token);let s=await pe(i=>{je(i,"mesh.enabled",!0);let r=St(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),je(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.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(Ae.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var zt=new uy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");zt.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 Sg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});zt.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 Ag({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Cg=zt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Cg.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 Og({url:e.url,configPath:e.config})});Cg.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 jg(e,{configPath:o.config})});zt.action(()=>{console.log(),console.log(Gt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Gt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Gt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Gt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Gt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Gt.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as fy}from"commander";import fe from"chalk";var Pn=new fy().name("usage").description("token usage analysis and reporting");Pn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[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(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});Pn.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(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});Pn.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-X7ROPRQP.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};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(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.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(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as hy}from"commander";import ke from"chalk";import{readFileSync as yy}from"fs";import{resolve as wy}from"path";ne();var Ho=new hy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ho.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{ma(wy(process.cwd(),".env"))}catch{}let o=$y(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-ABEIELBC.js");t(o)}catch(o){console.log(ke.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ke.dim(o.stack)),process.exit(1)}});function $y(e,o){try{let t=C();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
412
+ `}function _n(e,o,t=".env"){let n=kg(t),s=vg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${hr(o)}`})),zh(n,Xh(s))}function yr(e,o=".env"){return vg(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var xg="https://t.me/BotFather";async function Qh(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 Zh(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 Sg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${xg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[xg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Dn({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(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Qh(t.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.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(ie.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(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Dn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Dn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;_n(f,t.trim()),process.env[f]=t.trim();let p=await pe(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=St(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),je(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await Zh(t.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import be from"chalk";import wr from"prompts";import{existsSync as br,mkdirSync as ey,readdirSync as oy,readFileSync as Eg}from"fs";import{resolve as $r}from"path";var ty=".agentx/whatsapp-sessions";function ny(){let e=$r(process.cwd(),".agentx/daemon.pid");if(!br(e))return!1;try{let o=parseInt(Eg(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function sy(e){if(!br(e))return!1;try{return oy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function iy(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;ey(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 u=setTimeout(()=>{o(be.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(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Ag(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),ny()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await wr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||$r(process.cwd(),"agentx.json");br(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Eg(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||ty,s=$r(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await wr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(sy(s)&&a){let{keep:l}=await wr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await iy(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ry}from"crypto";import Ae from"chalk";import Tg from"prompts";var Ws="agentx-mesh:",Bs="//join/";function ay(e){return Buffer.from(e,"utf-8").toString("base64url")}function cy(e){return Buffer.from(e,"base64url").toString("utf-8")}function ly(e){return`${Ws}${Bs}${ay(JSON.stringify(e))}`}function dy(e){if(!e.startsWith(`${Ws}${Bs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ws}${Bs}\u2026`);let o=e.slice(Ws.length+Bs.length),t=JSON.parse(cy(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 gy(){return ry(32).toString("hex")}function my(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function py(e){return e?.node?.name||e?.node?.id||"node"}async function Og(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(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=yr("MESH_TOKEN");r||(r=gy(),_n("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||my(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Tg({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=ly({url:a,token:r,name:py(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jg(e,o={}){let t;try{t=dy(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=yr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Tg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}_n("MESH_TOKEN",t.token);let s=await pe(i=>{je(i,"mesh.enabled",!0);let r=St(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),je(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.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(Ae.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var zt=new uy().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");zt.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 Sg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});zt.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 Ag({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Cg=zt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Cg.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 Og({url:e.url,configPath:e.config})});Cg.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 jg(e,{configPath:o.config})});zt.action(()=>{console.log(),console.log(Gt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Gt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Gt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Gt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Gt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Gt.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as fy}from"commander";import fe from"chalk";var Pn=new fy().name("usage").description("token usage analysis and reporting");Pn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[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(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});Pn.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(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});Pn.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-N3AVBQMK.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};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(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.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(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as hy}from"commander";import ke from"chalk";import{readFileSync as yy}from"fs";import{resolve as wy}from"path";ne();var Ho=new hy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ho.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{ma(wy(process.cwd(),".env"))}catch{}let o=$y(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-SI5GP3XR.js");t(o)}catch(o){console.log(ke.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ke.dim(o.stack)),process.exit(1)}});function $y(e,o){try{let t=C();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
413
413
  `)),{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}}}}Ho.command("list").description("list configured boards").action(()=>{try{let e=C();if(!e.boards?.length){console.log(ke.dim(`
414
414
  No boards configured.
415
415
  `));return}console.log();for(let o of e.boards){console.log(` ${ke.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(ke.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(ke.dim(` primary label: ${o.primaryToolLabel}`)),console.log(ke.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(ke.red(` ${e.message}`)),process.exit(1)}});Ho.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{Mn(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(ke.red(` ${t.message}`)),process.exit(1)}});Ho.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{Mn(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(ke.red(` ${t.message}`)),process.exit(1)}});var kr=Ho.command("column").description("manage a board's columns (add / remove / edit / list)");kr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(yy("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(ke.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(` ${ke.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${ke.dim(i)}`)}}catch(o){console.log(ke.red(` ${o.message}`)),process.exit(1)}});kr.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{Mn(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(ke.red(` ${n.message}`)),process.exit(1)}});kr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Mn(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(ke.red(` ${t.message}`)),process.exit(1)}});Ho.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Mn(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(ke.red(` ${o.message}`)),process.exit(1)}});function Mn(e){let{summary:o,backupPath:t}=Qe(n=>e(n));console.log(ke.green(`
@@ -420,9 +420,9 @@ return aid ?? null`}function Bf(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
420
420
  ${v.content}
421
421
  --- END ENTRY ---`).join(`
422
422
 
423
- `),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:I,renderFactsBlock:j,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-2K6UX5GD.js");if(!a){let J=new Set;for(let Oe of t.listAgents())for(let ve of t.getAgentWiki(Oe).listArticles(Oe))ve.meta.type==="person"&&J.add(ve.meta.title);a=[...J]}let G=v(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:Oe,results:ve}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=I([...me,...Oe]);$=j(M);let Ke=[...me.length>0?[`entries:${me.length}`]:[],...ve.filter(xe=>xe.records.length>0).map(xe=>`${xe.source}:${xe.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Ke.length?` (${Ke.join(" ")})`:""}`));for(let xe of P(ve,J))console.log(m.yellow(` ! ${xe.source} ${xe.kind} \u2014 would supply ${xe.provides.join(", ")}`)),console.log(m.dim(` ${xe.hint}`))}}let E=za(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${xr(o)}`));let S=U(h.baseDir,"_tmp");Ao(S,{recursive:!0});let x=U(S,"absorb-prompt.txt");mt(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=gt(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:wt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let I,j=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],me=G==="{"?"}":"]",J=0,Oe=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){Oe=M+1;break}if(Oe===-1){console.log(m.red(" Unbalanced JSON"));continue}let ve=R.slice(L,Oe);try{let M=JSON.parse(ve);Array.isArray(M)?I=M:(I=M.articles||[],j=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ve.slice(0,300)}`));continue}for(let M of I){let Ke=new Date().toISOString().slice(0,10),xe=l(M.sources||[],p);h.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ke,lastUpdated:Ke,sources:M.sources||[],graphPath:xe},M.content,u);let Ko=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Ko}${M.path}: ${M.title}${m.dim(_)}`);let ye=(M.tags||[]).slice(0,4).join(", ");ye&&console.log(m.dim(` tags: ${ye}`)),xe?.length&&(console.log(m.dim(` graphPath: ${xe.join(" \u203A ")}`)),d++),g++}if(j.length>0){console.log(),console.log(m.yellow(` Gaps detected (${j.length} missing pieces):`));for(let M of j)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ke=new M(pt(e.dir)).add(j.map(xe=>({kind:"article",agentId:u,path:"",subject:String(xe).slice(0,120),question:`No article yet for: ${String(xe).slice(0,160)}`})));Ke.added>0&&console.log(m.dim(` queued ${Ke.added} for follow-up (agentx wiki questions)`))}catch{}}h.rebuildIndex()}catch(v){console.log(m.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(m.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(m.dim("stdout: "+String(v.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 u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.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=Ey(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-ZBBIPFJT.js"),{default:c}=await import("better-sqlite3"),l=U(process.cwd(),".agentx/db.sqlite");if(!Xe(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(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} 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=U(process.cwd(),".agentx/db.sqlite");if(!Xe(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let h=p[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Va({extraCandidates:i,wikiDir:e.dir?U(e.dir):void 0,memoryRoot:e.memoryDir?U(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=ee.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Gs(e){return e?U(e):U(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(Gs(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(Gs(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(`
423
+ `),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:I,renderFactsBlock:j,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-2K6UX5GD.js");if(!a){let J=new Set;for(let Oe of t.listAgents())for(let ve of t.getAgentWiki(Oe).listArticles(Oe))ve.meta.type==="person"&&J.add(ve.meta.title);a=[...J]}let G=v(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:Oe,results:ve}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=I([...me,...Oe]);$=j(M);let Ke=[...me.length>0?[`entries:${me.length}`]:[],...ve.filter(xe=>xe.records.length>0).map(xe=>`${xe.source}:${xe.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Ke.length?` (${Ke.join(" ")})`:""}`));for(let xe of P(ve,J))console.log(m.yellow(` ! ${xe.source} ${xe.kind} \u2014 would supply ${xe.provides.join(", ")}`)),console.log(m.dim(` ${xe.hint}`))}}let E=za(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${xr(o)}`));let S=U(h.baseDir,"_tmp");Ao(S,{recursive:!0});let x=U(S,"absorb-prompt.txt");mt(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=gt(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:wt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let I,j=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],me=G==="{"?"}":"]",J=0,Oe=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){Oe=M+1;break}if(Oe===-1){console.log(m.red(" Unbalanced JSON"));continue}let ve=R.slice(L,Oe);try{let M=JSON.parse(ve);Array.isArray(M)?I=M:(I=M.articles||[],j=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ve.slice(0,300)}`));continue}for(let M of I){let Ke=new Date().toISOString().slice(0,10),xe=l(M.sources||[],p);h.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ke,lastUpdated:Ke,sources:M.sources||[],graphPath:xe},M.content,u);let Ko=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Ko}${M.path}: ${M.title}${m.dim(_)}`);let ye=(M.tags||[]).slice(0,4).join(", ");ye&&console.log(m.dim(` tags: ${ye}`)),xe?.length&&(console.log(m.dim(` graphPath: ${xe.join(" \u203A ")}`)),d++),g++}if(j.length>0){console.log(),console.log(m.yellow(` Gaps detected (${j.length} missing pieces):`));for(let M of j)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ke=new M(pt(e.dir)).add(j.map(xe=>({kind:"article",agentId:u,path:"",subject:String(xe).slice(0,120),question:`No article yet for: ${String(xe).slice(0,160)}`})));Ke.added>0&&console.log(m.dim(` queued ${Ke.added} for follow-up (agentx wiki questions)`))}catch{}}h.rebuildIndex()}catch(v){console.log(m.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(m.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(m.dim("stdout: "+String(v.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 u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.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=Ey(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-J3OBF4GM.js"),{default:c}=await import("better-sqlite3"),l=U(process.cwd(),".agentx/db.sqlite");if(!Xe(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(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} 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=U(process.cwd(),".agentx/db.sqlite");if(!Xe(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let h=p[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Va({extraCandidates:i,wikiDir:e.dir?U(e.dir):void 0,memoryRoot:e.memoryDir?U(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=ee.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Gs(e){return e?U(e):U(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(Gs(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(Gs(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(`
424
424
  `).map(s=>` ${s}`).join(`
425
- `)),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-72BY34SI.js"),n=t(Gs(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-72BY34SI.js"),n=t(Gs(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 Ey(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)}ee.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",U(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-AJO3NOO6.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Te(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 u=[],f=t(d).sort().reverse();for(let w of f){let k=r(d,w),b=[];try{b=t(k).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of b){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.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 p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
425
+ `)),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-O6Y2RG4K.js"),n=t(Gs(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-O6Y2RG4K.js"),n=t(Gs(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 Ey(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)}ee.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",U(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-J3XX5U3P.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Te(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 u=[],f=t(d).sort().reverse();for(let w of f){let k=r(d,w),b=[];try{b=t(k).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of b){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.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 p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
426
426
  `)||"_(none returned)_",E;try{let S=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")E=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map(v=>`\`${v.title}\` [${v.type||"?"}]`).join(", ");E=`**Answer:**
427
427
 
428
428
  ${S.answer}
@@ -439,7 +439,7 @@ Q: ${_.q}
439
439
  A: ${_.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(`
440
440
  `),E=U(a.baseDir,"_tmp");Ao(E,{recursive:!0});let S=U(E,`interview-${t().slice(0,8)}.txt`);mt(S,$),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ye=gt(_,{env:wt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ze=JSON.parse(ye);x=String(Ze.result||Ze.content||"")}catch{x=ye}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let v=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(x=v[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let I=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!I){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let j={};for(let _ of I[1].split(`
441
441
  `)){let ye=_.match(/^(\w+):\s*(.+)$/);ye&&(j[ye[1]]=ye[2].trim().replace(/^"(.*)"$/,"$1"))}let P=I[2],B=j.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),me=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${me}`)),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 Oe=P,ve={title:B,type:j.type||d,related:j.related?j.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:j.tags?j.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:j.access||"public",created:j.created||new Date().toISOString().slice(0,10),lastUpdated:j.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",ye=U(E,`draft-${t().slice(0,8)}.md`);mt(ye,x);try{gt(`${_} '${ye}'`,{stdio:"inherit"});let li=Ln(ye,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(li){let jo={};for(let dn of li[1].split(`
442
- `)){let di=dn.match(/^(\w+):\s*(.+)$/);di&&(jo[di[1]]=di[2].trim().replace(/^"(.*)"$/,"$1"))}Oe=li[2],ve={...ve,title:jo.title||ve.title,type:jo.type||ve.type,access:jo.access||ve.access,related:jo.related?jo.related.replace(/^\[|\]$/g,"").split(",").map(dn=>dn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ve.related,tags:jo.tags?jo.tags.replace(/^\[|\]$/g,"").split(",").map(dn=>dn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ve.tags}}}catch(Ze){console.log(m.red(` editor failed: ${Ze.message}`));return}}if(!a.writeArticle(me,ve,Oe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ke=a.extractWikilinks(Oe),xe=new Map;for(let _ of a.listArticles(e.agent))xe.set(_.meta.title.toLowerCase(),!0);let Ko=Ke.filter(_=>!xe.has(_.toLowerCase()));if(Ko.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Ko.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.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-AJO3NOO6.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Te(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 p=Ln(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);r=[];for(let h of p){let w=h.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),b=w.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=[],u=0;for(let f=0;f<l;f++){let p,h;if(r){let G=r[f];if(!G)break;p=G.q,h=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let G=w.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
442
+ `)){let di=dn.match(/^(\w+):\s*(.+)$/);di&&(jo[di[1]]=di[2].trim().replace(/^"(.*)"$/,"$1"))}Oe=li[2],ve={...ve,title:jo.title||ve.title,type:jo.type||ve.type,access:jo.access||ve.access,related:jo.related?jo.related.replace(/^\[|\]$/g,"").split(",").map(dn=>dn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ve.related,tags:jo.tags?jo.tags.replace(/^\[|\]$/g,"").split(",").map(dn=>dn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ve.tags}}}catch(Ze){console.log(m.red(` editor failed: ${Ze.message}`));return}}if(!a.writeArticle(me,ve,Oe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ke=a.extractWikilinks(Oe),xe=new Map;for(let _ of a.listArticles(e.agent))xe.set(_.meta.title.toLowerCase(),!0);let Ko=Ke.filter(_=>!xe.has(_.toLowerCase()));if(Ko.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Ko.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.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-J3XX5U3P.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Te(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 p=Ln(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);r=[];for(let h of p){let w=h.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),b=w.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=[],u=0;for(let f=0;f<l;f++){let p,h;if(r){let G=r[f];if(!G)break;p=G.q,h=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let G=w.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
443
443
  `)),console.log(m.dim(" citations: "+G))}r||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let k={q:p,answer:w.answer,citations:w.citations,verdict:h},b=h.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 $=b[1].toLowerCase(),E=(b[2]||"").trim();if(d.push(k),$==="/ok"||$==="/skip")continue;if(!E){console.log(m.yellow(` ${$} without note \u2014 skipping.`));continue}let S=w.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 v=Ty(x.content,$,E,x.meta.title,x.meta.type),R=U(i.baseDir,"_tmp");Ao(R,{recursive:!0});let I=U(R,`quiz-patch-${t().slice(0,8)}.txt`);mt(I,v);let j="";try{let G=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=gt(G,{env:wt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Oe=JSON.parse(me);j=String(Oe.result||Oe.content||"")}catch{j=me}let J=j.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(j=J[1].trim()),j=j.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!j||j.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
444
444
  `).length,B=j.split(`
445
445
  `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!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)},j,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let h=d[p];f.push(`## ${p+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}mt(e.out,f.join(`
@@ -500,14 +500,14 @@ Output (JSON array, one entry per input article, same order):
500
500
  [
501
501
  {"path": "path/to/article.md", "type": "project"},
502
502
  ...
503
- ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Te(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()});ee.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||U(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-44LINWKG.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(),ul(o,t,e.agent,n,e.mode)});ee.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-MKY332GD.js"),c=Te(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let b of k.listArticles(w)){if(u.length>=g)break e;let $=k.readArticle(b.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...o($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,t({path:b.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:b.path}],features:{agent:w,type:$.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),v=e.fields?r($.meta.type,S.answers):null;x.completeness>=d&&!(v&&!v.fit)||u.push({agent:w,type:$.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...v?{missing:v.missingCritical.join(",")||"-",cov:`${Math.round(v.coverage*100)}%`}:{},title:$.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),h=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(h(f)));for(let w of u)console.log(h(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
503
+ ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Te(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()});ee.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||U(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-OQVGSZWB.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(),ul(o,t,e.agent,n,e.mode)});ee.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-NBQOUDGU.js"),c=Te(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let b of k.listArticles(w)){if(u.length>=g)break e;let $=k.readArticle(b.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...o($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,t({path:b.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:b.path}],features:{agent:w,type:$.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),v=e.fields?r($.meta.type,S.answers):null;x.completeness>=d&&!(v&&!v.fit)||u.push({agent:w,type:$.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...v?{missing:v.missingCritical.join(",")||"-",cov:`${Math.round(v.coverage*100)}%`}:{},title:$.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),h=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(h(f)));for(let w of u)console.log(h(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
504
504
  ${u.length} article(s) flagged; ${w} 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(`
505
- ${u.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."))});ee.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-AJO3NOO6.js"),n=Te(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=U(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()}});ee.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=Te(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()});ee.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=Te(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=U(process.cwd(),".agentx/graph");if(!Xe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Co({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.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 u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),h=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of $.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),I=s.fingerprint({text:v.content,channel:v.source,sender:R}),j=r.get(I);if(!j?.length)continue;let P=j.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:j,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} 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()});ee.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=Te(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-44LINWKG.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 u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.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 u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.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()});ee.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||U(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new mi(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,h=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);h+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:xr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.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(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.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()});ee.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?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");Xe(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?U(process.cwd(),e):U(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=U(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=Xe(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Cy(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.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-MKY332GD.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Te(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let I=v.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let j=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:I.meta.type??"?"}});if(!j){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,j.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:I.meta.title,field:B.field,tier:B.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:I.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(pt(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),$=(x,v)=>String(x)+" ".repeat(Math.max(0,b[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>$(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>$(x[v],R)).join(" "));let E=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(I=>(x[I.tier??"furniture"]??9)<=v);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-44LINWKG.js"),j=I(),P=j?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
505
+ ${u.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."))});ee.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-J3XX5U3P.js"),n=Te(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=U(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()}});ee.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=Te(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()});ee.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=Te(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=U(process.cwd(),".agentx/graph");if(!Xe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Co({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.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 u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),h=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of $.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),I=s.fingerprint({text:v.content,channel:v.source,sender:R}),j=r.get(I);if(!j?.length)continue;let P=j.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:j,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} 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()});ee.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=Te(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-OQVGSZWB.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 u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.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 u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.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()});ee.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||U(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new mi(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,h=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);h+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:xr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.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(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.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()});ee.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?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");Xe(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?U(process.cwd(),e):U(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=U(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=Xe(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Cy(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.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-NBQOUDGU.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Te(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let I=v.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let j=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:I.meta.type??"?"}});if(!j){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,j.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:I.meta.title,field:B.field,tier:B.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:I.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(pt(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),$=(x,v)=>String(x)+" ".repeat(Math.max(0,b[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>$(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>$(x[v],R)).join(" "));let E=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(I=>(x[I.tier??"furniture"]??9)<=v);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-OQVGSZWB.js"),j=I(),P=j?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
506
506
  `),L=R.length>10?`
507
507
  \u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
508
508
  ${B}${L}
509
509
 
510
- agentx wiki questions`,me=j?.daemon?.port??j?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.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.`))}}}}});ee.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-MKY332GD.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-2K6UX5GD.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Te(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(j=>[j.name.toLowerCase().trim(),j])),$=0,E=0,S=[],x=!1;e:for(let j of p){let P=f.getAgentWiki(j);for(let B of P.listArticles(j)){if($>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:j,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Oe,results:ve}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ve,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ke=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,ye])=>[_,ye.value]))}]:[],...Oe]);if(Ke.length===0)continue;let{content:xe,edits:Ko}=u(L.content,Ke[0],J);if(Ko.length!==0){for(let _ of Ko)S.push({agent:j,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,xe,j)?E++: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(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(j=>Math.max(j.length,...S.map(P=>String(P[j]).length))),I=j=>j.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(I(v)));for(let j of S)console.log(I(v.map(P=>j[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} 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 ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.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-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(pt(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`))});ee.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-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(pt(t.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(pt(t.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Te(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ee.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-MKY332GD.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=Te(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:me.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),j=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:I,failures:S,elapsed:j},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),v.lostPositives>0){let L=v.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=v.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(` ${j}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 L=parseFloat(e.minRecall),{best:G,points:me}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Oe,ve)=>ve.recall-Oe.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.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=U(process.cwd(),e);Xe(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");Xe(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=U(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 Cy(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"}Bm();import{Command as Iy}from"commander";import D from"chalk";import{resolve as zs}from"path";import{existsSync as Ny}from"fs";ne();var Kt=new Iy().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Kt.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=C();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.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 Co({baseDir:zs(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let h=r[p],w=Qn(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(h.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Ry(h,a,c),b=null;try{b=await _y(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{Dy(i,h,a,c,t),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Kt.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=C();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=zs(process.cwd(),o.graph.baseDir);if(!Ny(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Co({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Kt.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=C();if(!o.graph?.enabled){console.log(D.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 Co({baseDir:zs(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let v=await fetch(`${t}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let j=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!j.ok)throw new Error(`classifications HTTP ${j.status}`);d=(await j.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let v of k){if(c.has(v.id)){$++;continue}if(e.dryRun){b++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${t}`}),c.add(v.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function Ry(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(`
510
+ agentx wiki questions`,me=j?.daemon?.port??j?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.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.`))}}}}});ee.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-NBQOUDGU.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-2K6UX5GD.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Te(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(j=>[j.name.toLowerCase().trim(),j])),$=0,E=0,S=[],x=!1;e:for(let j of p){let P=f.getAgentWiki(j);for(let B of P.listArticles(j)){if($>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:j,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Oe,results:ve}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ve,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ke=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,ye])=>[_,ye.value]))}]:[],...Oe]);if(Ke.length===0)continue;let{content:xe,edits:Ko}=u(L.content,Ke[0],J);if(Ko.length!==0){for(let _ of Ko)S.push({agent:j,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,xe,j)?E++: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(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(j=>Math.max(j.length,...S.map(P=>String(P[j]).length))),I=j=>j.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(I(v)));for(let j of S)console.log(I(v.map(P=>j[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} 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 ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.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-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(pt(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`))});ee.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-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(pt(t.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(pt(t.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Te(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ee.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-NBQOUDGU.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=Te(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:me.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),j=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:I,failures:S,elapsed:j},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),v.lostPositives>0){let L=v.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=v.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(` ${j}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 L=parseFloat(e.minRecall),{best:G,points:me}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Oe,ve)=>ve.recall-Oe.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.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=U(process.cwd(),e);Xe(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?U(process.cwd(),o.dir):U(process.cwd(),".agentx/wiki");Xe(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=U(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 Cy(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"}Bm();import{Command as Iy}from"commander";import D from"chalk";import{resolve as zs}from"path";import{existsSync as Ny}from"fs";ne();var Kt=new Iy().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Kt.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=C();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.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 Co({baseDir:zs(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let h=r[p],w=Qn(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(h.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Ry(h,a,c),b=null;try{b=await _y(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{Dy(i,h,a,c,t),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Kt.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=C();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=zs(process.cwd(),o.graph.baseDir);if(!Ny(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Co({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Kt.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=C();if(!o.graph?.enabled){console.log(D.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 Co({baseDir:zs(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let v=await fetch(`${t}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let j=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!j.ok)throw new Error(`classifications HTTP ${j.status}`);d=(await j.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let v of k){if(c.has(v.id)){$++;continue}if(e.dryRun){b++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${t}`}),c.add(v.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function Ry(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(`
511
511
  `),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(`
512
512
  `)}async function _y(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 ca((c?.content||"").toString())}finally{clearTimeout(r)}}function Dy(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Sr(){let e=C();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=zs(process.cwd(),e.graph.baseDir);return{store:new Co({baseDir:o}),baseDir:o}}var Er=Kt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Er.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=Sr();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(D.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):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(Qn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Er.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(D.red(" verdict must be correct | wrong | unsure"));return}let n=Sr();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(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.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(D.green(` ${o}: ${Qn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});Er.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Sr();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} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.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?D.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(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as qy}from"commander";import Y from"chalk";import{Command as Lg}from"commander";import de from"chalk";import{existsSync as Py}from"fs";import{resolve as My}from"path";import Ly from"better-sqlite3";function Uy(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(de.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Fy(e){let o=My(process.cwd(),e);return Py(o)||(console.log(de.red(` No db at ${o}`)),process.exit(1)),new Ly(o,{readonly:!0})}var Ug=new Lg().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(fn)).option("--max <n>","max clusters distilled per run",String(ts)).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(de.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Fy(e.path),t=await Ya(o,{since:Uy(e.since),agentId:e.agent,sessions:new fa(process.cwd()),minOccurrences:Number(e.minOccurrences)||fn,max:Number(e.max)||ts,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(de.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(` ${de.cyan(n.key)} ${de.bold(`\xD7${n.count}`)} ${de.dim(n.status)}`),n.sampleMessage&&console.log(de.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(de.dim(`
513
513
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(de.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(de.green(` \u2713 draft written: ${n.id}`)+de.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(de.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(de.yellow(` \u26A0 ${n}`));t.dryRun?console.log(de.dim(`
@@ -524,7 +524,7 @@ agentx wiki questions`,me=j?.daemon?.port??j?.port??18800;try{let J=await fetch(
524
524
  `)}`)}var Ve=new Jy().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ve.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Xo().list();if(!o.length){console.log(A.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?A.green("dispatch: active"):A.yellow(`dispatch: ${t.state}`);console.log(` ${A.cyan(t.id)} ${A.bold(t.title)} ${A.dim(`v${t.version} \xB7`)} ${r} ${A.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${A.dim("trigger:")} ${s.source??"?"}${i?` ${A.dim(i)}`:""}`),console.log(` ${A.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(A.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Ve.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new Xo().get(e);n||(console.log(A.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(ba(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(A.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Ve.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=Qt(process.cwd(),e);Ar(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=Tr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?vt(r,{filePath:e}):JSON.parse(r),l=kt.safeParse(c);if(!l.success){console.log(A.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=Zn(l.data);if(g.length){console.log(A.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(A.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof es?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let t=new Xo().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(A.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(A.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(A.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ve.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Un.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");Un.some(a=>a.name===t)||(console.log(A.red(` unknown template "${o.template}"`)),console.log(A.dim(` available: ${Un.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(A.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Xo;!o.force&&n.get(e)&&(console.log(A.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Wg(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=vt(s,{filePath:`${e}.yaml`}),c=kt.safeParse(a);if(!c.success){console.log(A.red(` template "${t}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(A.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=Qt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=vt(s,{filePath:`${e}.yaml`}),c=kt.parse(a);Vs(r,JSON.stringify(c,null,2)+`
525
525
  `)}else Vs(r,s);console.log(),console.log(A.green(` \u2713 scaffolded ${r}`)),console.log(A.dim(` template: ${t}`)),console.log(),console.log(A.dim(" Next:")),console.log(A.dim(` 1. edit ${r}`)),console.log(A.dim(` 2. agentx workflow validate ${r}`)),console.log(A.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Ve.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Un)console.log(` ${A.cyan(e.name.padEnd(20))} ${A.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${A.dim(e.description)}`);console.log(),console.log(A.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Ve.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=Qt(process.cwd(),e);Ar(t)||(console.log(A.red(` file not found: ${t}`)),process.exit(1));let n=Tr(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?vt(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof es?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=kt.safeParse(i);if(!r.success){console.log(A.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=Zn(r.data);if(a.length){console.log(A.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Xo,l=s?Hy(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Qt(c.baseDir,`${r.data.id}.${l}`);if(Vs(g,s?n:JSON.stringify(r.data,null,2)+`
526
526
  `),console.log(A.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(A.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(A.dim(" \u2713 daemon reloaded")):console.log(A.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(A.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ve.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new pn({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(A.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?A.cyan:s.status==="failed"?A.red:A.green;console.log(` ${A.dim(s.id.slice(0,8))} ${A.bold(s.workflowId)} ${a(r)} ${A.dim(s.status)}`),console.log(` ${A.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${A.dim("home: ")} ${s.homeNode}`),console.log(` ${A.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${A.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(A.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ve.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(A.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Qt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Ar(s)){let c=Tr(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?vt(c,{filePath:e}):JSON.parse(c)}catch(b){let $=b instanceof es?b.message:`parse error: ${b?.message??b}`;console.log(A.red(` ${$}`)),process.exit(1)}let d=kt.safeParse(g);if(!d.success){console.log(A.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=Zn(d.data);if(u.length){console.log(A.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Xo,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,h=l?"yaml":"json",w=Qt(f.baseDir,`${p}.${h}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
527
- `;Vs(w,k),n=p,console.log(A.dim(` ad-hoc registered as "${p}" \u2192 ${w}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(A.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(A.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(A.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?A.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(A.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Gy({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Gy(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?A.green:a==="error"?A.red:A.cyan,l=r.totalTokens!=null?A.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?A.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${A.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${A.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${A.dim("run finished:")} ${c.status}`),console.log(A.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(A.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Ve.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}Bg(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(A.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(A.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(A.yellow(` no traces for "${e}"`)),console.log(A.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(A.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Bg(i)});function Bg(e){let o=e.status||"ok",t=o==="ok"?A.green:o==="error"?A.red:A.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${A.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${A.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${A.dim("model:")} ${i}`),console.log(` ${A.dim("tokens:")} ${n} ${A.dim("duration:")} ${s}`),e.error&&console.log(` ${A.dim("error:")} ${A.red(String(e.error).slice(0,300))}`),console.log()}Ve.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new pn({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Ve.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new pn({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Ve.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new pn({nodeId:t}).setStatus(e,"canceled")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 canceled ${e}`))});import{Command as Jg}from"commander";import re from"chalk";import ut from"prompts";import{readFileSync as zy,existsSync as Vy}from"fs";import{resolve as Yy}from"path";var Fn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Or=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Hg={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function Gg(){let e=Yy(process.cwd(),"agentx.json");if(!Vy(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(zy(e,"utf-8"))}function Ky(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?re.yellow("\u26A0 no signing secret"):re.green("\u2713 active"):re.dim("disabled")}function Xy(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Or.has(e.source)?re.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${re.cyan(e.id)} ${Ky(e)}`),console.log(` ${re.dim(e.source)} \u2192 ${re.bold(e.agentId)}${n}`),console.log(` POST ${re.dim(t)}`),e.secretEnv&&console.log(` secret: ${re.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${re.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${re.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${re.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var To=new Jg().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");To.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Gg(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(re.dim(`
527
+ `;Vs(w,k),n=p,console.log(A.dim(` ad-hoc registered as "${p}" \u2192 ${w}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(A.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&g.includes('"hint"')&&console.log(A.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(A.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?A.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(A.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Gy({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Gy(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?A.green:a==="error"?A.red:A.cyan,l=r.totalTokens!=null?A.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?A.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${A.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${A.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${A.dim("run finished:")} ${c.status}`),console.log(A.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(A.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Ve.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}Bg(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(A.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(A.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(A.yellow(` no traces for "${e}"`)),console.log(A.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(A.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Bg(i)});function Bg(e){let o=e.status||"ok",t=o==="ok"?A.green:o==="error"?A.red:A.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${A.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${A.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${A.dim("model:")} ${i}`),console.log(` ${A.dim("tokens:")} ${n} ${A.dim("duration:")} ${s}`),e.error&&console.log(` ${A.dim("error:")} ${A.red(String(e.error).slice(0,300))}`),console.log()}Ve.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new pn({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Ve.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new pn({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Ve.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new pn({nodeId:t}).setStatus(e,"canceled")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 canceled ${e}`))});import{Command as Jg}from"commander";import re from"chalk";import ut from"prompts";import{readFileSync as zy,existsSync as Vy}from"fs";import{resolve as Yy}from"path";var Fn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Or=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Hg={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function Gg(){let e=Yy(process.cwd(),"agentx.json");if(!Vy(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(zy(e,"utf-8"))}function Ky(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?re.yellow("\u26A0 no signing secret"):re.green("\u2713 active"):re.dim("disabled")}function Xy(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Or.has(e.source)?re.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${re.cyan(e.id)} ${Ky(e)}`),console.log(` ${re.dim(e.source)} \u2192 ${re.bold(e.agentId)}${n}`),console.log(` POST ${re.dim(t)}`),e.secretEnv&&console.log(` secret: ${re.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${re.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${re.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${re.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var To=new Jg().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");To.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Gg(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(re.dim(`
528
528
  No webhooks registered. Add one with: agentx webhook add
529
529
  `));return}console.log();for(let n of t)Xy(n)});To.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Fn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=Gg(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),l=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),d=o.prompt!==!1;if(!r&&d&&(r=((await ut({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:p=>/^[a-z0-9][a-z0-9_-]*$/.test(p)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!r)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(r))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&d&&(a=(await ut({type:"select",name:"source",message:"Source",choices:Fn.map(p=>({title:`${p}${Or.has(p)?" \u2713 wired":""}`,value:p,description:Hg[p]}))})).source),!Fn.includes(a))throw new Error(`Source must be one of: ${Fn.join(", ")}`);if(!c&&d&&(i?c=((await ut({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await ut({type:"select",name:"agentId",message:"Agent",choices:n.map(p=>({title:p,value:p}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!l&&d&&a!=="custom"&&(l=((await ut({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await ut({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await pe(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(h=>h.id===r))throw new Error(`Webhook "${r}" already exists.`);let p={id:r,source:a,agentId:c,enabled:!0};l&&(p.secretEnv=l),g&&(p.description=g),i&&(p.node=i),f.webhooks.push(p)});if(!u.success)throw new Error(u.error);console.log(re.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(re.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(re.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});To.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await ut({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await pe(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(re.green(`\u2713 removed webhook "${e}"`))});function zg(e){return async o=>{let t=await pe(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(re.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}To.command("enable <id>").description("enable a webhook entry").action(zg(!0));To.command("disable <id>").description("disable a webhook entry").action(zg(!1));var Ys=new Jg().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Ys.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await pe(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});Ys.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await pe(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(re.green(`\u2713 removed trigger ${o} from "${e}"`))});Ys.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await pe(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});To.addCommand(Ys);To.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Fn.map(t=>({source:t,wired:Or.has(t),hint:Hg[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?re.green("\u2713 wired"):re.dim("inbound-only");console.log(` ${re.cyan(t.source.padEnd(8))} ${n} ${re.dim(t.hint)}`)}console.log(),console.log(re.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(re.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Qy}from"commander";import ae from"chalk";ne();function Zt(e){let{summary:o,backupPath:t}=Qe(n=>e(n));console.log(ae.green(`
530
530
  \u2713 ${o}`)),t&&console.log(ae.dim(` Backup: ${t}`)),console.log(ae.dim(` Restart the daemon (or POST /reload) for the change to take effect.
@@ -543,7 +543,7 @@ agentx wiki questions`,me=j?.daemon?.port??j?.port??18800;try{let J=await fetch(
543
543
 
544
544
  `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),gw(f)}}}catch(r){console.error(te.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function gw(e){let o="message",t="";for(let i of e.split(`
545
545
  `))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?te.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=te.cyan(n.phase?.padEnd(9)??"run"),r=te.bold(n.workflowId??""),a=te.dim((n.runId??"").slice(0,8)),c=n.nodeId?te.yellow(n.nodeId):"",l=n.note?te.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=te.magenta(`task.${n.phase}`.padEnd(14)),r=te.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?te.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${te.cyan(a)} ${c}`);break}case"signal":{let i=te.green("signal".padEnd(9)),r=te.bold(n.name),a=te.dim(`(${n.scope})`),c=n.workflowId?te.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=te.blue("mesh".padEnd(9)),r=te.bold(n.peer),a=n.healthy?te.green("\u2713 healthy"):te.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${te.dim(n.delta??"")}`);break}case"channel":{let i=te.yellow("channel".padEnd(9)),r=n.direction==="in"?te.cyan("\u2190"):te.magenta("\u2192"),a=te.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?te.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(te.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)}`)}}ne();import{Command as mw}from"commander";import nn from"chalk";function pw(e,o){let t=e.replace(/\/+$/,""),n=new URLSearchParams;if(o.since&&n.set("since",o.since),o.limit&&n.set("limit",o.limit),o.agent){let s=n.toString();return`${t}/agents/${encodeURIComponent(o.agent)}/events${s?`?${s}`:""}`}return o.kind&&n.set("kind",o.kind),o.limit||n.set("limit","50"),`${t}/events/recent?${n}`}var tm=new mw().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").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 a=C(e.config);o||(o=a.dashboard?.daemonUrl||""),t||(t=a.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n={};t&&(n.Authorization=`Bearer ${t}`);let s;try{let a=await fetch(pw(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(nn.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(nn.red(` daemon unreachable at ${o}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let i=s.events??[];if(e.agent&&!s.subscriptions){console.log(nn.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(nn.dim(" no events"));return}for(let a of i)console.log(` ${wa(a)} ${nn.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(nn.dim(`
546
- ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as fw}from"commander";import qn from"chalk";import{spawn as hw}from"node:child_process";import{execFileSync as uw}from"node:child_process";function nm(e=()=>uw("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 sm=new fw().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(qn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-OAAE3KM5.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:nm();if(n?.ok){let{fetchAgents:l}=await import("./client-OAAE3KM5.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(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(qn.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:h,spawnImpl:hw,log:k=>console.error(qn.dim(k))});return}n&&!n.ok&&(console.error(qn.yellow(n.reason)),console.error(qn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-UNWLWLH5.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 yw}from"commander";import K from"chalk";import{randomUUID as am}from"crypto";import{createInterface as ww}from"node:readline/promises";import $w from"ora";import ei from"chalk";function im(e){console.error(),console.error(ei.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(ei.dim(` ${e.why}`)),console.error(),console.error(` Use ${ei.cyan(e.instead)} instead.`),e.note&&console.error(ei.dim(` ${e.note}`)),console.error()}var rm={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 cm=new yw().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)=>{im({what:"agentx chat",...rm});let t=fl({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${am().slice(0,12)}`,r=[];try{r=await us(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.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-UBSOVFRK.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}kw(t.baseUrl,n,i,s);let a=ww({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
546
+ ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as fw}from"commander";import qn from"chalk";import{spawn as hw}from"node:child_process";import{execFileSync as uw}from"node:child_process";function nm(e=()=>uw("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 sm=new fw().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(qn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-TZPRACLX.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:nm();if(n?.ok){let{fetchAgents:l}=await import("./client-TZPRACLX.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(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(qn.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:h,spawnImpl:hw,log:k=>console.error(qn.dim(k))});return}n&&!n.ok&&(console.error(qn.yellow(n.reason)),console.error(qn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-NZQQXETO.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 yw}from"commander";import K from"chalk";import{randomUUID as am}from"crypto";import{createInterface as ww}from"node:readline/promises";import $w from"ora";import ei from"chalk";function im(e){console.error(),console.error(ei.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(ei.dim(` ${e.why}`)),console.error(),console.error(` Use ${ei.cyan(e.instead)} instead.`),e.note&&console.error(ei.dim(` ${e.note}`)),console.error()}var rm={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 cm=new yw().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)=>{im({what:"agentx chat",...rm});let t=fl({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${am().slice(0,12)}`,r=[];try{r=await us(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.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-CSVN3PRK.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}kw(t.baseUrl,n,i,s);let a=ww({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
547
547
  bye`)),process.exit(0)});;){let g;try{g=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${am().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await us(t);for(let h of p){let w=h.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${w} @${h.id} ${K.dim(h.tier)} ${h.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await us(t)).find(w=>w.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(h){console.error(K.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=$w({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=bw(n);try{let p=await hl(t,n,g,{channel:s,chatId:i,onText:w=>{d.stop(),f.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),f.tool(w)}});d.stop();let h=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(h,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function bw(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
548
548
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
549
549
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
@@ -636,7 +636,7 @@ Restart the daemon to activate.
636
636
  dist/
637
637
  *.log
638
638
  .env
639
- `}import{Command as d$}from"commander";import Re from"chalk";import{writeFileSync as g$,mkdirSync as m$,existsSync as ri,readFileSync as Em,appendFileSync as Am}from"fs";import{resolve as an,dirname as jm}from"path";import{homedir as Jr}from"os";var Cm=new d$().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-X7ROPRQP.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=f$(t);break;case"bash":s=b$(t);break;case"fish":s=k$(t);break;default:console.error(Re.red(`unsupported shell: ${n}`)),console.error(Re.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?an(String(e.output)):p$(n);m$(jm(i),{recursive:!0}),g$(i,s),console.log(Re.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),u$(n,i,!!e.yes)});function p$(e){let o=Jr();switch(e){case"zsh":return an(o,".zsh","completions","_agentx");case"bash":return an(o,".bash_completion.d","agentx.bash");case"fish":return an(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function u$(e,o,t){if(e==="zsh"){let n=an(Jr(),".zshrc"),s=jm(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ri(n)?Em(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Re.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ri(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Am(n,g.join(`
639
+ `}import{Command as d$}from"commander";import Re from"chalk";import{writeFileSync as g$,mkdirSync as m$,existsSync as ri,readFileSync as Em,appendFileSync as Am}from"fs";import{resolve as an,dirname as jm}from"path";import{homedir as Jr}from"os";var Cm=new d$().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-N3AVBQMK.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=f$(t);break;case"bash":s=b$(t);break;case"fish":s=k$(t);break;default:console.error(Re.red(`unsupported shell: ${n}`)),console.error(Re.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?an(String(e.output)):p$(n);m$(jm(i),{recursive:!0}),g$(i,s),console.log(Re.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),u$(n,i,!!e.yes)});function p$(e){let o=Jr();switch(e){case"zsh":return an(o,".zsh","completions","_agentx");case"bash":return an(o,".bash_completion.d","agentx.bash");case"fish":return an(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function u$(e,o,t){if(e==="zsh"){let n=an(Jr(),".zshrc"),s=jm(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ri(n)?Em(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Re.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&ri(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Am(n,g.join(`
640
640
  `)+`
641
641
  `),console.log(Re.green("\u2713 Patched ~/.zshrc")),console.log(Re.dim("Reload your shell: exec zsh"));return}console.log(Re.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Re.cyan(` ${i}`)),l&&console.log(Re.cyan(` ${r}`)),console.log(),console.log(Re.dim("Then reload: exec zsh")),console.log(Re.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=an(Jr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((ri(n)?Em(n,"utf-8"):"").includes(o)){console.log(Re.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&ri(n)){Am(n,`
642
642
  # agentx completion
@@ -652,4 +652,4 @@ ${v$({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
652
652
  ${t.url}`)}catch(o){console.error(ln.red(` ${o.message}`)),process.exitCode=1}});Vn.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",Gr).action(async(e,o)=>{try{let t=await Yr(o.models);if(!zr(o.model,t)){console.log(Vr(o.model,t)),process.exitCode=1;return}let n=e==="-"?await E$():await S$(e,"utf8"),s=JSON.parse(n),{version:i}=await os(),r=_m({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(ln.red(` ${t.message}`)),process.exitCode=1}});async function E$(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function lj(){let e=await os(),o=new A$().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=gl(n);ml(s)&&dl("cli",s)});for(let t of[Fl,Ml,zt,Ct,Rt,oo,al,et,xs,xo,Eo,Jo,vs,sm,qo,rd,fd,Cn,Ad,Cd,Rd,Pd,Md,eg,sg,ig,Bt,Pn,lm,xn,Po,Cm,Vn])o.addCommand(t);for(let t of Pm)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Pm.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,T$(t,74," "),""].join(`
653
653
  `)}),o}var Pm=[ee,Kt,Vo,go,En,Jt,Ve,To,Ho,dt,en,on,Uo,Je,Mt,qs,om,tm,ko,ot,yl,tt,Gn,Ji,zo,Dt,Hi,Zs,wo,Oo,wm,bm,cm];function T$(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(`
654
654
  `)}export{lj as a};
655
- //# sourceMappingURL=chunk-FSVUSXJB.js.map
655
+ //# sourceMappingURL=chunk-YX5S4FHR.js.map