agentix-cli 0.83.0 → 0.83.2

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 (103) hide show
  1. package/dist/{App-CREMUAHS.js → App-3CNSN65B.js} +2 -2
  2. package/dist/{ChatApp-YX3YNPNS.js → ChatApp-6RBH5UEC.js} +2 -2
  3. package/dist/{agent-3PJF4PUE.js → agent-C2DHSDPG.js} +2 -2
  4. package/dist/{board-dashboard-7B2GNISR.js → board-dashboard-DJMGIUXC.js} +21 -21
  5. package/dist/board-dashboard-DJMGIUXC.js.map +1 -0
  6. package/dist/{chunk-WMIQHJB5.js → chunk-7R6BHIPA.js} +2 -2
  7. package/dist/{chunk-JDXNHBGR.js → chunk-7UUPDBXP.js} +15 -15
  8. package/dist/chunk-7UUPDBXP.js.map +1 -0
  9. package/dist/{chunk-AACJ62ID.js → chunk-AO73YQRI.js} +2 -2
  10. package/dist/{chunk-AXQIFHOX.js → chunk-DGSLKE3Z.js} +2 -2
  11. package/dist/{chunk-ZUINXZPI.js → chunk-DJ57LID5.js} +2 -2
  12. package/dist/{chunk-MDYARXA4.js → chunk-DY4GWAG2.js} +2 -2
  13. package/dist/{chunk-KNSYKQKB.js → chunk-F2BICD4J.js} +2 -2
  14. package/dist/{chunk-K2NFNNDB.js → chunk-J2OPXEID.js} +2 -2
  15. package/dist/{chunk-DND5VBG5.js → chunk-NCY5Z7Y5.js} +225 -225
  16. package/dist/chunk-NCY5Z7Y5.js.map +1 -0
  17. package/dist/{chunk-IMFB2KTJ.js → chunk-O2CQ6HIH.js} +2 -2
  18. package/dist/{chunk-ZNLBF4ED.js → chunk-QD5HZPDN.js} +2 -2
  19. package/dist/{chunk-3AXSSYSY.js → chunk-QMXRZ7NZ.js} +2 -2
  20. package/dist/{chunk-IUQOOSD4.js → chunk-RMREPXEE.js} +2 -2
  21. package/dist/{chunk-QZ3CLHGL.js → chunk-SHYZJU73.js} +2 -2
  22. package/dist/{chunk-AK5J3DQY.js → chunk-SL4UN3MQ.js} +2 -2
  23. package/dist/{chunk-HJZFDQKD.js → chunk-SQAZ6XRV.js} +2 -2
  24. package/dist/{chunk-WYYNJTDC.js → chunk-TH7O37GJ.js} +72 -72
  25. package/dist/chunk-TH7O37GJ.js.map +1 -0
  26. package/dist/{chunk-WGZPKQNI.js → chunk-TIO5O5KS.js} +2 -2
  27. package/dist/{chunk-EBDUPZ7C.js → chunk-TXPRTOON.js} +38 -44
  28. package/dist/chunk-TXPRTOON.js.map +1 -0
  29. package/dist/{chunk-2W3UVIEG.js → chunk-VT7NIJVK.js} +23 -17
  30. package/dist/chunk-VT7NIJVK.js.map +1 -0
  31. package/dist/{chunk-XGTZMJUI.js → chunk-XWON33RF.js} +2 -2
  32. package/dist/cli.js +1 -1
  33. package/dist/{client-K5ZISLAI.js → client-CGZ3XXAA.js} +2 -2
  34. package/dist/{config-ZBNH2DMN.js → config-PTBPLRVQ.js} +2 -2
  35. package/dist/config-mutator-QVETJAFD.js +2 -0
  36. package/dist/{doctor-Y3GPTM3C.js → doctor-RGUJJURY.js} +2 -2
  37. package/dist/index.d.ts +20 -0
  38. package/dist/index.js +1 -1
  39. package/dist/{program-Y5BSOGQQ.js → program-QKNNDRP6.js} +132 -132
  40. package/dist/program-QKNNDRP6.js.map +1 -0
  41. package/dist/{promote-KLA3DBKX.js → promote-7BCIFXE7.js} +2 -2
  42. package/dist/{query-N3BRQU6S.js → query-QHUQDZ3P.js} +2 -2
  43. package/dist/{registry-GHOOAS2Z.js → registry-QJVKEZV6.js} +2 -2
  44. package/dist/{request-planner-ABXJ35NE.js → request-planner-LATURRJL.js} +2 -2
  45. package/dist/{review-candidates-UFVMO3IT.js → review-candidates-27LHBY44.js} +2 -2
  46. package/dist/{routing-GOOV7H7I.js → routing-O6PD6ULG.js} +2 -2
  47. package/dist/schedule-tool-FHWMYWVQ.js +2 -0
  48. package/dist/scheduler-BCLXHHPJ.js +2 -0
  49. package/dist/{seat-E4FYHBIC.js → seat-PUTTNNVU.js} +2 -2
  50. package/dist/{select-6QI65HKR.js → select-APGSUM4S.js} +2 -2
  51. package/dist/{set-enabled-XPIHHOPT.js → set-enabled-5LLEUDTZ.js} +2 -2
  52. package/dist/{tool-UK5MDLBQ.js → tool-7JH2ZKED.js} +2 -2
  53. package/dist/{tool-IX7B5CYT.js → tool-DQICJQ6Z.js} +2 -2
  54. package/dist/wiki-7ZTUI57I.js +2 -0
  55. package/package.json +1 -1
  56. package/dist/board-dashboard-7B2GNISR.js.map +0 -1
  57. package/dist/chunk-2W3UVIEG.js.map +0 -1
  58. package/dist/chunk-DND5VBG5.js.map +0 -1
  59. package/dist/chunk-EBDUPZ7C.js.map +0 -1
  60. package/dist/chunk-JDXNHBGR.js.map +0 -1
  61. package/dist/chunk-WYYNJTDC.js.map +0 -1
  62. package/dist/config-mutator-ENWFEDFU.js +0 -2
  63. package/dist/program-Y5BSOGQQ.js.map +0 -1
  64. package/dist/schedule-tool-KKH32REI.js +0 -2
  65. package/dist/scheduler-NBRWUJAD.js +0 -2
  66. package/dist/wiki-XSK3IIZE.js +0 -2
  67. /package/dist/{App-CREMUAHS.js.map → App-3CNSN65B.js.map} +0 -0
  68. /package/dist/{ChatApp-YX3YNPNS.js.map → ChatApp-6RBH5UEC.js.map} +0 -0
  69. /package/dist/{agent-3PJF4PUE.js.map → agent-C2DHSDPG.js.map} +0 -0
  70. /package/dist/{chunk-WMIQHJB5.js.map → chunk-7R6BHIPA.js.map} +0 -0
  71. /package/dist/{chunk-AACJ62ID.js.map → chunk-AO73YQRI.js.map} +0 -0
  72. /package/dist/{chunk-AXQIFHOX.js.map → chunk-DGSLKE3Z.js.map} +0 -0
  73. /package/dist/{chunk-ZUINXZPI.js.map → chunk-DJ57LID5.js.map} +0 -0
  74. /package/dist/{chunk-MDYARXA4.js.map → chunk-DY4GWAG2.js.map} +0 -0
  75. /package/dist/{chunk-KNSYKQKB.js.map → chunk-F2BICD4J.js.map} +0 -0
  76. /package/dist/{chunk-K2NFNNDB.js.map → chunk-J2OPXEID.js.map} +0 -0
  77. /package/dist/{chunk-IMFB2KTJ.js.map → chunk-O2CQ6HIH.js.map} +0 -0
  78. /package/dist/{chunk-ZNLBF4ED.js.map → chunk-QD5HZPDN.js.map} +0 -0
  79. /package/dist/{chunk-3AXSSYSY.js.map → chunk-QMXRZ7NZ.js.map} +0 -0
  80. /package/dist/{chunk-IUQOOSD4.js.map → chunk-RMREPXEE.js.map} +0 -0
  81. /package/dist/{chunk-QZ3CLHGL.js.map → chunk-SHYZJU73.js.map} +0 -0
  82. /package/dist/{chunk-AK5J3DQY.js.map → chunk-SL4UN3MQ.js.map} +0 -0
  83. /package/dist/{chunk-HJZFDQKD.js.map → chunk-SQAZ6XRV.js.map} +0 -0
  84. /package/dist/{chunk-WGZPKQNI.js.map → chunk-TIO5O5KS.js.map} +0 -0
  85. /package/dist/{chunk-XGTZMJUI.js.map → chunk-XWON33RF.js.map} +0 -0
  86. /package/dist/{client-K5ZISLAI.js.map → client-CGZ3XXAA.js.map} +0 -0
  87. /package/dist/{config-ZBNH2DMN.js.map → config-PTBPLRVQ.js.map} +0 -0
  88. /package/dist/{config-mutator-ENWFEDFU.js.map → config-mutator-QVETJAFD.js.map} +0 -0
  89. /package/dist/{doctor-Y3GPTM3C.js.map → doctor-RGUJJURY.js.map} +0 -0
  90. /package/dist/{promote-KLA3DBKX.js.map → promote-7BCIFXE7.js.map} +0 -0
  91. /package/dist/{query-N3BRQU6S.js.map → query-QHUQDZ3P.js.map} +0 -0
  92. /package/dist/{registry-GHOOAS2Z.js.map → registry-QJVKEZV6.js.map} +0 -0
  93. /package/dist/{request-planner-ABXJ35NE.js.map → request-planner-LATURRJL.js.map} +0 -0
  94. /package/dist/{review-candidates-UFVMO3IT.js.map → review-candidates-27LHBY44.js.map} +0 -0
  95. /package/dist/{routing-GOOV7H7I.js.map → routing-O6PD6ULG.js.map} +0 -0
  96. /package/dist/{schedule-tool-KKH32REI.js.map → schedule-tool-FHWMYWVQ.js.map} +0 -0
  97. /package/dist/{scheduler-NBRWUJAD.js.map → scheduler-BCLXHHPJ.js.map} +0 -0
  98. /package/dist/{seat-E4FYHBIC.js.map → seat-PUTTNNVU.js.map} +0 -0
  99. /package/dist/{select-6QI65HKR.js.map → select-APGSUM4S.js.map} +0 -0
  100. /package/dist/{set-enabled-XPIHHOPT.js.map → set-enabled-5LLEUDTZ.js.map} +0 -0
  101. /package/dist/{tool-UK5MDLBQ.js.map → tool-7JH2ZKED.js.map} +0 -0
  102. /package/dist/{tool-IX7B5CYT.js.map → tool-DQICJQ6Z.js.map} +0 -0
  103. /package/dist/{wiki-XSK3IIZE.js.map → wiki-7ZTUI57I.js.map} +0 -0
@@ -1,44 +1,44 @@
1
- import{a as Gl,b as As,g as zl}from"./chunk-ZNLBF4ED.js";import{a as oo,b as jl,f as _t,g as Il,h as Nl,i as Rl,j as _l,k as Dl,l as Pl,m as Ml,q as Ll,r as ql,s as Ki,t as Ul,w as Xi,x as Bl,z as Hl}from"./chunk-EBDUPZ7C.js";import{a as Fl,c as Wl,d as Jl}from"./chunk-BYD5B3P3.js";import"./chunk-O5U5NVLR.js";import{a as Ol,c as Cl}from"./chunk-AK5J3DQY.js";import{a as Di,b as nc}from"./chunk-RKPAVWXF.js";import{$ as Ss,A as ol,B as tl,C as nl,D as sl,E as il,F as ml,G as Ct,H as vs,I as Bi,J as pl,K as ul,L as fl,M as hl,N as yl,O as wl,P as It,Q as Nt,R as $l,S as bl,T as Pe,U as xs,V as En,W as Hi,X as kl,Y as Sl,Z as Yi,_ as Al,a as gc,aa as Rt,b as mc,ba as Es,ca as Vi,da as Tl,h as gs,i as hc,j as vn,k as ms,l as $c,m as bc,n as Nc,o as Rc,p as ws,q as Mi,r as qc,s as Gc,t as Vc,u as Kc,v as Xc,w as Qc,x as Zc,y as qi,z as el}from"./chunk-DND5VBG5.js";import{A as $s,B as Hc,Ha as vl,Ia as Gi,Ja as xl,Ka as zi,Q as xn,T as Ui,U as bs,V as rl,Ya as wo,_a as El,aa as Lo,ba as al,ca as Fi,ea as Wi,ga as cl,ha as ll,ia as Sn,ma as ks,pa as dl,qa as gl,ra as Ji,w as Li,x as Jc,z as Bc}from"./chunk-IMFB2KTJ.js";import"./chunk-GTJIKXDB.js";import{a as pc,d as uc,e as fc}from"./chunk-KNSYKQKB.js";import"./chunk-CL53UVOF.js";import"./chunk-ZVP6GB4G.js";import{a as ps,b as us,c as kc,d as vc,e as xc,g as Sc,h as Ec,j as Ac,k as Tc,l as jc,m as Oc,p as fs,s as Cc,t as Ic}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as zc,b as Yc}from"./chunk-EKJG63EJ.js";import{a as yc,p as wc}from"./chunk-MDYARXA4.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as eo}from"./chunk-ACFQBLPX.js";import{c as _c,e as hs,g as ys}from"./chunk-LQE73AZR.js";import{a as Dc,b as Pc,c as Mc,d as Lc}from"./chunk-2D3RYIDU.js";import"./chunk-4L244AW4.js";import{a as Uc,e as Fc,g as Wc}from"./chunk-XIYWXCNU.js";import"./chunk-PPUN7YHA.js";import{D as Mo,J as Za,U as ec,g as Ma,q as La,x as Ni,y as Wa}from"./chunk-WYYNJTDC.js";import{b as St,g as At,h as ls,i as ds,j as Tt,k as Ja,l as tt,m as bn}from"./chunk-2W3UVIEG.js";import{e as Va,f as _i,k as Ka}from"./chunk-GLQLCBJS.js";import{b as Et}from"./chunk-DP7RTNDM.js";import"./chunk-AACJ62ID.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as kn}from"./chunk-LLNPKE7H.js";import{a as oc,b as tc}from"./chunk-SHEUCITK.js";import{a as Pi,e as sc,f as ic,h as rc,i as ac,k as cc,l as lc,m as dc}from"./chunk-XGTZMJUI.js";import{c as Ha}from"./chunk-SZDACK6O.js";import{f as Ga,g as za,h as Ri}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Ua,k as Ya}from"./chunk-IUQOOSD4.js";import{a as Xa,b as ie,c as Ie,d as Ot,e as Qa}from"./chunk-WMIQHJB5.js";import"./chunk-VWTBHLMX.js";import{a as Ci}from"./chunk-ZUINXZPI.js";import"./chunk-WGZPKQNI.js";import"./chunk-KA2UIZXG.js";import{a as Ii,b as qa}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Fa}from"./chunk-X5C5W3E4.js";import{a as jt}from"./chunk-GV7S5BAX.js";import{e as Ba}from"./chunk-GSX4NK2N.js";import"./chunk-AXQIFHOX.js";import"./chunk-MYVHVJWZ.js";import{h as Pa}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-HJZFDQKD.js";import{g as Po,i as cs}from"./chunk-QZ3CLHGL.js";import"./chunk-WPNRDEHW.js";import{b as xt,d as Da}from"./chunk-2GIDVZ4H.js";import{a as Ti,b as wa,c as Sp,d as is,e as $a,f as Oa,g as Op,h as Ca,i as Cp,m as vt,n as Na,o as Ra,s as _a,v as yo,w as $n}from"./chunk-K2NFNNDB.js";import{a as Eo,b as kt,e as Aa,f as wn}from"./chunk-72SZI2UW.js";import{a as Ia,b as Ip}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as So,b as xp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as as,J as ji,K as Oi,N as Tp,Y as Sa,Z as Ea,_ as j,ba as oe,h as ba,i as ka,k as va,l as Ep,v as xa,w as Ap}from"./chunk-JDXNHBGR.js";import{a as Do,i as rs}from"./chunk-PN6XHTG5.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Ta,k as ja,l as jp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Np}from"commander";var Yl=new Np().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 mc({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()});oe();import{Command as Rp}from"commander";import{execFileSync as io}from"node:child_process";import{cpSync as Vl,existsSync as er,mkdirSync as Qi,mkdtempSync as _p,readdirSync as Dp,rmSync as Kl,writeFileSync as Xl}from"node:fs";import{dirname as Ql,join as Le}from"node:path";import{homedir as Ts,release as Pp,tmpdir as Mp}from"node:os";import{setTimeout as Lp}from"node:timers/promises";function js(){let e=kc(process.platform,process.arch,Pp());if(e)throw new Error(e)}function Os(){let e=Le(Ts(),"Library/LaunchAgents"),o=[];try{o=Dp(e).filter(Sc)}catch{}let t=o.flatMap(n=>{let s=Le(e,n);try{return[{file:s,plist:io("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ec(e,t)}function An(e){return`gui/${process.getuid()}/${e.label}`}async function Zi(e){try{io("launchctl",["bootout",An(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{io("launchctl",["print",An(e)],{stdio:"pipe"})}catch{return}await Lp(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Zl(e){if(!er(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{io("launchctl",["print",An(e)],{stdio:"pipe"})}catch{o=!1}o||io("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),io("launchctl",["kickstart",An(e)],{stdio:"pipe"})}function qp(){let e=Oc();if(e&&er(Le(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 Dt=new Rp("desktop").description("install and control the macOS desktop assistant");Dt.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=>{js();let o=j(),t=vc(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=qp(),r=Le(Ts(),"Applications"),{keep:a,remove:c}=Os();if(console.log(`Desktop assistant \u2192 ${Le(r,ps)}
1
+ import{a as Gl,b as As,g as zl}from"./chunk-QD5HZPDN.js";import{a as oo,b as Ol,f as _t,g as Nl,h as Rl,i as _l,j as Dl,k as Pl,l as Ml,p as Ll,q as ql,r as Ki,s as Ul,v as Xi,w as Bl,y as Hl}from"./chunk-TXPRTOON.js";import{a as Fl,c as Wl,d as Jl}from"./chunk-BYD5B3P3.js";import"./chunk-O5U5NVLR.js";import{a as Cl,c as Il}from"./chunk-SL4UN3MQ.js";import{a as Di,b as sc}from"./chunk-RKPAVWXF.js";import{$ as Ss,A as tl,B as nl,C as sl,D as il,E as rl,F as pl,G as Ct,H as vs,I as Bi,J as ul,K as fl,L as hl,M as yl,N as wl,O as $l,P as It,Q as Nt,R as bl,S as kl,T as Pe,U as xs,V as En,W as Hi,X as vl,Y as El,Z as Yi,_ as Tl,a as mc,aa as Rt,b as pc,ba as Es,ca as Vi,da as jl,h as gs,i as yc,j as vn,k as ms,l as bc,m as kc,n as Rc,o as _c,p as ws,q as Mi,r as Uc,s as zc,t as Kc,u as Xc,v as Qc,w as Zc,x as el,y as qi,z as ol}from"./chunk-NCY5Z7Y5.js";import{A as $s,B as Gc,Ha as xl,Ia as Gi,Ja as Sl,Ka as zi,Q as xn,T as Ui,U as bs,V as al,Ya as wo,_a as Al,aa as Lo,ba as cl,ca as Fi,ea as Wi,ga as ll,ha as dl,ia as Sn,ma as ks,pa as gl,qa as ml,ra as Ji,w as Li,x as Bc,z as Hc}from"./chunk-O2CQ6HIH.js";import"./chunk-GTJIKXDB.js";import{a as uc,d as fc,e as hc}from"./chunk-F2BICD4J.js";import"./chunk-CL53UVOF.js";import"./chunk-ZVP6GB4G.js";import{a as ps,b as us,c as vc,d as xc,e as Sc,g as Ec,h as Ac,j as Tc,k as jc,l as Oc,m as Cc,p as fs,s as Ic,t as Nc}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as Yc,b as Vc}from"./chunk-EKJG63EJ.js";import{a as wc,p as $c}from"./chunk-DY4GWAG2.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as eo}from"./chunk-ACFQBLPX.js";import{c as Dc,e as hs,g as ys}from"./chunk-LQE73AZR.js";import{a as Pc,b as Mc,c as Lc,d as qc}from"./chunk-2D3RYIDU.js";import"./chunk-4L244AW4.js";import{a as Fc,e as Wc,g as Jc}from"./chunk-XIYWXCNU.js";import"./chunk-PPUN7YHA.js";import{D as Mo,J as Za,U as oc,g as Ma,q as La,x as Ni,y as Wa}from"./chunk-TH7O37GJ.js";import{b as St,g as At,h as ls,i as ds,j as Tt,k as Ja,l as tt,m as bn,u as ec}from"./chunk-VT7NIJVK.js";import{e as Va,f as _i,k as Ka}from"./chunk-GLQLCBJS.js";import{b as Et}from"./chunk-DP7RTNDM.js";import"./chunk-AO73YQRI.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as kn}from"./chunk-LLNPKE7H.js";import{a as tc,b as nc}from"./chunk-SHEUCITK.js";import{a as Pi,e as ic,f as rc,h as ac,i as cc,k as lc,l as dc,m as gc}from"./chunk-XWON33RF.js";import{c as Ha}from"./chunk-SZDACK6O.js";import{f as Ga,g as za,h as Ri}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Ua,k as Ya}from"./chunk-RMREPXEE.js";import{a as Xa,b as ie,c as Ie,d as Ot,e as Qa}from"./chunk-7R6BHIPA.js";import"./chunk-VWTBHLMX.js";import{a as Ci}from"./chunk-DJ57LID5.js";import"./chunk-TIO5O5KS.js";import"./chunk-KA2UIZXG.js";import{a as Ii,b as qa}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Fa}from"./chunk-X5C5W3E4.js";import{a as jt}from"./chunk-GV7S5BAX.js";import{e as Ba}from"./chunk-GSX4NK2N.js";import"./chunk-DGSLKE3Z.js";import"./chunk-MYVHVJWZ.js";import{h as Pa}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-SQAZ6XRV.js";import{g as Po,i as cs}from"./chunk-SHYZJU73.js";import"./chunk-WPNRDEHW.js";import{b as xt,d as Da}from"./chunk-2GIDVZ4H.js";import{a as Ti,b as wa,c as Ap,d as is,e as $a,f as Oa,g as Ip,h as Ca,i as Np,m as vt,n as Na,o as Ra,s as _a,v as yo,w as $n}from"./chunk-J2OPXEID.js";import{a as Eo,b as kt,e as Aa,f as wn}from"./chunk-72SZI2UW.js";import{a as Ia,b as Rp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as So,b as Ep}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as as,J as ji,K as Oi,N as Op,Y as Sa,Z as Ea,_ as T,ba as oe,h as ba,i as ka,k as va,l as Tp,v as xa,w as jp}from"./chunk-7UUPDBXP.js";import{a as Do,i as rs}from"./chunk-PN6XHTG5.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Ta,k as ja,l as Cp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as _p}from"commander";var Yl=new _p().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 pc({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()});oe();import{Command as Dp}from"commander";import{execFileSync as io}from"node:child_process";import{cpSync as Vl,existsSync as er,mkdirSync as Qi,mkdtempSync as Pp,readdirSync as Mp,rmSync as Kl,writeFileSync as Xl}from"node:fs";import{dirname as Ql,join as Le}from"node:path";import{homedir as Ts,release as Lp,tmpdir as qp}from"node:os";import{setTimeout as Up}from"node:timers/promises";function js(){let e=vc(process.platform,process.arch,Lp());if(e)throw new Error(e)}function Os(){let e=Le(Ts(),"Library/LaunchAgents"),o=[];try{o=Mp(e).filter(Ec)}catch{}let t=o.flatMap(n=>{let s=Le(e,n);try{return[{file:s,plist:io("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ac(e,t)}function An(e){return`gui/${process.getuid()}/${e.label}`}async function Zi(e){try{io("launchctl",["bootout",An(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{io("launchctl",["print",An(e)],{stdio:"pipe"})}catch{return}await Up(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Zl(e){if(!er(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{io("launchctl",["print",An(e)],{stdio:"pipe"})}catch{o=!1}o||io("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),io("launchctl",["kickstart",An(e)],{stdio:"pipe"})}function Fp(){let e=Cc();if(e&&er(Le(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 Dt=new Dp("desktop").description("install and control the macOS desktop assistant");Dt.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=>{js();let o=T(),t=xc(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=Fp(),r=Le(Ts(),"Applications"),{keep:a,remove:c}=Os();if(console.log(`Desktop assistant \u2192 ${Le(r,ps)}
2
2
  Computer-use helper \u2192 ${Le(r,us)}
3
3
  Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
5
5
  Starts at login \u2192 ${a.file}${c.map(d=>`
6
- Removes duplicate login item \u2192 ${d.file}`).join("")}`),e.dryRun)return;try{io("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let l=null;try{l=io("/bin/sh",["-c","command -v ffmpeg"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{}!l&&!process.env.AGENTX_VOICE_PATH&&console.warn("ffmpeg was not found. Local Whisper transcription needs it: install ffmpeg (for example brew install ffmpeg), then rerun this install.");let g=_p(Le(Mp(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Vl(Le(i,"apps",p),Le(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let y=p==="mac-helper"?Tc(o.notifications.local.icon):[];io("/bin/bash",[Le(g,p,"build.sh"),...y],{stdio:"inherit"})}let d=Le(Ts(),"Library/Logs/agentx-desktop.err.log"),u=Ac({label:a.label,executable:Le(r,ps,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:jc(Ts()),cli:Le(i,"dist/cli.js"),node:process.execPath,log:d,path:xc(l,process.env.AGENTX_VOICE_PATH)}),f=Le(g,"desktop.plist");Xl(f,u,{mode:384}),io("plutil",["-lint",f],{stdio:"pipe"}),await Zi(a);for(let p of c)p.label!==a.label&&await Zi(p),Kl(p.file,{force:!0});Qi(r,{recursive:!0});for(let[p,y,w]of[["mac-voice","AgentX Voice.app",ps],["mac-helper",us,us]])Vl(Le(g,p,"build",y),Le(r,w),{recursive:!0});Qi(Ql(a.file),{recursive:!0}),Qi(Ql(d),{recursive:!0}),Xl(a.file,u,{mode:384}),Zl(a),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
6
+ Removes duplicate login item \u2192 ${d.file}`).join("")}`),e.dryRun)return;try{io("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let l=null;try{l=io("/bin/sh",["-c","command -v ffmpeg"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{}!l&&!process.env.AGENTX_VOICE_PATH&&console.warn("ffmpeg was not found. Local Whisper transcription needs it: install ffmpeg (for example brew install ffmpeg), then rerun this install.");let g=Pp(Le(qp(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Vl(Le(i,"apps",p),Le(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let y=p==="mac-helper"?jc(o.notifications.local.icon):[];io("/bin/bash",[Le(g,p,"build.sh"),...y],{stdio:"inherit"})}let d=Le(Ts(),"Library/Logs/agentx-desktop.err.log"),u=Tc({label:a.label,executable:Le(r,ps,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:Oc(Ts()),cli:Le(i,"dist/cli.js"),node:process.execPath,log:d,path:Sc(l,process.env.AGENTX_VOICE_PATH)}),f=Le(g,"desktop.plist");Xl(f,u,{mode:384}),io("plutil",["-lint",f],{stdio:"pipe"}),await Zi(a);for(let p of c)p.label!==a.label&&await Zi(p),Kl(p.file,{force:!0});Qi(r,{recursive:!0});for(let[p,y,w]of[["mac-voice","AgentX Voice.app",ps],["mac-helper",us,us]])Vl(Le(g,p,"build",y),Le(r,w),{recursive:!0});Qi(Ql(a.file),{recursive:!0}),Qi(Ql(d),{recursive:!0}),Xl(a.file,u,{mode:384}),Zl(a),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
7
7
  Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
8
- The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Kl(g,{recursive:!0,force:!0})}});Dt.command("start").description("start the installed desktop assistant").action(()=>{js(),Zl(Os().keep),console.log("Desktop assistant started.")});Dt.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{js(),await Zi(Os().keep),console.log("Desktop assistant stopped.")});Dt.command("status").description("show the desktop login service status").action(()=>{js();let{keep:e}=Os();try{console.log(io("launchctl",["print",An(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(er(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Hp}from"commander";import{open as Gp}from"fs/promises";import{existsSync as Ns,mkdirSync as Up,readFileSync as Rs,writeFileSync as ed}from"fs";import{homedir as Fp}from"os";import{dirname as Wp,resolve as or}from"path";var tr="/attach/",od="/guard/check";function td(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function Cs(e,o,t){let n={hooks:[{type:"command",command:td(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function Jp(e){return{SessionStart:[Cs("/attach/session-start",e,"")],UserPromptSubmit:[Cs("/attach/prompt",e)],Stop:[Cs("/attach/stop",e)],SessionEnd:[Cs("/attach/session-end",e)]}}function Bp(e){let o=td("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Is(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Tn(){return or(Fp(),".claude/settings.json")}function nt(e=process.cwd()){for(let o of[e,or(e,"..")]){let t=or(o,"agentx.json");if(Ns(t))try{let n=JSON.parse(Rs(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function nd(e,o={}){let t=o.path??Tn(),n=o.withGuard!==!1,s={};if(Ns(t))try{s=JSON.parse(Rs(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,d]of Object.entries(Jp(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!Is(f,tr)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Is(d,od)):[];r.PreToolUse=[...g,...Bp(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(Up(Wp(t),{recursive:!0}),ed(t,`${JSON.stringify(s,null,2)}
8
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Kl(g,{recursive:!0,force:!0})}});Dt.command("start").description("start the installed desktop assistant").action(()=>{js(),Zl(Os().keep),console.log("Desktop assistant started.")});Dt.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{js(),await Zi(Os().keep),console.log("Desktop assistant stopped.")});Dt.command("status").description("show the desktop login service status").action(()=>{js();let{keep:e}=Os();try{console.log(io("launchctl",["print",An(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(er(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as zp}from"commander";import{open as Yp}from"fs/promises";import{existsSync as Ns,mkdirSync as Wp,readFileSync as Rs,writeFileSync as ed}from"fs";import{homedir as Jp}from"os";import{dirname as Bp,resolve as or}from"path";var tr="/attach/",od="/guard/check";function td(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function Cs(e,o,t){let n={hooks:[{type:"command",command:td(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function Hp(e){return{SessionStart:[Cs("/attach/session-start",e,"")],UserPromptSubmit:[Cs("/attach/prompt",e)],Stop:[Cs("/attach/stop",e)],SessionEnd:[Cs("/attach/session-end",e)]}}function Gp(e){let o=td("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Is(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Tn(){return or(Jp(),".claude/settings.json")}function nt(e=process.cwd()){for(let o of[e,or(e,"..")]){let t=or(o,"agentx.json");if(Ns(t))try{let n=JSON.parse(Rs(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function nd(e,o={}){let t=o.path??Tn(),n=o.withGuard!==!1,s={};if(Ns(t))try{s=JSON.parse(Rs(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,d]of Object.entries(Hp(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!Is(f,tr)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Is(d,od)):[];r.PreToolUse=[...g,...Gp(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(Wp(Bp(t),{recursive:!0}),ed(t,`${JSON.stringify(s,null,2)}
9
9
  `)),{path:t,changed:l,events:a,guardInstalled:c}}function sd(e={}){let o=e.path??Tn();if(!Ns(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Rs(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?od:tr;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!Is(g,c));l.length!==s[a].length&&i.push(a),l.length===0?delete s[a]:s[a]=l}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&ed(o,`${JSON.stringify(t,null,2)}
10
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function jn(e=Tn()){if(!Ns(e))return!1;try{return!!JSON.parse(Rs(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Is(t,tr))}catch{return!1}}var _s=new Hp("monitor").description("Register external CLI sessions and report ended runs to the briefing"),id=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${nt()}`;async function rd(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}_s.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",id).action(async e=>{try{await rd(e.url,"register",uc.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});_s.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",id).action(async e=>{try{let o=await Gp(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
11
- `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await rd(e.url,"ended",fc.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as bb}from"commander";import{Command as ou}from"commander";oe();import T from"chalk";import{existsSync as tu,readFileSync as nu}from"fs";oe();import{Command as zp}from"commander";import re from"chalk";import{spawn as cd}from"child_process";import{existsSync as Yp,readFileSync as Vp,unlinkSync as Kp}from"fs";import{resolve as nr}from"path";var sr=e=>new Promise(o=>setTimeout(o,e));function ir(e){try{return process.kill(e,0),!0}catch{return!1}}async function Pt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function Xp(e){let o=await Pt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await Pt(`${e}/health`);return t?typeof t.inflight?.total=="number"?t.inflight.total:Array.isArray(t.agents)?t.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Qp(e){for(let o of[nr(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(Vp(o,"utf-8").trim(),10);if(Number.isFinite(t)&&ir(t))return t}catch{}return null}function Zp(e){return new Promise(o=>{let t=cd(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var ld=new zp("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let o=j(e.config),[t,n]=o.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s}`,r=await Pt(`${i}/health`);r||(console.log(re.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(re.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await Pt(`${i}/daemon/restart`),c=a?.pid??el(s)??Qp(process.cwd()),l=a?.service??(c?Qc(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=Kc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?Zc(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${re.bold(r.node?.name||r.node?.id||i)}${c?re.dim(` (PID ${c})`):""}`),console.log(` Run by: ${Xc(l)}`),f.ok||(console.log(re.red(` ${f.reason}`)),console.log(re.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(re.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(re.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(re.dim(" Would run:"));for(let $ of f.steps)console.log(re.dim(` ${ad($,c)}`));console.log();return}if(e.whenIdle){let $=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite($)||$<0)&&(console.log(re.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await Vc({read:()=>Xp(i),intervalMs:E*1e3,timeoutMs:$*6e4,onCheck:v=>{v!==S&&v!==null&&v>0&&console.log(re.dim(` Waiting: ${v} task(s) running...`)),S=v}});if(x.outcome==="unreachable"&&(console.log(re.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(re.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let v=x.inflight??"some";e.abortOnTimeout&&(console.log(re.yellow(` Still ${v} task(s) running after ${$} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(re.yellow(` Still ${v} task(s) running after ${$} min. Restarting anyway:`)),console.log(re.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(re.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=nr(g,".agentx");try{Yc(p,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let y=Date.now(),w=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(re.dim(" Restarting..."));for(let $ of f.steps){if(await eu($,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||$.kind==="exec"&&$.mayFail)continue;let S=$===f.steps[0];try{S&&Kp(nr(p,zc))}catch{}console.log(re.red(` Step failed: ${ad($,c)}`)),console.log(S?re.dim(` The daemon is still running. Restart it with: ${f.manual}`):re.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,b=Date.now();for(;Date.now()-b<k;){let $=await Pt(`${i}/health`);if($&&typeof $.uptime=="number"&&$.uptime*1e3<=Date.now()-y+2e3){let E=await Pt(`${i}/daemon/restart`);console.log(re.green(` Daemon is back${E?.pid?` (PID ${E.pid})`:""} after ${Math.round((Date.now()-y)/1e3)}s.`)),console.log();return}await sr(1e3)}console.log(re.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(re.dim(` Start it with: ${f.manual}`)),console.log(re.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function ad(e,o){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${o??"<pid>"} (the daemon finishes running tasks, then exits)`;case"wait-exit":return"wait for the old daemon to exit";case"wait-unloaded":return"wait until launchd has unloaded the job";case"start-detached":return"agentx daemon start --detach"}}async function eu(e,o){switch(e.kind){case"exec":return await Zp(e.argv)===0;case"sigterm":if(!o.pid)return!1;try{return process.kill(o.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!o.pid)return!0;let t=Date.now(),n=!1;for(;ir(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(re.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await sr(500);return ir(o.pid)?(console.log(re.yellow(` The old daemon (PID ${o.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(o.service.kind!=="launchd")return!0;let t=Date.now();for(;qi(o.service)&&Date.now()-t<3e4;)await sr(500);return!qi(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!Yp(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=cd(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function su(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var ro=new ou().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");ro.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(f))&&(console.error(T.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(T.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let p=[f,"daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.push("--port",e.port);let y="/tmp/agentx-daemon.log",w;try{w=g(y,"a")}catch(b){console.error(T.red(` Failed to open ${y} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${y}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${y} for the error:`)),console.log(T.dim(` tail -n 40 ${y}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await su(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{iu(i(process.cwd(),".env"))}catch{}await new Vi(e.config).start()});function iu(e){if(!tu(e))return;let o=nu(e,"utf-8");for(let t of o.split(`
12
- `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}ro.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-SNI2B4LI.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;dd(a)&&Date.now()-l<c;)!g&&Date.now()-l>3e3&&(console.log(T.dim(` Waiting for in-flight tasks to finish (up to ${Math.round(c/6e4)} min)...`)),g=!0),await new Promise(d=>setTimeout(d,500));if(dd(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(T.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(T.green("Daemon stopped"))}catch{console.log(T.yellow("No daemon process found"))}});ro.addCommand(ld);ro.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=j(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(T.bold(` ${r.node.name}`)+T.dim(` (${r.node.id})`)),console.log(T.green(" Status: running")+T.dim(` \u2014 uptime ${ru(r.uptime)}`)),console.log(),console.log(T.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?T.yellow(` [${c.active} active]`):"",g=c.errors>0?T.red(` (${c.errors} errors)`):"";console.log(` ${T.cyan(c.name)} ${T.dim(`(${c.tier})`)}${l}${g}`),console.log(T.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(T.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?T.green("\u25CF"):T.dim("\u25CB"),g=c.nextRun?T.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(T.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?T.green("\u25CF"):T.red("\u25CF"),g=c.skills?.length?T.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${T.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let t=j(e.config),n=as(t);if(console.log(),console.log(T.bold(` ${t.node.name}`)+T.dim(` (${t.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(T.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(T.red(` ${t.message}`))}}});ro.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(T.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});ro.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(j(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(T.dim(` Connecting to ${n}...`)),console.log(T.dim(` Press Ctrl+C to stop
13
- `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(T.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let g=a.split(`
14
- `);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let u=JSON.parse(d.slice(6)),f=new Date(u.time).toLocaleTimeString(),p=u.message?.replace(/^\[agentx\]\s*/,"")||"";p.includes("executing")?console.log(`${T.dim(f)} ${T.cyan("\u25B6")} ${p}`):p.includes("completed")?console.log(`${T.dim(f)} ${T.green("\u2713")} ${p}`):p.includes("error")||p.includes("Error")?console.log(`${T.dim(f)} ${T.red("\u2717")} ${p}`):p.includes("Routing")?console.log(`${T.dim(f)} ${T.yellow("\u2192")} ${p}`):p.includes("mention")?console.log(`${T.dim(f)} ${T.magenta("@")} ${p}`):p.includes("Skipping")?console.log(`${T.dim(f)} ${T.dim("\u2298")} ${T.dim(p)}`):console.log(`${T.dim(f)} ${p}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(T.red(` Connection failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Diagnostic order:")),console.log(T.dim(" 1) agentx daemon status # is the daemon up?")),console.log(T.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(T.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(T.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(T.dim(" to see the error in the foreground."))}});ro.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=j(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(T.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(T.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(T.dim(`
15
- (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(T.red(` Failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Try: agentx daemon status"))}});ro.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(T.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Tests passed"))}catch{console.log(T.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(T.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(T.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(T.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),o.restart){console.log(T.dim(" Restarting remote daemon once no task is running..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} -t ${o.user}@${e} "cd ${o.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(T.green(" Remote daemon restarted"))}}catch(i){console.log(T.red(` Deploy failed: ${i.message}`))}});ro.action(async e=>{await new Vi(e.config).start()});function ru(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}function dd(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as au}from"commander";import ao from"chalk";import{existsSync as On,readFileSync as cu,writeFileSync as gd,mkdirSync as md}from"fs";import{hostname as pd}from"os";import{resolve as Mt}from"path";var ud=new au().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Mt(o,"agentx.json"),n=Mt(o,".env"),s=Mt(o,".agentx/sessions");if(console.log(),console.log(ao.bold(" agentx init")),console.log(),On(t)&&!e.force){console.log(ao.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Mt(o,"agentx.example.json"),Mt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(On(c)){r=cu(c,"utf-8");break}r||(r=JSON.stringify({node:{id:pd().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:pd(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),gd(t,r),console.log(ao.green(" \u2713 Created agentx.json")),On(n)||(gd(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
- `)),console.log(ao.green(" \u2713 Created .env template"))),On(s)||(md(s,{recursive:!0}),console.log(ao.green(" \u2713 Created .agentx/sessions/")));let a=Mt(o,".claude");On(a)||(md(a,{recursive:!0}),console.log(ao.green(" \u2713 Created .claude/"))),console.log(),console.log(ao.bold(" Next steps:")),console.log(` 1. Edit ${ao.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${ao.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${ao.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${ao.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as mu}from"commander";import Cn from"chalk";import{spawn as pu}from"child_process";import{existsSync as uu}from"fs";import{dirname as fu,resolve as hu}from"path";import{fileURLToPath as yu}from"url";oe();import{spawn as lu}from"child_process";import du from"chalk";function gu(e=process.platform){return e==="darwin"?"open":e==="win32"?"start":"xdg-open"}function st(e,o=gu()){let t=()=>console.log(du.dim(` Couldn't open a browser. Visit ${e}`));try{let n=lu(o,[e],{stdio:"ignore",detached:!0});n.once("error",t),n.unref()}catch{t()}}var fd=new mu().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=jl(),t=e.port?parseInt(e.port,10):wu(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Cn.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Cn.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Cn.bold(` Opening ${n}`)),console.log(),await bu(n).catch(()=>!1))console.log(Cn.dim(" Dashboard is already running.")),e.open!==!1&&st(n);else{console.log(Cn.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=$u(),r=pu(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&st(n),await new Promise(a=>r.on("exit",()=>a()))}});function wu(){try{return j().dashboard.port||4202}catch{return 4202}}function $u(){let e=hu(fu(yu(import.meta.url)),"cli.js");return uu(e)?e:process.argv[1]||e}async function bu(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}import{Command as ku}from"commander";import Ne from"chalk";var In=new ku().name("token").description("scoped API tokens for external access (mesh peers, integrations)");In.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new eo,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Ne.bold(" Token created.")),console.log(),console.log(` id: ${Ne.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ne.dim("never")}`),console.log(),console.log(Ne.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ne.green.bold(s)}`),console.log(),console.log(Ne.dim(" Use it via the Authorization header:")),console.log(Ne.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ne.red(` ${o.message}`)),process.exit(1)}});In.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new eo().list();if(e.length===0){console.log(Ne.dim(`
10
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function jn(e=Tn()){if(!Ns(e))return!1;try{return!!JSON.parse(Rs(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Is(t,tr))}catch{return!1}}var _s=new zp("monitor").description("Register external CLI sessions and report ended runs to the briefing"),id=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${nt()}`;async function rd(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}_s.command("register").requiredOption("--session <id>","Native session ID").requiredOption("--runtime <name>","claude, codex, gemini, opencode, or another CLI").requiredOption("--label <label>","Human-readable task label").option("--url <url>","Daemon URL",id).action(async e=>{try{await rd(e.url,"register",fc.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});_s.command("ended").requiredOption("--session <id>","Registered session ID").requiredOption("--run <id>","Stable unique turn ID; reuse this ID when retrying delivery").requiredOption("--transcript <file>","Local transcript file; only the last 90 KB is submitted").option("--url <url>","Daemon URL",id).action(async e=>{try{let o=await Yp(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
11
+ `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await rd(e.url,"ended",hc.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as vb}from"commander";import{Command as nu}from"commander";oe();import j from"chalk";import{existsSync as su,readFileSync as iu}from"fs";oe();import{Command as Vp}from"commander";import re from"chalk";import{spawn as cd}from"child_process";import{existsSync as Kp,readFileSync as Xp,unlinkSync as Qp}from"fs";import{resolve as nr}from"path";var sr=e=>new Promise(o=>setTimeout(o,e));function ir(e){try{return process.kill(e,0),!0}catch{return!1}}async function Pt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function Zp(e){let o=await Pt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await Pt(`${e}/health`);return t?typeof t.inflight?.total=="number"?t.inflight.total:Array.isArray(t.agents)?t.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function eu(e){for(let o of[nr(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(Xp(o,"utf-8").trim(),10);if(Number.isFinite(t)&&ir(t))return t}catch{}return null}function ou(e){return new Promise(o=>{let t=cd(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var ld=new Vp("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let o=T(e.config),[t,n]=o.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s}`,r=await Pt(`${i}/health`);r||(console.log(re.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(re.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await Pt(`${i}/daemon/restart`),c=a?.pid??ol(s)??eu(process.cwd()),l=a?.service??(c?Zc(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=Xc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?el(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${re.bold(r.node?.name||r.node?.id||i)}${c?re.dim(` (PID ${c})`):""}`),console.log(` Run by: ${Qc(l)}`),f.ok||(console.log(re.red(` ${f.reason}`)),console.log(re.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(re.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(re.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(re.dim(" Would run:"));for(let $ of f.steps)console.log(re.dim(` ${ad($,c)}`));console.log();return}if(e.whenIdle){let $=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite($)||$<0)&&(console.log(re.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await Kc({read:()=>Zp(i),intervalMs:E*1e3,timeoutMs:$*6e4,onCheck:v=>{v!==S&&v!==null&&v>0&&console.log(re.dim(` Waiting: ${v} task(s) running...`)),S=v}});if(x.outcome==="unreachable"&&(console.log(re.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(re.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let v=x.inflight??"some";e.abortOnTimeout&&(console.log(re.yellow(` Still ${v} task(s) running after ${$} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(re.yellow(` Still ${v} task(s) running after ${$} min. Restarting anyway:`)),console.log(re.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(re.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=nr(g,".agentx");try{Vc(p,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let y=Date.now(),w=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(re.dim(" Restarting..."));for(let $ of f.steps){if(await tu($,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||$.kind==="exec"&&$.mayFail)continue;let S=$===f.steps[0];try{S&&Qp(nr(p,Yc))}catch{}console.log(re.red(` Step failed: ${ad($,c)}`)),console.log(S?re.dim(` The daemon is still running. Restart it with: ${f.manual}`):re.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,b=Date.now();for(;Date.now()-b<k;){let $=await Pt(`${i}/health`);if($&&typeof $.uptime=="number"&&$.uptime*1e3<=Date.now()-y+2e3){let E=await Pt(`${i}/daemon/restart`);console.log(re.green(` Daemon is back${E?.pid?` (PID ${E.pid})`:""} after ${Math.round((Date.now()-y)/1e3)}s.`)),console.log();return}await sr(1e3)}console.log(re.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(re.dim(` Start it with: ${f.manual}`)),console.log(re.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function ad(e,o){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${o??"<pid>"} (the daemon finishes running tasks, then exits)`;case"wait-exit":return"wait for the old daemon to exit";case"wait-unloaded":return"wait until launchd has unloaded the job";case"start-detached":return"agentx daemon start --detach"}}async function tu(e,o){switch(e.kind){case"exec":return await ou(e.argv)===0;case"sigterm":if(!o.pid)return!1;try{return process.kill(o.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!o.pid)return!0;let t=Date.now(),n=!1;for(;ir(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(re.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await sr(500);return ir(o.pid)?(console.log(re.yellow(` The old daemon (PID ${o.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(o.service.kind!=="launchd")return!0;let t=Date.now();for(;qi(o.service)&&Date.now()-t<3e4;)await sr(500);return!qi(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!Kp(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=cd(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function ru(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var ro=new nu().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");ro.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(f))&&(console.error(j.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(j.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let p=[f,"daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.push("--port",e.port);let y="/tmp/agentx-daemon.log",w;try{w=g(y,"a")}catch(b){console.error(j.red(` Failed to open ${y} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(j.green(`Daemon started in background (PID: ${k.pid})`)),console.log(j.dim(` Logs: tail -f ${y}`)),console.log(j.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(j.yellow(` Daemon exited within 1s \u2014 check ${y} for the error:`)),console.log(j.dim(` tail -n 40 ${y}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await ru(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{au(i(process.cwd(),".env"))}catch{}await new Vi(e.config).start()});function au(e){if(!su(e))return;let o=iu(e,"utf-8");for(let t of o.split(`
12
+ `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}ro.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-SNI2B4LI.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;dd(a)&&Date.now()-l<c;)!g&&Date.now()-l>3e3&&(console.log(j.dim(` Waiting for in-flight tasks to finish (up to ${Math.round(c/6e4)} min)...`)),g=!0),await new Promise(d=>setTimeout(d,500));if(dd(a)){console.log(j.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(j.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(j.green("Daemon stopped"))}catch{console.log(j.yellow("No daemon process found"))}});ro.addCommand(ld);ro.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=T(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(j.bold(` ${r.node.name}`)+j.dim(` (${r.node.id})`)),console.log(j.green(" Status: running")+j.dim(` \u2014 uptime ${cu(r.uptime)}`)),console.log(),console.log(j.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?j.yellow(` [${c.active} active]`):"",g=c.errors>0?j.red(` (${c.errors} errors)`):"";console.log(` ${j.cyan(c.name)} ${j.dim(`(${c.tier})`)}${l}${g}`),console.log(j.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(j.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?j.green("\u25CF"):j.dim("\u25CB"),g=c.nextRun?j.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(j.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?j.green("\u25CF"):j.red("\u25CF"),g=c.skills?.length?j.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${j.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(j.red(" Daemon is not running")),console.log(j.dim(" Start with: agentx daemon start"));else try{let t=T(e.config),n=as(t);if(console.log(),console.log(j.bold(` ${t.node.name}`)+j.dim(` (${t.node.id})`)),console.log(j.yellow(" Status: stopped")),console.log(j.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(j.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(j.red(` ${t.message}`))}}});ro.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(j.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});ro.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(T(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(j.dim(` Connecting to ${n}...`)),console.log(j.dim(` Press Ctrl+C to stop
13
+ `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(j.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let g=a.split(`
14
+ `);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let u=JSON.parse(d.slice(6)),f=new Date(u.time).toLocaleTimeString(),p=u.message?.replace(/^\[agentx\]\s*/,"")||"";p.includes("executing")?console.log(`${j.dim(f)} ${j.cyan("\u25B6")} ${p}`):p.includes("completed")?console.log(`${j.dim(f)} ${j.green("\u2713")} ${p}`):p.includes("error")||p.includes("Error")?console.log(`${j.dim(f)} ${j.red("\u2717")} ${p}`):p.includes("Routing")?console.log(`${j.dim(f)} ${j.yellow("\u2192")} ${p}`):p.includes("mention")?console.log(`${j.dim(f)} ${j.magenta("@")} ${p}`):p.includes("Skipping")?console.log(`${j.dim(f)} ${j.dim("\u2298")} ${j.dim(p)}`):console.log(`${j.dim(f)} ${p}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(j.red(` Connection failed: ${s.message}`)),console.log(j.dim(" Is the daemon running? Diagnostic order:")),console.log(j.dim(" 1) agentx daemon status # is the daemon up?")),console.log(j.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(j.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(j.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(j.dim(" to see the error in the foreground."))}});ro.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=T(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(j.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(j.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(j.dim(`
15
+ (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(j.red(` Failed: ${s.message}`)),console.log(j.dim(" Is the daemon running? Try: agentx daemon status"))}});ro.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(j.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(j.green(" \u2713 Tests passed"))}catch{console.log(j.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(j.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(j.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(j.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(j.green(" \u2713 Build complete")))}console.log(j.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(j.green(" \u2713 Deploy complete")),o.restart){console.log(j.dim(" Restarting remote daemon once no task is running..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} -t ${o.user}@${e} "cd ${o.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(j.green(" Remote daemon restarted"))}}catch(i){console.log(j.red(` Deploy failed: ${i.message}`))}});ro.action(async e=>{await new Vi(e.config).start()});function cu(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}function dd(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as lu}from"commander";import ao from"chalk";import{existsSync as On,readFileSync as du,writeFileSync as gd,mkdirSync as md}from"fs";import{hostname as pd}from"os";import{resolve as Mt}from"path";var ud=new lu().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Mt(o,"agentx.json"),n=Mt(o,".env"),s=Mt(o,".agentx/sessions");if(console.log(),console.log(ao.bold(" agentx init")),console.log(),On(t)&&!e.force){console.log(ao.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Mt(o,"agentx.example.json"),Mt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(On(c)){r=du(c,"utf-8");break}r||(r=JSON.stringify({node:{id:pd().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:pd(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),gd(t,r),console.log(ao.green(" \u2713 Created agentx.json")),On(n)||(gd(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
+ `)),console.log(ao.green(" \u2713 Created .env template"))),On(s)||(md(s,{recursive:!0}),console.log(ao.green(" \u2713 Created .agentx/sessions/")));let a=Mt(o,".claude");On(a)||(md(a,{recursive:!0}),console.log(ao.green(" \u2713 Created .claude/"))),console.log(),console.log(ao.bold(" Next steps:")),console.log(` 1. Edit ${ao.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${ao.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${ao.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${ao.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as uu}from"commander";import Cn from"chalk";import{spawn as fu}from"child_process";import{existsSync as hu}from"fs";import{dirname as yu,resolve as wu}from"path";import{fileURLToPath as $u}from"url";oe();import{spawn as gu}from"child_process";import mu from"chalk";function pu(e=process.platform){return e==="darwin"?"open":e==="win32"?"start":"xdg-open"}function st(e,o=pu()){let t=()=>console.log(mu.dim(` Couldn't open a browser. Visit ${e}`));try{let n=gu(o,[e],{stdio:"ignore",detached:!0});n.once("error",t),n.unref()}catch{t()}}var fd=new uu().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=Ol(),t=e.port?parseInt(e.port,10):bu(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Cn.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Cn.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Cn.bold(` Opening ${n}`)),console.log(),await vu(n).catch(()=>!1))console.log(Cn.dim(" Dashboard is already running.")),e.open!==!1&&st(n);else{console.log(Cn.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=ku(),r=fu(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&st(n),await new Promise(a=>r.on("exit",()=>a()))}});function bu(){try{return T().dashboard.port||4202}catch{return 4202}}function ku(){let e=wu(yu($u(import.meta.url)),"cli.js");return hu(e)?e:process.argv[1]||e}async function vu(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}import{Command as xu}from"commander";import Ne from"chalk";var In=new xu().name("token").description("scoped API tokens for external access (mesh peers, integrations)");In.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new eo,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Ne.bold(" Token created.")),console.log(),console.log(` id: ${Ne.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ne.dim("never")}`),console.log(),console.log(Ne.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ne.green.bold(s)}`),console.log(),console.log(Ne.dim(" Use it via the Authorization header:")),console.log(Ne.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ne.red(` ${o.message}`)),process.exit(1)}});In.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new eo().list();if(e.length===0){console.log(Ne.dim(`
17
17
  No tokens issued.
18
18
  `));return}console.log();for(let o of e){let t=o.revokedAt?Ne.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Ne.red("expired"):Ne.green("active");console.log(` ${Ne.cyan(o.id)} ${t} ${o.name}`),console.log(Ne.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Ne.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ne.red(` ${e.message}`)),process.exit(1)}});In.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new eo().revoke(e);o||(console.log(Ne.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ne.green(`
19
19
  \u2713 Revoked ${e} (${o.name})
20
- `))}catch(o){console.log(Ne.red(` ${o.message}`)),process.exit(1)}});import{Command as vu}from"commander";import Te from"chalk";import{execFileSync as yd}from"child_process";import{existsSync as hd}from"fs";oe();var Lt=new vu().name("app").description("pair phones with the AgentX phone app and manage paired devices");Lt.command("pair").description("pair a phone \u2014 prints a QR code to scan and a one-time code to type in the installed app").option("--name <name>","name for this phone (shown in `agentx app devices`)","Phone").option("--url <origin>","address the phone opens, e.g. https://my-mac.tailnet-name.ts.net (default: this machine's Tailscale name)").action(async e=>{try{let o=ar(cr(),Nn());if(o.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${o.join(", ")}`," Anyone on your tailnet can open it without a key. Serve only the app paths instead:"," tailscale serve reset (removes every served path; add the /member lines back if you use them)",` tailscale serve --bg --set-path /app http://127.0.0.1:${Nn()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${Nn()}/api/app`].join(`
21
- `));let t=(e.url?String(e.url):rr()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(t))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${t}`);let{token:n,record:s}=new eo().create({name:String(e.name),scopes:["app"]}),{code:i}=new ys().create({token:n,tokenId:s.id,name:s.name}),r=`${t}/app/pair#token=${n}`,{default:a}=await import("qrcode-terminal");console.log(),a.generate(r,{small:!0},c=>console.log(c));for(let c of xu({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!hd("agentx.json")&&!hd(".agentx/config.json")&&console.log(Te.yellow(" \u26A0 No agentx.json here. The dashboard only accepts phones paired from the folder that holds agentx.json.")),console.log()}catch(o){console.log(Te.red(` ${o.message}`)),process.exit(1)}});Lt.command("devices").description("list paired phones").action(()=>{let e=new eo().list().filter(o=>o.scopes.includes("app"));if(e.length===0){console.log(Te.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let o of e){let t=o.revokedAt?Te.red("revoked"):Te.green("active");console.log(` ${Te.cyan(o.id)} ${t} ${o.name}`),console.log(Te.dim(` paired: ${o.createdAt}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()});Lt.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new eo,t=o.list().find(n=>n.id===e&&n.scopes.includes("app"));t||(console.log(Te.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),o.revoke(e),console.log(Te.green(`
20
+ `))}catch(o){console.log(Ne.red(` ${o.message}`)),process.exit(1)}});import{Command as Su}from"commander";import Te from"chalk";import{execFileSync as yd}from"child_process";import{existsSync as hd}from"fs";oe();var Lt=new Su().name("app").description("pair phones with the AgentX phone app and manage paired devices");Lt.command("pair").description("pair a phone \u2014 prints a QR code to scan and a one-time code to type in the installed app").option("--name <name>","name for this phone (shown in `agentx app devices`)","Phone").option("--url <origin>","address the phone opens, e.g. https://my-mac.tailnet-name.ts.net (default: this machine's Tailscale name)").action(async e=>{try{let o=ar(cr(),Nn());if(o.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${o.join(", ")}`," Anyone on your tailnet can open it without a key. Serve only the app paths instead:"," tailscale serve reset (removes every served path; add the /member lines back if you use them)",` tailscale serve --bg --set-path /app http://127.0.0.1:${Nn()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${Nn()}/api/app`].join(`
21
+ `));let t=(e.url?String(e.url):rr()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(t))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${t}`);let{token:n,record:s}=new eo().create({name:String(e.name),scopes:["app"]}),{code:i}=new ys().create({token:n,tokenId:s.id,name:s.name}),r=`${t}/app/pair#token=${n}`,{default:a}=await import("qrcode-terminal");console.log(),a.generate(r,{small:!0},c=>console.log(c));for(let c of Eu({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!hd("agentx.json")&&!hd(".agentx/config.json")&&console.log(Te.yellow(" \u26A0 No agentx.json here. The dashboard only accepts phones paired from the folder that holds agentx.json.")),console.log()}catch(o){console.log(Te.red(` ${o.message}`)),process.exit(1)}});Lt.command("devices").description("list paired phones").action(()=>{let e=new eo().list().filter(o=>o.scopes.includes("app"));if(e.length===0){console.log(Te.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let o of e){let t=o.revokedAt?Te.red("revoked"):Te.green("active");console.log(` ${Te.cyan(o.id)} ${t} ${o.name}`),console.log(Te.dim(` paired: ${o.createdAt}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()});Lt.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new eo,t=o.list().find(n=>n.id===e&&n.scopes.includes("app"));t||(console.log(Te.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),o.revoke(e),console.log(Te.green(`
22
22
  \u2713 Unpaired ${e} (${t.name})
23
- `))});Lt.command("push-keys").description("create the key pair that lets this computer send notifications to paired phones").option("--force","replace existing keys (every phone must turn notifications on again)").action(async e=>{let o=Dc;try{o=j().channels.push.keysFile}catch{}let t=Pc(o),n=Mc(t);if(n&&!e.force){console.log(Te.green(`
23
+ `))});Lt.command("push-keys").description("create the key pair that lets this computer send notifications to paired phones").option("--force","replace existing keys (every phone must turn notifications on again)").action(async e=>{let o=Pc;try{o=T().channels.push.keysFile}catch{}let t=Mc(o),n=Lc(t);if(n&&!e.force){console.log(Te.green(`
24
24
  \u2713 Keys already exist in ${t} (created ${n.createdAt}).`)),console.log(Te.dim(` Replacing them cuts off every phone; pass --force if you really mean to.
25
- `));return}let{default:s}=await import("web-push");Lc(t,s.generateVAPIDKeys()),console.log(Te.green(`
25
+ `));return}let{default:s}=await import("web-push");qc(t,s.generateVAPIDKeys()),console.log(Te.green(`
26
26
  \u2713 Saved new push keys to ${t}`)),console.log(Te.dim(" Keep this file private. It is readable only by you, and agentx.json never contains it.")),n&&console.log(Te.yellow(" \u26A0 Old keys replaced: open Alerts on each phone and turn notifications on again.")),console.log(Te.dim(` Restart the daemon so it picks up the keys.
27
- `))});function xu(e){let o=Math.round(_c/6e4),t=[` Pairing code: ${Te.bold.cyan(hs(e.code))}`,Te.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 ${Te.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Te.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(Te.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function rr(){let e;try{e=JSON.parse(yd("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 Su=new Set(["/app","/api/app","/member","/api/member"]);function ar(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&&!Su.has(g)&&n.push(`${i}${a}`)}return n}function cr(){try{return JSON.parse(yd("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Nn(){try{return j().dashboard.port||4202}catch{return 4202}}oe();import{Command as bo}from"commander";import h from"chalk";import Me from"prompts";import{readFileSync as Uo,writeFileSync as qt,existsSync as we,mkdirSync as $o,cpSync as lr,readdirSync as gr}from"fs";import{resolve as H,join as qo,dirname as Eu}from"path";import{fileURLToPath as Au}from"url";function ge(){let e=H(process.cwd(),"agentx.json");if(!we(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Uo(e,"utf-8"))}function Je(e){return ie(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var it=new bo().name("agent").description("manage agents \u2014 add, list, remove");it.command("list").alias("ls").description("list configured agents").action(()=>{let e=ge();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});it.command("add").description("add a new agent interactively").action(async()=>{let e=ge(),o=await Me([{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:qo(o.workspace,o.id);$o(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(h.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Eu(Au(import.meta.url)),"../wiki/SKILL.md"),c=we(r)?r:a;we(c)&&($o(H(t,".claude/skills/wiki"),{recursive:!0}),lr(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Je(e),console.log(h.green(`
27
+ `))});function Eu(e){let o=Math.round(Dc/6e4),t=[` Pairing code: ${Te.bold.cyan(hs(e.code))}`,Te.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 ${Te.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Te.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(Te.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function rr(){let e;try{e=JSON.parse(yd("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 Au=new Set(["/app","/api/app","/member","/api/member"]);function ar(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&&!Au.has(g)&&n.push(`${i}${a}`)}return n}function cr(){try{return JSON.parse(yd("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Nn(){try{return T().dashboard.port||4202}catch{return 4202}}oe();import{Command as bo}from"commander";import h from"chalk";import Me from"prompts";import{readFileSync as Uo,writeFileSync as qt,existsSync as we,mkdirSync as $o,cpSync as lr,readdirSync as gr}from"fs";import{resolve as H,join as qo,dirname as Tu}from"path";import{fileURLToPath as ju}from"url";function ge(){let e=H(process.cwd(),"agentx.json");if(!we(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Uo(e,"utf-8"))}function Je(e){return ie(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var it=new bo().name("agent").description("manage agents \u2014 add, list, remove");it.command("list").alias("ls").description("list configured agents").action(()=>{let e=ge();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});it.command("add").description("add a new agent interactively").action(async()=>{let e=ge(),o=await Me([{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:qo(o.workspace,o.id);$o(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(h.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Tu(ju(import.meta.url)),"../wiki/SKILL.md"),c=we(r)?r:a;we(c)&&($o(H(t,".claude/skills/wiki"),{recursive:!0}),lr(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Je(e),console.log(h.green(`
28
28
  Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});it.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ge();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Je(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});it.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=ge(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Je(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Rn=new bo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Rn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ge().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
29
29
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
30
- `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Rn.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=ge();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-ZBNH2DMN.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Me({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 Me({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 Me({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 Me({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,...y]=f.split("=");p&&(g[p.trim()]=y.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Je(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Rn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ge(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Je(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Rn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ge().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});it.addCommand(Rn);var Ds=new bo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Ds.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ge();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Ds.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ge(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Me({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 Me([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Je(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Me([{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 Me([{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 Je(e),$o(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Me([{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 Me([{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 Je(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Ut=new bo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Ut.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ge();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Ut.command("add").description("add a cron job").action(async()=>{let e=ge(),o=Object.keys(e.agents||{}),t=await Me([{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 Je(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Ut.command("enable <id>").description("enable a cron job").action(async e=>{let o=ge();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Je(o),console.log(h.green(` Cron "${e}" enabled`))});Ut.command("disable <id>").description("disable a cron job").action(async e=>{let o=ge();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Je(o),console.log(h.green(` Cron "${e}" disabled`))});var to=new bo().name("mesh").description("manage mesh peers \u2014 add, list, remove");to.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ge();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});to.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ge(),o=await Me([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Je(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});to.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ge();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Je(o),console.log(h.green(` Peer "${e}" removed`)))});to.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=ge();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Je(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});to.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=j().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(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var wd=e=>{let o=e||"";if(!o)try{o=j().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Ps(e,o,t={}){let n=wd(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let i=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${o}`,{method:"POST",headers:s,body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` ${r.error||`HTTP ${i.status}`}`)),process.exit(1));let a=r.grant;console.log(h.green(` \u2713 ${a?.name??e}: ${a?.state}${r.stopped?`, ${r.stopped} running turn(s) stopped`:""}`))}catch(i){console.log(h.red(` Could not reach the daemon at ${n}: ${i?.message||i}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var rt=to.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");rt.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:o}=await import("./token-store-YBSU2DTV.js"),{PairCodeStore:t,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:i}=await import("./grants-N7XC7NLS.js"),r=j(),a=i({tokens:new o,codes:new t,guests:new s,hasAgent:l=>!!r.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(h.red(` ${a.error}`)),process.exit(1));let c=(e.url||wd()).replace(/\/+$/,"");console.log(),console.log(` Grant ${h.bold(a.grant.name)} for ${h.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(h.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${h.cyan(c)}`),console.log(` ${h.bold(n(a.code))}`),console.log(),console.log(` They run: ${h.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});rt.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:o}=await import("./store-7W2AP5H4.js"),t=new o().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(h.dim(`
30
+ `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Rn.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=ge();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-PTBPLRVQ.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Me({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 Me({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 Me({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 Me({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,...y]=f.split("=");p&&(g[p.trim()]=y.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Je(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Rn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ge(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Je(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Rn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ge().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});it.addCommand(Rn);var Ds=new bo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Ds.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ge();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Ds.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ge(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Me({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 Me([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Je(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Me([{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 Me([{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 Je(e),$o(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Me([{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 Me([{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 Je(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Ut=new bo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Ut.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ge();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Ut.command("add").description("add a cron job").action(async()=>{let e=ge(),o=Object.keys(e.agents||{}),t=await Me([{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 Je(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Ut.command("enable <id>").description("enable a cron job").action(async e=>{let o=ge();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Je(o),console.log(h.green(` Cron "${e}" enabled`))});Ut.command("disable <id>").description("disable a cron job").action(async e=>{let o=ge();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Je(o),console.log(h.green(` Cron "${e}" disabled`))});var to=new bo().name("mesh").description("manage mesh peers \u2014 add, list, remove");to.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ge();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});to.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ge(),o=await Me([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Je(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});to.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ge();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Je(o),console.log(h.green(` Peer "${e}" removed`)))});to.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=ge();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Je(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});to.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=T().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(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var wd=e=>{let o=e||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Ps(e,o,t={}){let n=wd(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let i=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${o}`,{method:"POST",headers:s,body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` ${r.error||`HTTP ${i.status}`}`)),process.exit(1));let a=r.grant;console.log(h.green(` \u2713 ${a?.name??e}: ${a?.state}${r.stopped?`, ${r.stopped} running turn(s) stopped`:""}`))}catch(i){console.log(h.red(` Could not reach the daemon at ${n}: ${i?.message||i}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var rt=to.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");rt.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:o}=await import("./token-store-YBSU2DTV.js"),{PairCodeStore:t,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:i}=await import("./grants-N7XC7NLS.js"),r=T(),a=i({tokens:new o,codes:new t,guests:new s,hasAgent:l=>!!r.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(h.red(` ${a.error}`)),process.exit(1));let c=(e.url||wd()).replace(/\/+$/,"");console.log(),console.log(` Grant ${h.bold(a.grant.name)} for ${h.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(h.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${h.cyan(c)}`),console.log(` ${h.bold(n(a.code))}`),console.log(),console.log(` They run: ${h.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});rt.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:o}=await import("./store-7W2AP5H4.js"),t=new o().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(h.dim(`
31
31
  No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
32
32
  `));return}console.log();for(let n of t){let s=n.state==="active"?h.green("active"):n.state==="pending"?h.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?h.yellow("paused"):h.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${h.cyan(n.id)} ${h.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(h.dim(` until ${n.expiresAt.slice(0,10)} \xB7 ${n.usage.turns} turn(s), ${n.usage.tokens} tokens${n.usage.lastAt?` \xB7 last ${n.usage.lastAt.slice(0,16).replace("T"," ")} UTC`:""}${n.guestNode?.name?` \xB7 node ${n.guestNode.name}`:""}`))}console.log()});rt.command("show <id>").description("one grant, what it opens and what the guest did").action(async e=>{let{GuestStore:o}=await import("./store-7W2AP5H4.js"),t=new o,n=t.get(e);n||(console.log(h.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${h.bold(n.name)} (${n.id}) \xB7 ${n.state}`),console.log(` guest: ${n.guest}${n.guestNode?` \xB7 node ${n.guestNode.name??n.guestNode.id??"?"} at ${n.guestNode.address??"?"}`:""}`),console.log(` agent: ${n.agentId} \xB7 level: ${n.level} \xB7 until ${n.expiresAt.slice(0,10)}`),console.log(` folders: ${n.folders.join(", ")||"none"}
33
33
  skills: ${n.skills.join(", ")||"none"}
34
34
  commands: ${n.commands.join(", ")||"none"}`),console.log(` usage: ${n.usage.turns} turn(s), ${n.usage.tokens} tokens`),console.log(`
35
- Trail (newest first)`);for(let s of t.events(e,30))console.log(h.dim(` ${s.at.slice(0,19).replace("T"," ")} ${s.event}${s.detail?` ${s.detail}`:""}${s.address?` from ${s.address}`:""}`));console.log()});rt.command("pause <id>").description("stop the guest at once; running turns are cancelled. Resume later").action(e=>Ps(e,"pause"));rt.command("resume <id>").description("let a paused guest work again").action(e=>Ps(e,"resume"));rt.command("end <id>").description("end the grant for good; its key stops at once").action(e=>Ps(e,"end"));rt.command("set <id>").description("widen or narrow a grant while it is in use").option("--folders <list>",'folders, comma-separated ("none" clears)').option("--skills <list>",'skills, comma-separated ("none" clears)').option("--commands <list>",'commands, comma-separated ("none" clears)').option("--level <level>","report | propose | act").option("--days <n>","new length, counted from now").action((e,o)=>{let t=s=>s===void 0?void 0:s.toLowerCase()==="none"?[]:s.split(","),n={};return o.folders!==void 0&&(n.folders=t(o.folders)),o.skills!==void 0&&(n.skills=t(o.skills)),o.commands!==void 0&&(n.commands=t(o.commands)),o.level!==void 0&&(n.level=o.level),o.days!==void 0&&(n.days=Number(o.days)),Object.keys(n).length||(console.log(h.red(" Nothing to change: pass --folders, --skills, --commands, --level or --days.")),process.exit(1)),Ps(e,"update",n)});to.command("join <url>").description("join another organisation's mesh as a guest, with the code its owner sent you").requiredOption("--code <code>","the one-time code from the host").requiredOption("--name <name>","what you call the host, e.g. company-x").action(async(e,o)=>{let{GuestHostStore:t}=await import("./hosts-NFNCYKGY.js"),n=e.replace(/\/+$/,""),s={};try{let i=j();s={id:i.node?.id,name:i.node?.name}}catch{}try{let i=await fetch(`${n}/mesh/guest/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o.code,node:s}),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Join refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),new t().add({name:o.name,url:n,token:String(r.token),grant:String(r.grant),agentId:String(r.agentId),expiresAt:String(r.expiresAt),joinedAt:new Date().toISOString()}),console.log(h.green(`
35
+ Trail (newest first)`);for(let s of t.events(e,30))console.log(h.dim(` ${s.at.slice(0,19).replace("T"," ")} ${s.event}${s.detail?` ${s.detail}`:""}${s.address?` from ${s.address}`:""}`));console.log()});rt.command("pause <id>").description("stop the guest at once; running turns are cancelled. Resume later").action(e=>Ps(e,"pause"));rt.command("resume <id>").description("let a paused guest work again").action(e=>Ps(e,"resume"));rt.command("end <id>").description("end the grant for good; its key stops at once").action(e=>Ps(e,"end"));rt.command("set <id>").description("widen or narrow a grant while it is in use").option("--folders <list>",'folders, comma-separated ("none" clears)').option("--skills <list>",'skills, comma-separated ("none" clears)').option("--commands <list>",'commands, comma-separated ("none" clears)').option("--level <level>","report | propose | act").option("--days <n>","new length, counted from now").action((e,o)=>{let t=s=>s===void 0?void 0:s.toLowerCase()==="none"?[]:s.split(","),n={};return o.folders!==void 0&&(n.folders=t(o.folders)),o.skills!==void 0&&(n.skills=t(o.skills)),o.commands!==void 0&&(n.commands=t(o.commands)),o.level!==void 0&&(n.level=o.level),o.days!==void 0&&(n.days=Number(o.days)),Object.keys(n).length||(console.log(h.red(" Nothing to change: pass --folders, --skills, --commands, --level or --days.")),process.exit(1)),Ps(e,"update",n)});to.command("join <url>").description("join another organisation's mesh as a guest, with the code its owner sent you").requiredOption("--code <code>","the one-time code from the host").requiredOption("--name <name>","what you call the host, e.g. company-x").action(async(e,o)=>{let{GuestHostStore:t}=await import("./hosts-NFNCYKGY.js"),n=e.replace(/\/+$/,""),s={};try{let i=T();s={id:i.node?.id,name:i.node?.name}}catch{}try{let i=await fetch(`${n}/mesh/guest/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o.code,node:s}),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Join refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),new t().add({name:o.name,url:n,token:String(r.token),grant:String(r.grant),agentId:String(r.agentId),expiresAt:String(r.expiresAt),joinedAt:new Date().toISOString()}),console.log(h.green(`
36
36
  \u2713 Joined ${o.name} as a guest: grant "${r.name}", agent ${r.agentId}, ${r.level}, until ${String(r.expiresAt).slice(0,10)}.`)),console.log(h.dim(" The host's owner has to approve the join once. Check with: agentx mesh hosts")),console.log(h.dim(` Then ask: agentx mesh ask ${o.name} "<message>", or from an agent: POST /mesh/task { peer: "${o.name}", message }
37
37
  `))}catch(i){console.log(h.red(` Could not reach ${n}: ${i?.message||i}`)),process.exit(1)}});to.command("hosts").description("the meshes this node has joined as a guest, and where each grant stands").action(async()=>{let{GuestHostStore:e,hostStatus:o}=await import("./hosts-NFNCYKGY.js"),t=new e().hosts();if(!t.length){console.log(h.dim(`
38
38
  Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
39
39
  `));return}console.log();for(let n of t){let s=await o(n),i=s.ok?s.grant.state==="active"?h.green("active"):h.yellow(String(s.grant.state)):s.status===403?h.yellow(s.error):h.red(s.error);console.log(` ${h.cyan(n.name)} ${h.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${i}`)}console.log()});to.command("ask <host> <message...>").description("ask the host's agent something, inside the grant").action(async(e,o)=>{let{GuestHostStore:t,askHost:n}=await import("./hosts-NFNCYKGY.js"),s=new t().get(e);s||(console.log(h.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let i=await n(s,o.join(" "));i.error&&(console.log(h.red(` ${i.error}`)),process.exit(1)),console.log(`
40
40
  ${i.content}
41
- `)});to.command("leave <host>").description("forget a host you joined as a guest (the host can also end it on its side)").action(async e=>{let{GuestHostStore:o}=await import("./hosts-NFNCYKGY.js");new o().remove(e)||(console.log(h.red(` No host "${e}".`)),process.exit(1)),console.log(h.green(` \u2713 Left ${e}`))});var at=new bo().name("skill").description("manage skills \u2014 add to agent(s), list");at.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=ge(),n=H(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(qo(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 Me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);$o(c,{recursive:!0}),we(qo(n,"SKILL.md"))?lr(n,c,{recursive:!0}):n.endsWith(".md")&&lr(n,qo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});at.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ge();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=we(n)?gr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});at.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=>we(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=Uo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=j()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,y=0;for(let[k,b]of d){let $=b.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||($o(E,{recursive:!0}),qt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Uo(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||qt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${y} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});at.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=ge().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=ge();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"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let y of f.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});at.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=ge(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-6QI65HKR.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
41
+ `)});to.command("leave <host>").description("forget a host you joined as a guest (the host can also end it on its side)").action(async e=>{let{GuestHostStore:o}=await import("./hosts-NFNCYKGY.js");new o().remove(e)||(console.log(h.red(` No host "${e}".`)),process.exit(1)),console.log(h.green(` \u2713 Left ${e}`))});var at=new bo().name("skill").description("manage skills \u2014 add to agent(s), list");at.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=ge(),n=H(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(qo(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 Me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);$o(c,{recursive:!0}),we(qo(n,"SKILL.md"))?lr(n,c,{recursive:!0}):n.endsWith(".md")&&lr(n,qo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});at.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ge();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=we(n)?gr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});at.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=>we(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=Uo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=T()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,y=0;for(let[k,b]of d){let $=b.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||($o(E,{recursive:!0}),qt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Uo(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||qt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${y} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});at.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=ge().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=ge();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"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let y of f.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});at.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=ge(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-APGSUM4S.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
42
42
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
43
43
  (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var _n=new bo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");_n.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=H(o.cwd),n=H(t,"references/example"),s=H(t,"references/recipes/example.yaml");we(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(t,".agentx/references",e),r=H(t,".agentx/references/recipes");$o(i,{recursive:!0}),$o(r,{recursive:!0});let a=gr(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=qo(i,d);if(we(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Uo(qo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);qt(u,p),console.log(h.green(` + ${u}`)),c++}let g=qo(r,`${e}.yaml`);if(we(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(we(s)){let d=Uo(s,"utf-8").replaceAll("example.",`${e}.`);qt(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});_n.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(o.cwd),r=o.from?String(o.from).split(",").map(y=>y.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([y,w])=>[y,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(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[y,w]of Object.entries(g))console.log(h.cyan(`
44
44
  --- ${y} ---`)),console.log(w.split(`
@@ -47,7 +47,7 @@ ${i.content}
47
47
  `).length>30&&console.log(h.dim(` \u2026 (${w.split(`
48
48
  `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}$o(u,{recursive:!0});let f=0,p=0;for(let[y,w]of Object.entries(g)){let k=qo(u,y);if(we(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}qt(k,w),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});_n.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(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var mr=new bo().name("hook").description("manage hooks \u2014 add to agent workspace");mr.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ge().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=H(t.workspace,".claude/settings.json"),s=we(n)?JSON.parse(Uo(n,"utf-8")):{},i=await Me([{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),$o(H(t.workspace,".claude"),{recursive:!0}),qt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var pr=new bo().name("migrate").description("import configuration from OpenClaw or other tools");pr.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&&we(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(Uo(n,"utf-8")),i=we(H(process.cwd(),"agentx.json"))?ge():{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"),y=f.groupChat?.mentionPatterns||[];if(y.some(w=>w===p)||y.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:y,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){$o(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-42ARC42I.js");w(p,i.agents[p])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,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(` ${h.green(d)} Telegram accounts imported`);let u=H(n,"../cron/jobs.json");if(we(u)){let f=JSON.parse(Uo(u,"utf-8")),p=0;for(let y of f.jobs||[]){let w=y.name||y.id,k=y.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:y.enabled||!1,schedule:y.schedule?.expr||"0 9 * * *",timezone:y.schedule?.tz||"UTC",agent:k,prompt:y.payload?.message||"",timeout:y.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
49
49
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Je(i),console.log(h.green(`
50
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Fo=new bo().name("config").description("validate and inspect configuration");Fo.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=j(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=as(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=we(H(r,".claude")),c=we(H(r,"CLAUDE.md")),l=we(H(r,".claude/settings.json")),g=we(H(r,".claude/skills"))?gr(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Fo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=j(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Tu(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 dr(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Fo.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-ENWFEDFU.js"),{expandEnvVars:r}=await import("./config-ZBNH2DMN.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(dr(g))});Fo.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-ENWFEDFU.js"),r=Tu(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${dr(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${dr(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Fo.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-ENWFEDFU.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});Fo.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=j(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});rs();import{Command as ju}from"commander";import Wo from"chalk";import{resolve as Jo}from"path";import{existsSync as Ou}from"fs";var Ao=new ju().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function ct(e){let o=Jo(e,".agentx/db.sqlite");Ou(o)||(console.log(Wo.red(` No SQLite at ${o}`)),console.log(Wo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Do({path:o});return t||(console.log(Wo.red(` Could not open ${o}`)),console.log(Wo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function lt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Wo.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])))}Ao.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=ct(Jo(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=`
50
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Fo=new bo().name("config").description("validate and inspect configuration");Fo.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=T(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=as(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=we(H(r,".claude")),c=we(H(r,"CLAUDE.md")),l=we(H(r,".claude/settings.json")),g=we(H(r,".claude/skills"))?gr(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Fo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=T(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Ou(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 dr(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Fo.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-QVETJAFD.js"),{expandEnvVars:r}=await import("./config-PTBPLRVQ.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(dr(g))});Fo.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-QVETJAFD.js"),r=Ou(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${dr(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${dr(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Fo.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-QVETJAFD.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});Fo.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=T(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});rs();import{Command as Cu}from"commander";import Wo from"chalk";import{resolve as Jo}from"path";import{existsSync as Iu}from"fs";var Ao=new Cu().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function ct(e){let o=Jo(e,".agentx/db.sqlite");Iu(o)||(console.log(Wo.red(` No SQLite at ${o}`)),console.log(Wo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Do({path:o});return t||(console.log(Wo.red(` Could not open ${o}`)),console.log(Wo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function lt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Wo.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])))}Ao.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=ct(Jo(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=`
51
51
  SELECT agent_id, channel, status, duration_ms,
52
52
  input_tokens, output_tokens,
53
53
  substr(message_preview, 1, 60) AS message,
@@ -98,7 +98,7 @@ ${i.content}
98
98
  WHERE ${t.join(" AND ")}
99
99
  ORDER BY started_at DESC
100
100
  LIMIT @limit
101
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});lt(i,!!e.json)});Ao.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=ct(Jo(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));lt(n,!!e.json)});Ao.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=ct(Jo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Wo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Wo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();lt(n,!!o.json)}catch(n){console.log(Wo.red(` ${n.message}`)),process.exit(1)}});import{Command as Nu}from"commander";import z from"chalk";import{mkdtempSync as Ru}from"fs";import{tmpdir as _u}from"os";import{resolve as bd,join as kd}from"path";import{existsSync as Du}from"fs";import Pu from"better-sqlite3";function $d(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(p){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${p?.message??p}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=Cu(l),u={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=Ya(e,u,d,()=>l.decidedAt);a+=1,(f.outcome!==l.outcome||f.agentId!==l.agentId)&&r.push({eventId:g.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Iu(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Cu(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Iu(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var Bo=new Nu().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Ft(e){let o=bd(e.cwd??process.cwd()),t=bd(o,e.path??".agentx/intent/ledger.sqlite");Du(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Pu(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function dt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.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])))}function Mu(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Ms(e){if(!e)return;let o=Mu(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Bo.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=Ft(e),t=Ms(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),l=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),d=o.prepare(`
101
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});lt(i,!!e.json)});Ao.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=ct(Jo(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));lt(n,!!e.json)});Ao.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=ct(Jo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Wo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Wo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();lt(n,!!o.json)}catch(n){console.log(Wo.red(` ${n.message}`)),process.exit(1)}});import{Command as _u}from"commander";import z from"chalk";import{mkdtempSync as Du}from"fs";import{tmpdir as Pu}from"os";import{resolve as bd,join as kd}from"path";import{existsSync as Mu}from"fs";import Lu from"better-sqlite3";function $d(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(p){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${p?.message??p}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=Nu(l),u={id:g.id,ts:g.ts,source:g.source,sourceEventId:g.sourceEventId,project:g.project,subject:g.subject,intent:g.intent,rawJson:g.rawJson},f=Ya(e,u,d,()=>l.decidedAt);a+=1,(f.outcome!==l.outcome||f.agentId!==l.agentId)&&r.push({eventId:g.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:f.agentId,outcome:f.outcome},reason:Ru(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Nu(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Ru(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var Bo=new _u().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Ft(e){let o=bd(e.cwd??process.cwd()),t=bd(o,e.path??".agentx/intent/ledger.sqlite");Mu(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Lu(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function dt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.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])))}function qu(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Ms(e){if(!e)return;let o=qu(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Bo.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=Ft(e),t=Ms(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),l=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),d=o.prepare(`
102
102
  SELECT COUNT(*) as n FROM intent_decisions d
103
103
  LEFT JOIN intent_resolutions r
104
104
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
@@ -167,7 +167,7 @@ ${i.content}
167
167
  SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
168
168
  FROM intent_resolutions
169
169
  WHERE decision_event_id IN (${c})
170
- `).all(l).map(p=>({decisionEventId:p.decision_event_id,decisionDecidedBy:p.decision_decided_by,resolvedAt:p.resolved_at,status:p.status,durationMs:p.duration_ms,resultSummary:p.result_summary})),u=Ru(kd(_u(),"agentx-ledger-replay-")),f=new Ua({path:kd(u,"target.sqlite")});try{let p=$d(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(z.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${p.divergences.length} divergences`)),dt(p.divergences.map(y=>({event_id:y.eventId,decided_by:y.decidedBy,recorded:`${y.expected.outcome}/${y.expected.agentId??"-"}`,replayed:`${y.actual.outcome}/${y.actual.agentId??"-"}`,reason:y.reason.slice(0,80)})),!1))}finally{f.close()}});$a();jp();Op();Cp();Sp();Na();wn();import{Command as Lu}from"commander";import F from"chalk";import{existsSync as vd}from"fs";import{resolve as ur}from"path";import qu from"better-sqlite3";var Ge=new Lu().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),co=".agentx/decisions/decisions.sqlite";function Uu(e){return ur(ur(e.cwd??process.cwd()),e.path??co)}function vo(e,o=!1){let t=Uu(e);vd(t)||(console.log(F.red(` No decision store at ${t}`)),console.log(F.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new is({path:t,readonly:!o})}catch(n){console.log(F.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(F.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function ko(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(F.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(F.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function fr(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function hr(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:fr(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Ge.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",co).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=vo(e),t=fr(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
170
+ `).all(l).map(p=>({decisionEventId:p.decision_event_id,decisionDecidedBy:p.decision_decided_by,resolvedAt:p.resolved_at,status:p.status,durationMs:p.duration_ms,resultSummary:p.result_summary})),u=Du(kd(Pu(),"agentx-ledger-replay-")),f=new Ua({path:kd(u,"target.sqlite")});try{let p=$d(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(z.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${p.divergences.length} divergences`)),dt(p.divergences.map(y=>({event_id:y.eventId,decided_by:y.decidedBy,recorded:`${y.expected.outcome}/${y.expected.agentId??"-"}`,replayed:`${y.actual.outcome}/${y.actual.agentId??"-"}`,reason:y.reason.slice(0,80)})),!1))}finally{f.close()}});$a();Cp();Ip();Np();Ap();Na();wn();import{Command as Uu}from"commander";import F from"chalk";import{existsSync as vd}from"fs";import{resolve as ur}from"path";import Fu from"better-sqlite3";var Ge=new Uu().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),co=".agentx/decisions/decisions.sqlite";function Wu(e){return ur(ur(e.cwd??process.cwd()),e.path??co)}function vo(e,o=!1){let t=Wu(e);vd(t)||(console.log(F.red(` No decision store at ${t}`)),console.log(F.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new is({path:t,readonly:!o})}catch(n){console.log(F.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(F.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function ko(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(F.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(F.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function fr(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function hr(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:fr(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Ge.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",co).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=vo(e),t=fr(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
171
171
  COUNT(*) AS calls,
172
172
  SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
173
173
  SUM(retries) AS retries,
@@ -185,7 +185,7 @@ ${i.content}
185
185
  Those are the only rows in the skip region that can ever be graded.`))),o.close()});Ge.command("calls").description("recent calls").option("--path <file>","store path",co).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=vo(e),t=["ts >= ?"],n=[fr(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
186
186
  structure_mode AS structure, latency_ms AS ms, retries, truncated, error
187
187
  FROM decision_calls WHERE ${t.join(" AND ")}
188
- ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));ko(s,e.json),o.close()});Ge.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",co).option("--json").action((e,o)=>{let t=vo(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(F.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}ko(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});Ge.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",co).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=vo(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(F.green(` labeled ${e}.${o} = ${t}`)),s.close()});Ge.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",co).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=vo(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));ko(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Ge.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",co).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=vo(e,!0),t=ur(process.cwd(),e.db);vd(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new qu(t,{readonly:!0});try{let s=pc(n,o);console.log(F.green(` wrote ${s} label(s)`)),s===0&&console.log(F.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
188
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));ko(s,e.json),o.close()});Ge.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",co).option("--json").action((e,o)=>{let t=vo(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(F.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}ko(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});Ge.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",co).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=vo(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(F.green(` labeled ${e}.${o} = ${t}`)),s.close()});Ge.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",co).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=vo(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));ko(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Ge.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",co).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=vo(e,!0),t=ur(process.cwd(),e.db);vd(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new Fu(t,{readonly:!0});try{let s=uc(n,o);console.log(F.green(` wrote ${s} label(s)`)),s===0&&console.log(F.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
189
189
  label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});Ge.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",co).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=vo(e),t=o.gradedRows(hr(e)),n=ja(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(F.bold(`
190
190
  ${e.seat}${e.question?`.${e.question}`:""}`)),console.log(` ${n.n} answers, ${n.nLabeled} labeled`+(n.agreement.n>0?`, ${n.agreement.n} with an incumbent (agree ${(n.agreement.rate*100).toFixed(1)}%, kappa ${n.agreement.kappa.toFixed(3)})`:"")),n.insufficient){console.log(F.yellow(`
191
191
  Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(F.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(F.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
@@ -216,14 +216,14 @@ ${i.content}
216
216
  calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
217
217
  traffic. Reading real logits does not buy this: a posterior can be
218
218
  confidently wrong. It comes from a recalibrator fitted on your own
219
- labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Ge.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{vt();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=kt(s,"Which option fits this state?")}e.noul&&(o.verdict=Eo(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await Ti(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Hu}from"commander";import O from"chalk";import{resolve as Od}from"path";import{existsSync as Gu}from"fs";import zu from"better-sqlite3";var xd=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],Fu=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function Ed(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...Fu,...xd,"num_turns","injected_context"].map(d=>t.has(d)?d:`NULL AS ${d}`).join(", "),i=["status IN ('ok', 'error', 'timeout')"],r=[];o.since!==void 0&&(i.push("started_at >= ?"),r.push(o.since)),o.agentId&&(i.push("agent_id = ?"),r.push(o.agentId));let a=i.join(" AND "),c=e.prepare(`
219
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Ge.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{vt();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=kt(s,"Which option fits this state?")}e.noul&&(o.verdict=Eo(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await Ti(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as zu}from"commander";import O from"chalk";import{resolve as Od}from"path";import{existsSync as Yu}from"fs";import Vu from"better-sqlite3";var xd=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],Ju=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function Ed(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...Ju,...xd,"num_turns","injected_context"].map(d=>t.has(d)?d:`NULL AS ${d}`).join(", "),i=["status IN ('ok', 'error', 'timeout')"],r=[];o.since!==void 0&&(i.push("started_at >= ?"),r.push(o.since)),o.agentId&&(i.push("agent_id = ?"),r.push(o.agentId));let a=i.join(" AND "),c=e.prepare(`
220
220
  SELECT ${s} FROM task_traces WHERE ${a} ORDER BY started_at
221
221
  `).all(...r),l=new Map,g=e.prepare(`
222
222
  SELECT task_id, action FROM task_trace_steps
223
223
  WHERE name = 'tool_use' AND action IS NOT NULL
224
224
  AND task_id IN (SELECT task_id FROM task_traces WHERE ${a})
225
225
  ORDER BY task_id, seq
226
- `).all(...r);for(let d of g){let u=l.get(d.task_id)??[];u.push(d.action),l.set(d.task_id,u)}return c.map(d=>{let u=d.task_id,f=d.agent_id,p=hc({taskId:u,agentId:f,channel:d.channel??"unknown",chatId:d.chat_id??"",startedAt:d.started_at,userMessage:(d.original_message??d.message_preview??"").trim(),userTurns:[],actions:l.get(u)??[],actionSummaries:[]}),y=xd.map(w=>d[w]).filter(w=>typeof w=="number");return{taskId:u,agentId:f,cluster:p,startedAt:d.started_at,ok:d.status==="ok",tokens:y.length>0?y.reduce((w,k)=>w+k,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:Va(d.injected_context)}})}function yr(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function wr(e){let o=e.filter(n=>n!==null).sort((n,s)=>n-s);if(o.length===0)return null;let t=Math.floor(o.length/2);return o.length%2?o[t]:(o[t-1]+o[t])/2}function Sd(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:wr(e.map(o=>o.tokens)),medianTurns:wr(e.map(o=>o.turns)),medianDurationMs:wr(e.map(o=>o.durationMs))}}function Ad(e,o={}){let t=Math.max(1,o.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of yr(r)){let g=`${r.agentId}\0${l}`;n.set(g,Math.min(n.get(g)??1/0,r.startedAt))}let a=`${r.agentId}\0${r.cluster}`,c=s.get(a)??[];c.push(r),s.set(a,c)}let i=[];for(let r of s.values()){let{agentId:a,cluster:c}=r[0],l=new Set(r.flatMap(yr));for(let g of l){let d=n.get(`${a}\0${g}`),u=r.filter(p=>p.injected!==null&&p.startedAt<d),f=r.filter(p=>yr(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Sd(u),after:Sd(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Ho from"chalk";function Wu(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function Ju(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function Bu(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function $r(e,o){if(e==null||o==null||e===0)return"";let t=Math.round((o-e)/e*100);return t===0?" (=)":` (${t>0?"+":""}${t}%)`}function Td(e,o,t){let n=`${Math.round(o.successRate*100)}%`,s=t?` (${o.successRate>=t.successRate?"+":""}${Math.round((o.successRate-t.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(o.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${Wu(o.medianTokens)}${t?$r(t.medianTokens,o.medianTokens):""}`,`turns ${Bu(o.medianTurns)}${t?$r(t.medianTurns,o.medianTurns):""}`,`time ${Ju(o.medianDurationMs)}${t?$r(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function jd(e,o){if(e.length===0)return[Ho.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Ho.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let t=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&t.push(""),t.push(`${Ho.bold(s.agentId)} ${Ho.cyan(s.cluster)}`),n=i),t.push(` ${Ho.yellow(s.lesson)} ${Ho.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Ho.dim(Td("before",s.before))),t.push(Td("after",s.after,s.before))}return t.push(""),t.push(Ho.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var Wt=new Hu().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function qs(e){let o=Od(e.cwd??process.cwd()),t=Od(o,e.path??".agentx/db.sqlite");Gu(t)||(console.log(O.red(` No db at ${t}`)),console.log(O.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new zu(t,{readonly:!0})}catch(n){console.log(O.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(O.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Yu(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Cd(e){if(!e)return;let o=Yu(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(O.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Vu(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function br(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}Wt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=qs(e),t=Ka(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Cd(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(O.dim(" (no traces)"));return}for(let n of t){let s=br(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?O.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?O.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${O.dim(n.taskId)} ${s} ${O.bold(n.agentId)}${O.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${O.dim("\xB7")} ${i}${a} ${O.dim(Vu(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});Wt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=qs(o),n=_i(t,e);if(n||(console.log(O.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Ku(n.task,n.steps)});function Ku(e,o){let t=br(e.status)(e.status);if(console.log(O.bold(`Trace ${e.taskId}`)),console.log(` ${O.dim("agent")} ${e.agentId}`),console.log(` ${O.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${O.dim("workflow")} ${O.cyan(e.workflowRunId)}${n?O.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${O.dim("intent")} ${e.intentEventId} ${O.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${O.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${O.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${O.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${O.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${O.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${O.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.numTurns!=null&&console.log(` ${O.dim("turns")} ${e.numTurns}`),e.injectedContext){let{memory:n,procedures:s,wiki:i}=e.injectedContext,r=[...n.map(a=>`memory:${a}`),...s.map(a=>`procedure:${a}`),...i?["wiki"]:[]];console.log(` ${O.dim("lessons")} ${r.length?r.join(" "):O.dim("none")}`)}if(e.error&&console.log(` ${O.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${O.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(O.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(O.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?br(n.status)(n.status):O.dim("\u2014"),i=n.action?O.cyan(n.action):"";if(console.log(` ${O.dim(`#${n.seq}`)} ${O.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?O.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
226
+ `).all(...r);for(let d of g){let u=l.get(d.task_id)??[];u.push(d.action),l.set(d.task_id,u)}return c.map(d=>{let u=d.task_id,f=d.agent_id,p=yc({taskId:u,agentId:f,channel:d.channel??"unknown",chatId:d.chat_id??"",startedAt:d.started_at,userMessage:(d.original_message??d.message_preview??"").trim(),userTurns:[],actions:l.get(u)??[],actionSummaries:[]}),y=xd.map(w=>d[w]).filter(w=>typeof w=="number");return{taskId:u,agentId:f,cluster:p,startedAt:d.started_at,ok:d.status==="ok",tokens:y.length>0?y.reduce((w,k)=>w+k,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:Va(d.injected_context)}})}function yr(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function wr(e){let o=e.filter(n=>n!==null).sort((n,s)=>n-s);if(o.length===0)return null;let t=Math.floor(o.length/2);return o.length%2?o[t]:(o[t-1]+o[t])/2}function Sd(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:wr(e.map(o=>o.tokens)),medianTurns:wr(e.map(o=>o.turns)),medianDurationMs:wr(e.map(o=>o.durationMs))}}function Ad(e,o={}){let t=Math.max(1,o.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of yr(r)){let g=`${r.agentId}\0${l}`;n.set(g,Math.min(n.get(g)??1/0,r.startedAt))}let a=`${r.agentId}\0${r.cluster}`,c=s.get(a)??[];c.push(r),s.set(a,c)}let i=[];for(let r of s.values()){let{agentId:a,cluster:c}=r[0],l=new Set(r.flatMap(yr));for(let g of l){let d=n.get(`${a}\0${g}`),u=r.filter(p=>p.injected!==null&&p.startedAt<d),f=r.filter(p=>yr(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Sd(u),after:Sd(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Ho from"chalk";function Bu(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function Hu(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function Gu(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function $r(e,o){if(e==null||o==null||e===0)return"";let t=Math.round((o-e)/e*100);return t===0?" (=)":` (${t>0?"+":""}${t}%)`}function Td(e,o,t){let n=`${Math.round(o.successRate*100)}%`,s=t?` (${o.successRate>=t.successRate?"+":""}${Math.round((o.successRate-t.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(o.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${Bu(o.medianTokens)}${t?$r(t.medianTokens,o.medianTokens):""}`,`turns ${Gu(o.medianTurns)}${t?$r(t.medianTurns,o.medianTurns):""}`,`time ${Hu(o.medianDurationMs)}${t?$r(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function jd(e,o){if(e.length===0)return[Ho.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Ho.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let t=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&t.push(""),t.push(`${Ho.bold(s.agentId)} ${Ho.cyan(s.cluster)}`),n=i),t.push(` ${Ho.yellow(s.lesson)} ${Ho.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Ho.dim(Td("before",s.before))),t.push(Td("after",s.after,s.before))}return t.push(""),t.push(Ho.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var Wt=new zu().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function qs(e){let o=Od(e.cwd??process.cwd()),t=Od(o,e.path??".agentx/db.sqlite");Yu(t)||(console.log(O.red(` No db at ${t}`)),console.log(O.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Vu(t,{readonly:!0})}catch(n){console.log(O.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(O.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Ku(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Cd(e){if(!e)return;let o=Ku(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(O.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Xu(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function br(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}Wt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=qs(e),t=Ka(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Cd(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(O.dim(" (no traces)"));return}for(let n of t){let s=br(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?O.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?O.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${O.dim(n.taskId)} ${s} ${O.bold(n.agentId)}${O.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${O.dim("\xB7")} ${i}${a} ${O.dim(Xu(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});Wt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=qs(o),n=_i(t,e);if(n||(console.log(O.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Qu(n.task,n.steps)});function Qu(e,o){let t=br(e.status)(e.status);if(console.log(O.bold(`Trace ${e.taskId}`)),console.log(` ${O.dim("agent")} ${e.agentId}`),console.log(` ${O.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${O.dim("workflow")} ${O.cyan(e.workflowRunId)}${n?O.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${O.dim("intent")} ${e.intentEventId} ${O.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${O.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${O.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${O.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${O.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${O.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${O.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.numTurns!=null&&console.log(` ${O.dim("turns")} ${e.numTurns}`),e.injectedContext){let{memory:n,procedures:s,wiki:i}=e.injectedContext,r=[...n.map(a=>`memory:${a}`),...s.map(a=>`procedure:${a}`),...i?["wiki"]:[]];console.log(` ${O.dim("lessons")} ${r.length?r.join(" "):O.dim("none")}`)}if(e.error&&console.log(` ${O.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${O.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(O.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(O.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?br(n.status)(n.status):O.dim("\u2014"),i=n.action?O.cyan(n.action):"";if(console.log(` ${O.dim(`#${n.seq}`)} ${O.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?O.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
227
227
  `).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2192")} ${a}`).join(`
228
228
  `)),n.inputSummary.split(`
229
229
  `).length>8&&console.log(` ${O.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
@@ -231,7 +231,7 @@ ${i.content}
231
231
  `)),n.outputSummary.split(`
232
232
  `).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}Wt.command("lessons").description("compare repeated tasks before and after each lesson (memory, procedure, wiki) was used").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","only this agent").option("--since <duration>","only tasks newer than (e.g. 7d, 30d)","30d").option("--min <n>","minimum tasks on each side of a lesson","2").option("--json","emit JSON").action(e=>{let o=qs(e),t=Math.max(1,parseInt(e.min,10)||2),n=Ed(o,{since:Cd(e.since),agentId:e.agent}),s=Ad(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of jd(s,{minSamples:t}))console.log(i)});Wt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=qs(o),n=_i(t,e);n||(console.log(O.red(` task not found: ${e}`)),console.log(O.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(O.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(O.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(O.bold(` replay ${O.cyan(e)}`)),console.log(O.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(O.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},l=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(O.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let d=await g.json().catch(()=>({})),u=Date.now()-l;if(g.ok||(console.log(O.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(O.bold(" INPUT (replayed verbatim)")),console.log(),Ls(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Ls(s.finalResponse):console.log(O.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(O.bold(` CURRENT OUTPUT ${O.dim(`status=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Ls(d.content??"(empty reply)"),d.error&&console.log(O.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?O.dim(" outputs are identical"):O.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(O.green(` \u2713 replayed in ${u}ms`)),console.log(),Ls(d.content??"(empty reply)"),d.error&&console.log(O.red(`
233
233
  error: ${d.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Ls(e){let o=e.split(`
234
- `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${O.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${O.dim("\u2502")} ${O.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as ef}from"commander";import fe from"chalk";import{existsSync as of,mkdirSync as tf,writeFileSync as nf}from"fs";import{resolve as Rd,join as Nd,dirname as sf}from"path";var Xu=`# AgentX destructive-action guardrails \u2014 global policy
234
+ `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${O.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${O.dim("\u2502")} ${O.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as tf}from"commander";import fe from"chalk";import{existsSync as nf,mkdirSync as sf,writeFileSync as rf}from"fs";import{resolve as Rd,join as Nd,dirname as af}from"path";var Zu=`# AgentX destructive-action guardrails \u2014 global policy
235
235
  #
236
236
  # This file + environments/*.yaml + agents/<id>.yaml are deep-merged
237
237
  # (most specific wins). The built-in catalog (prisma / rm -rf / docker /
@@ -257,7 +257,7 @@ defaults:
257
257
  # action: escalate
258
258
  # severity: high
259
259
  rules: []
260
- `,Qu=`# Production protected resources.
260
+ `,ef=`# Production protected resources.
261
261
  #
262
262
  # The catalog rules reference \`target_in: production\`, so DECLARING this set is
263
263
  # what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
@@ -279,7 +279,7 @@ protected_resources:
279
279
 
280
280
  # Production-only rules beyond the catalog:
281
281
  rules: []
282
- `,Zu=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
282
+ `,of=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
283
283
  # this agent (the filename names it). coder agents never touch production.
284
284
  rules:
285
285
  - id: coder-no-prod
@@ -288,7 +288,7 @@ rules:
288
288
  action: deny
289
289
  severity: critical
290
290
  message: "coder-agent is not permitted to run commands against production."
291
- `,Id=[{relPath:"policy.yaml",content:Xu},{relPath:"environments/production.yaml",content:Qu},{relPath:"agents/coder-agent.yaml",content:Zu}];var Go=new ef().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function kr(e){return e==="deny"?fe.red:e==="escalate"||e==="ask"?fe.yellow:e==="warn"?fe.magenta:fe.green}function Us(e){return e.root?Rd(e.root):il()}Go.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await sl({root:Us(e),agentId:e.agent,env:e.env}),process.exit(0)});Go.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=Us(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=nl({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}rf(s,i,r)});function rf(e,o,t){let n=kr(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":fe.dim(" (no rule matched)")}`),console.log(` enforced as ${kr(e.effectiveAction)(e.effectiveAction)} ${fe.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${fe.cyan(e.ruleId)}${e.severity?fe.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${fe.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${fe.dim(`evaluated in ${t}ms`)}`),console.log()}Go.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Ma({root:Us(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(fe.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=kr(t.verdict),i=t.effective_action!==t.verdict?fe.dim(`->${t.effective_action}`):"";console.log(` ${fe.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${fe.cyan((t.agent_id??"?").padEnd(16))} ${fe.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(fe.dim(` target: ${t.resolved_target}`))}});Go.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=Nd(Rd(e.root),ol),t=0;for(let n of Id){let s=Nd(o,n.relPath);if(of(s)&&!e.force){console.log(fe.dim(` skip (exists) ${n.relPath}`));continue}tf(sf(s),{recursive:!0}),nf(s,n.content),console.log(fe.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${fe.cyan(o)}`),console.log(fe.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(fe.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Go.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(fe.green(` daemon reloaded (${e.url})`)):console.log(fe.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(fe.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Go.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=tl(Us(e),e.agent);console.log(JSON.stringify(o,null,2))});$n();import{Command as af}from"commander";import{execFile as cf}from"child_process";import{promisify as lf}from"util";import{existsSync as df}from"fs";import lo from"chalk";wn();var Pn="ui-element";function Fs(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:Dn(t.tried,80),screenChanged:t.changed,note:t.note?Dn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:_d(t.role),label:Dn(t.label,120),value:t.value?Dn(t.value,80):null,enabled:t.enabled}))}}function Ws(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${_d(t.role)}: ${Dn(n,80)}`}return{target:kt(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:Eo("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function Js(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function _d(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Dn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var Dd=lf(cf),Pd=new af().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{df(Pe)||(console.log(lo.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await xs({max:Number(o.max)||40})}catch(d){console.log(lo.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(lo.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=En(t,n[0].id);d&&(console.log(lo.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+lo.bold(n[0].label)),await Dd(Pe,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await yo(Pn,Fs({request:e,app:t.app,window:t.window,candidates:n}),Ws(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(lo.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Pn}.mode`)),process.exit(1));let i=Js(s.answers,n),r=En(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(lo.yellow(` nothing on screen matches "${e}"`)+lo.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${lo.green("\u2192")} ${lo.bold(g)} `+lo.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Dd(Pe,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Nf}from"commander";import ze from"chalk";import{readFileSync as Md}from"fs";import{homedir as gf}from"os";import{join as mf}from"path";var Ld=12e5,pf="https://openrouter.ai/api/v1/chat/completions",uf=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function ff(e={kind:"window"},o=Ld,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return Rt(e,{},n);try{return await Rt(e,{untilStable:!0},n)}catch(s){if(s instanceof Al)return Rt(e,{},n);throw s}}var hf=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
291
+ `,Id=[{relPath:"policy.yaml",content:Zu},{relPath:"environments/production.yaml",content:ef},{relPath:"agents/coder-agent.yaml",content:of}];var Go=new tf().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function kr(e){return e==="deny"?fe.red:e==="escalate"||e==="ask"?fe.yellow:e==="warn"?fe.magenta:fe.green}function Us(e){return e.root?Rd(e.root):rl()}Go.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await il({root:Us(e),agentId:e.agent,env:e.env}),process.exit(0)});Go.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=Us(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=sl({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}cf(s,i,r)});function cf(e,o,t){let n=kr(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":fe.dim(" (no rule matched)")}`),console.log(` enforced as ${kr(e.effectiveAction)(e.effectiveAction)} ${fe.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${fe.cyan(e.ruleId)}${e.severity?fe.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${fe.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${fe.dim(`evaluated in ${t}ms`)}`),console.log()}Go.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Ma({root:Us(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(fe.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=kr(t.verdict),i=t.effective_action!==t.verdict?fe.dim(`->${t.effective_action}`):"";console.log(` ${fe.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${fe.cyan((t.agent_id??"?").padEnd(16))} ${fe.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(fe.dim(` target: ${t.resolved_target}`))}});Go.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=Nd(Rd(e.root),tl),t=0;for(let n of Id){let s=Nd(o,n.relPath);if(nf(s)&&!e.force){console.log(fe.dim(` skip (exists) ${n.relPath}`));continue}sf(af(s),{recursive:!0}),rf(s,n.content),console.log(fe.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${fe.cyan(o)}`),console.log(fe.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(fe.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Go.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(fe.green(` daemon reloaded (${e.url})`)):console.log(fe.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(fe.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Go.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=nl(Us(e),e.agent);console.log(JSON.stringify(o,null,2))});$n();import{Command as lf}from"commander";import{execFile as df}from"child_process";import{promisify as gf}from"util";import{existsSync as mf}from"fs";import lo from"chalk";wn();var Pn="ui-element";function Fs(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:Dn(t.tried,80),screenChanged:t.changed,note:t.note?Dn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:_d(t.role),label:Dn(t.label,120),value:t.value?Dn(t.value,80):null,enabled:t.enabled}))}}function Ws(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${_d(t.role)}: ${Dn(n,80)}`}return{target:kt(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:Eo("The screen actually contains a control matching the request.",{true:"One of the listed controls is plainly the thing the request names, or is the obvious way to perform it.",false:"Nothing listed corresponds to the request \u2014 the right control is on another screen, behind a menu, not yet visible, or this application simply cannot do what was asked."})}}function Js(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function _d(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Dn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var Dd=gf(df),Pd=new lf().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{mf(Pe)||(console.log(lo.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await xs({max:Number(o.max)||40})}catch(d){console.log(lo.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(lo.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=En(t,n[0].id);d&&(console.log(lo.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+lo.bold(n[0].label)),await Dd(Pe,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await yo(Pn,Fs({request:e,app:t.app,window:t.window,candidates:n}),Ws(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(lo.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Pn}.mode`)),process.exit(1));let i=Js(s.answers,n),r=En(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(lo.yellow(` nothing on screen matches "${e}"`)+lo.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${lo.green("\u2192")} ${lo.bold(g)} `+lo.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Dd(Pe,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as _f}from"commander";import ze from"chalk";import{readFileSync as Md}from"fs";import{homedir as pf}from"os";import{join as uf}from"path";var Ld=12e5,ff="https://openrouter.ai/api/v1/chat/completions",hf=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function yf(e={kind:"window"},o=Ld,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return Rt(e,{},n);try{return await Rt(e,{untilStable:!0},n)}catch(s){if(s instanceof Tl)return Rt(e,{},n);throw s}}var wf=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
292
292
 
293
293
  Report only what is visible in this image.
294
294
 
@@ -296,13 +296,13 @@ The failure that matters: an application that performs an action is on screen, a
296
296
 
297
297
  State indicators are usually small and specific: a coloured dot, a pill or badge in the menu bar, an elapsed timer, a filled or highlighted toggle, a progress bar, a changed icon. If the question turns on such an indicator, say whether you can see it and what it looks like.
298
298
 
299
- Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function yf(e,o,t,n){let s=$f();if(!s)throw new Error("no OPENROUTER_API_KEY \u2014 looking at the screen needs a vision model (set it, or ~/.agentx/openrouter-key.txt)");let i=Md(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
299
+ Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function $f(e,o,t,n){let s=kf();if(!s)throw new Error("no OPENROUTER_API_KEY \u2014 looking at the screen needs a vision model (set it, or ~/.agentx/openrouter-key.txt)");let i=Md(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
300
300
 
301
- The image is the region ${wf(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:hf,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),l;try{l=await fetch(pf,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${p.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(d.function.arguments),f=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Bs(e,o={}){let t=Date.now(),n=await ff(o.region??{kind:"window"},o.maxPixels??Ld,{settle:o.settle,screen:o.screen}),s=await yf(e,n,o.model??uf,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function wf(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var Mn;function $f(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Mn!==void 0)return Mn??void 0;try{let e=Md(mf(gf(),".agentx","openrouter-key.txt"),"utf-8").trim();Mn=e.length>0?e:null}catch{Mn=null}return Mn??void 0}import{execFile as bf}from"child_process";import{promisify as kf}from"util";var vf=kf(bf),xf=["screencapture"],Sf=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Ud(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Ef()),t}async function Ef(){let e=await qd(xf);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await qd(Sf);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function qd(e){let o=[];for(let t of e)try{let{stdout:n}=await vf("pgrep",["-x",t]),s=n.trim().split(`
302
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}$n();wn();var Fd="screen-state",Wd={observable:Eo("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:Eo("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function Jd(e){return{claim:e.claim,capturedRegion:e.region,whatWasSeen:e.observation,decidingDetail:e.evidence||null,visionModelReading:e.reading,...e.treeNote?{accessibilityTree:e.treeNote}:{},...e.probes?.length?{systemChecks:e.probes}:{}}}function Bd(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Af=.6,Tf=.7,jf=.3;async function Ln(e,o={}){let[t,n]=await Promise.all([Bs(e,o),Ud(e).catch(()=>[])]),s=o.observableFloor??Af,i=await yo(Fd,Jd({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:If(t),treeNote:o.treeNote,probes:n}),Wd,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:Cf(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=Bd(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${Hs(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Tf?"confirmed":a<=jf?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Of(c,a,t),sighting:t,probes:n}}function Of(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Hs(o)}). ${n}`:e==="refuted"?`Not true (${Hs(1-o)} it is false). ${n}`:`Inconclusive (${Hs(o)}, between the thresholds). ${n}`}function Cf(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function If(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var Hs=e=>`${Math.round(e*100)}%`;var Hd=new Nf().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--settle","wait for the region to stop moving before capturing it").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(ze.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Ln(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?wo():void 0});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?ze.green("\u2713"):s.outcome==="refuted"?ze.red("\u2717"):ze.yellow("?");console.log(` ${i} ${ze.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(ze.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(ze.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await Bs(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?wo():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${ze.bold(n.observation)}`),n.evidence&&console.log(ze.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Rf(n.reading)}`),console.log(ze.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(ze.red(` ${n?.message??n}`)),process.exit(1)}});function Rf(e){return e==="yes"?ze.green(e):e==="no"?ze.red(e):ze.yellow(e)}import{Command as _f}from"commander";import go from"chalk";import{spawn as Df}from"child_process";function zo(e){console.log(go.red(` ${e}`)),process.exit(1)}function Gd(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?go.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(go.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function Pf(e){return new Promise(o=>{let t=Df(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var qn=new _f("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");qn.command("capture").description("capture a region, optionally waiting for it to change or settle, or around a command").argument("[command...]","run this after arming; capture what it changes (put it after --)").option("--region <name|x,y,w,h>","window, screen, menubar, notifications, a name from screen.regions, or x,y,w,h","window").option("--until-changed","wait for the region to change first").option("--until-stable","wait for the region to stop changing").option("--max-pixels <n>","pixel budget for this capture (default screen.maxPixels)").option("--out <path>","where to write the PNG").option("-c, --config <path>","agentx.json to read screen settings from").option("--json","print the result as JSON").action(async(e,o)=>{let t=wo(o.config),n;try{n=Ss(o.region,t)}catch(r){zo(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&zo("--max-pixels must be a whole number above 0");let i={settings:t,maxPixels:s};try{if(e.length){let r=o.untilStable||!o.untilChanged,{result:a,shot:c,error:l}=await Es(()=>Pf(e),n,{out:o.out,untilStable:r},i);c||(console.log(go.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),Gd(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}Gd(await Rt(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){zo(r?.message??String(r))}});qn.command("recent").description("frames from the daemon's in-memory screen buffer (screen.buffer must be on)").option("--seconds <n>","how far back (default screen.buffer.seconds)").option("--url <url>","daemon URL",process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${nt()}`).option("--json","print the result as JSON").action(async e=>{let o=process.env.MESH_TOKEN,t=e.seconds?`?seconds=${encodeURIComponent(e.seconds)}`:"";try{let n=await fetch(`${String(e.url).replace(/\/$/,"")}/screen/recent${t}`,{headers:o?{Authorization:`Bearer ${o}`}:{},signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));if(n.ok||zo(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(go.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${go.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){zo(`could not reach the daemon: ${n?.message??n}`)}});qn.command("config").description("show or change screen capture settings (agentx.json `screen`)").option("--max-pixels <n>","pixel budget for a captured frame").option("--timeout <ms>","longest a capture waits").option("--interval <ms>","time between samples while waiting").option("--threshold <0-1>","difference that counts as a change").option("--stable-ms <ms>","how long a region must hold still to be stable").option("--region <name=x,y,w,h>","add or change a named region",(e,o)=>[...o,e],[]).option("--remove-region <name>","remove a named region",(e,o)=>[...o,e],[]).option("--buffer <state>","on | off: keep recent frames in memory").option("--buffer-seconds <n>","how many seconds the buffer keeps").option("--buffer-fps <n>","samples per second").option("--buffer-region <name|x,y,w,h>","region the buffer watches").option("--buffer-max-pixels <n>","pixel budget per buffered frame").option("-c, --config <path>","agentx.json to read and change (default: ./agentx.json)").action(e=>{let o={};e.maxPixels!==void 0&&(o.maxPixels=e.maxPixels),e.timeout!==void 0&&(o.timeoutMs=e.timeout),e.interval!==void 0&&(o.intervalMs=e.interval),e.threshold!==void 0&&(o.changeThreshold=e.threshold),e.stableMs!==void 0&&(o.stableMs=e.stableMs);let t={};for(let s of e.region){let i=s.indexOf("=");i<1&&zo(`--region wants name=x,y,w,h, got "${s}"`),t[s.slice(0,i)]=s.slice(i+1)}for(let s of e.removeRegion)t[s]=null;Object.keys(t).length&&(o.regions=t);let n={};if(e.buffer!==void 0){let s=String(e.buffer).toLowerCase();["on","off"].includes(s)||zo("--buffer must be on|off"),n.enabled=s==="on"}if(e.bufferSeconds!==void 0&&(n.seconds=e.bufferSeconds),e.bufferFps!==void 0&&(n.fps=e.bufferFps),e.bufferRegion!==void 0&&(n.region=e.bufferRegion),e.bufferMaxPixels!==void 0&&(n.maxPixels=e.bufferMaxPixels),Object.keys(n).length&&(o.buffer=n),Object.keys(o).length===0){let s=wo(e.config);console.log(`
301
+ The image is the region ${bf(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:wf,tools:[{type:"function",function:{name:"report",description:"Report what is visible and how it bears on the question",parameters:{type:"object",properties:{observation:{type:"string",description:"What is visible in the image, factually, in one or two sentences."},evidence:{type:"string",description:"The specific visible detail that decides the question \u2014 where it is and what it looks like. Empty string if no such detail is visible."},reading:{type:"string",enum:["yes","no","unclear"],description:"Answer to the question, or unclear if the pixels do not settle it."}},required:["observation","evidence","reading"]}}}],tool_choice:{type:"function",function:{name:"report"}}},a=new AbortController,c=setTimeout(()=>a.abort(),n),l;try{l=await fetch(ff,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${p.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(d.function.arguments),f=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Bs(e,o={}){let t=Date.now(),n=await yf(o.region??{kind:"window"},o.maxPixels??Ld,{settle:o.settle,screen:o.screen}),s=await $f(e,n,o.model??hf,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function bf(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var Mn;function kf(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Mn!==void 0)return Mn??void 0;try{let e=Md(uf(pf(),".agentx","openrouter-key.txt"),"utf-8").trim();Mn=e.length>0?e:null}catch{Mn=null}return Mn??void 0}import{execFile as vf}from"child_process";import{promisify as xf}from"util";var Sf=xf(vf),Ef=["screencapture"],Af=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Ud(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Tf()),t}async function Tf(){let e=await qd(Ef);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await qd(Af);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function qd(e){let o=[];for(let t of e)try{let{stdout:n}=await Sf("pgrep",["-x",t]),s=n.trim().split(`
302
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}$n();wn();var Fd="screen-state",Wd={observable:Eo("The evidence gathered \u2014 the screenshot and the system checks together \u2014 is enough to settle the claim, either way.",{true:"Something in the evidence decides it. Either the observation names a specific visible detail that bears on the claim and was legible, or a system check directly establishes the claim true or false. A system check alone is sufficient: it does not need the image to agree with it, or the image to have shown anything at all.",false:"Nothing decides it. The deciding detail is not in frame, too small or blurred, or covered; the observation only describes context \u2014 which application is open, what the screen generally shows \u2014 without the detail itself; and no system check settles it either. Absence of evidence in a capture that could not have shown the evidence is not evidence of absence. This is also false when a check says the question is not answerable from a screenshot and the observation nonetheless claims to have seen it: that is a guess, however specific it sounds."}),holds:Eo("The claim is true of the screen right now.",{true:"The visible evidence shows the claimed state is in effect: the indicator is present, the text is there, the element is visible and unobstructed, the action has plainly already happened.",false:"The visible evidence shows the claimed state is NOT in effect. An application being open, capable of the action, or offering it, is not the action having happened \u2014 a recorder on screen is not a recording, an unpressed button is not a pressed one, an offered dialog is not a chosen one. A system check that directly contradicts the observation outweighs it: the checks are deterministic readings of the machine, the observation is a model's reading of an image."})};function Jd(e){return{claim:e.claim,capturedRegion:e.region,whatWasSeen:e.observation,decidingDetail:e.evidence||null,visionModelReading:e.reading,...e.treeNote?{accessibilityTree:e.treeNote}:{},...e.probes?.length?{systemChecks:e.probes}:{}}}function Bd(e){return{observable:e.observable.noul,holds:e.holds.noul}}var jf=.6,Of=.7,Cf=.3;async function Ln(e,o={}){let[t,n]=await Promise.all([Bs(e,o),Ud(e).catch(()=>[])]),s=o.observableFloor??jf,i=await yo(Fd,Jd({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Rf(t),treeNote:o.treeNote,probes:n}),Wd,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:Nf(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=Bd(i.answers);if(r<s)return{claim:e,outcome:"unknown",ok:!1,observable:r,holds:a,calibrated:!0,reason:`Could not tell from the screenshot or the system checks (${Hs(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Of?"confirmed":a<=Cf?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:If(c,a,t),sighting:t,probes:n}}function If(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Hs(o)}). ${n}`:e==="refuted"?`Not true (${Hs(1-o)} it is false). ${n}`:`Inconclusive (${Hs(o)}, between the thresholds). ${n}`}function Nf(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function Rf(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var Hs=e=>`${Math.round(e*100)}%`;var Hd=new _f().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--settle","wait for the region to stop moving before capturing it").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(ze.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Ln(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?wo():void 0});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?ze.green("\u2713"):s.outcome==="refuted"?ze.red("\u2717"):ze.yellow("?");console.log(` ${i} ${ze.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(ze.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(ze.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await Bs(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?wo():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${ze.bold(n.observation)}`),n.evidence&&console.log(ze.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Df(n.reading)}`),console.log(ze.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(ze.red(` ${n?.message??n}`)),process.exit(1)}});function Df(e){return e==="yes"?ze.green(e):e==="no"?ze.red(e):ze.yellow(e)}import{Command as Pf}from"commander";import go from"chalk";import{spawn as Mf}from"child_process";function zo(e){console.log(go.red(` ${e}`)),process.exit(1)}function Gd(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?go.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(go.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function Lf(e){return new Promise(o=>{let t=Mf(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var qn=new Pf("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");qn.command("capture").description("capture a region, optionally waiting for it to change or settle, or around a command").argument("[command...]","run this after arming; capture what it changes (put it after --)").option("--region <name|x,y,w,h>","window, screen, menubar, notifications, a name from screen.regions, or x,y,w,h","window").option("--until-changed","wait for the region to change first").option("--until-stable","wait for the region to stop changing").option("--max-pixels <n>","pixel budget for this capture (default screen.maxPixels)").option("--out <path>","where to write the PNG").option("-c, --config <path>","agentx.json to read screen settings from").option("--json","print the result as JSON").action(async(e,o)=>{let t=wo(o.config),n;try{n=Ss(o.region,t)}catch(r){zo(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&zo("--max-pixels must be a whole number above 0");let i={settings:t,maxPixels:s};try{if(e.length){let r=o.untilStable||!o.untilChanged,{result:a,shot:c,error:l}=await Es(()=>Lf(e),n,{out:o.out,untilStable:r},i);c||(console.log(go.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),Gd(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}Gd(await Rt(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){zo(r?.message??String(r))}});qn.command("recent").description("frames from the daemon's in-memory screen buffer (screen.buffer must be on)").option("--seconds <n>","how far back (default screen.buffer.seconds)").option("--url <url>","daemon URL",process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${nt()}`).option("--json","print the result as JSON").action(async e=>{let o=process.env.MESH_TOKEN,t=e.seconds?`?seconds=${encodeURIComponent(e.seconds)}`:"";try{let n=await fetch(`${String(e.url).replace(/\/$/,"")}/screen/recent${t}`,{headers:o?{Authorization:`Bearer ${o}`}:{},signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));if(n.ok||zo(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(go.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${go.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){zo(`could not reach the daemon: ${n?.message??n}`)}});qn.command("config").description("show or change screen capture settings (agentx.json `screen`)").option("--max-pixels <n>","pixel budget for a captured frame").option("--timeout <ms>","longest a capture waits").option("--interval <ms>","time between samples while waiting").option("--threshold <0-1>","difference that counts as a change").option("--stable-ms <ms>","how long a region must hold still to be stable").option("--region <name=x,y,w,h>","add or change a named region",(e,o)=>[...o,e],[]).option("--remove-region <name>","remove a named region",(e,o)=>[...o,e],[]).option("--buffer <state>","on | off: keep recent frames in memory").option("--buffer-seconds <n>","how many seconds the buffer keeps").option("--buffer-fps <n>","samples per second").option("--buffer-region <name|x,y,w,h>","region the buffer watches").option("--buffer-max-pixels <n>","pixel budget per buffered frame").option("-c, --config <path>","agentx.json to read and change (default: ./agentx.json)").action(e=>{let o={};e.maxPixels!==void 0&&(o.maxPixels=e.maxPixels),e.timeout!==void 0&&(o.timeoutMs=e.timeout),e.interval!==void 0&&(o.intervalMs=e.interval),e.threshold!==void 0&&(o.changeThreshold=e.threshold),e.stableMs!==void 0&&(o.stableMs=e.stableMs);let t={};for(let s of e.region){let i=s.indexOf("=");i<1&&zo(`--region wants name=x,y,w,h, got "${s}"`),t[s.slice(0,i)]=s.slice(i+1)}for(let s of e.removeRegion)t[s]=null;Object.keys(t).length&&(o.regions=t);let n={};if(e.buffer!==void 0){let s=String(e.buffer).toLowerCase();["on","off"].includes(s)||zo("--buffer must be on|off"),n.enabled=s==="on"}if(e.bufferSeconds!==void 0&&(n.seconds=e.bufferSeconds),e.bufferFps!==void 0&&(n.fps=e.bufferFps),e.bufferRegion!==void 0&&(n.region=e.bufferRegion),e.bufferMaxPixels!==void 0&&(n.maxPixels=e.bufferMaxPixels),Object.keys(n).length&&(o.buffer=n),Object.keys(o).length===0){let s=wo(e.config);console.log(`
303
303
  maxPixels ${s.maxPixels}`),console.log(` wait timeout ${s.timeoutMs}ms \xB7 every ${s.intervalMs}ms \xB7 change > ${s.changeThreshold} \xB7 stable ${s.stableMs}ms`);let i=Object.entries(s.regions).map(([a,c])=>`${a}=${c.x},${c.y},${c.width},${c.height}`);console.log(` regions ${i.length?i.join(" "):go.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":go.dim("off")} ${go.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
304
- `);return}try{let{summary:s,backupPath:i}=oo(r=>{let a=El(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(go.green(`
305
- \u2713 ${s}`)),i&&console.log(go.dim(` Backup: ${i}`)),console.log()}catch(s){zo(s?.message??String(s))}});$n();import{Command as qf}from"commander";import{execFile as eg}from"child_process";import{promisify as Uf}from"util";import{existsSync as Ff,readFileSync as Wf,writeFileSync as og,mkdirSync as Jf}from"fs";import{homedir as Bf}from"os";import{join as Hf,dirname as Gf}from"path";import qe from"chalk";wn();var vr="paste-transform";function zd(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Yd(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:Eo("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:kt(o,"What shape should this paste arrive in?")}}function Vd(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var Mf=new Set(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","gclid","fbclid","mc_cid","mc_eid","igshid","ref_src","ref_url","s","si","spm","scid","twclid","yclid","_hsenc","_hsmi"]),Lf=e=>/^https?:\/\/\S+$/i.test(e.trim()),xr=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
304
+ `);return}try{let{summary:s,backupPath:i}=oo(r=>{let a=Al(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(go.green(`
305
+ \u2713 ${s}`)),i&&console.log(go.dim(` Backup: ${i}`)),console.log()}catch(s){zo(s?.message??String(s))}});$n();import{Command as Ff}from"commander";import{execFile as eg}from"child_process";import{promisify as Wf}from"util";import{existsSync as Jf,readFileSync as Bf,writeFileSync as og,mkdirSync as Hf}from"fs";import{homedir as Gf}from"os";import{join as zf,dirname as Yf}from"path";import qe from"chalk";wn();var vr="paste-transform";function zd(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Yd(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:Eo("The text is in the wrong shape for where it is being pasted, and a mechanical reshaping would fix it.",{true:"The destination renders or stores formatted text, and the clipboard arrived in a shape that will not come out right: lines hard-wrapped mid-sentence going into prose, a link carrying campaign or tracking parameters, JSON collapsed onto one line, separate items going somewhere that renders a list, text padded with stray whitespace from a web page. The fix is mechanical and is what the person would have done by hand after pasting.",false:"The text is already in the right shape for this destination, OR its exact bytes carry meaning that reformatting would destroy \u2014 a credential, a command, a path, code, an identifier, a search query \u2014 OR the destination is a terminal, a password field, a URL bar or a code editor, where introduced formatting would corrupt what is pasted."}),shape:kt(o,"What shape should this paste arrive in?")}}function Vd(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var qf=new Set(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id","gclid","fbclid","mc_cid","mc_eid","igshid","ref_src","ref_url","s","si","spm","scid","twclid","yclid","_hsenc","_hsmi"]),Uf=e=>/^https?:\/\/\S+$/i.test(e.trim()),xr=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
306
306
  `);if(o.length<3)return null;let t=0;for(let n=0;n<o.length-1;n++){let s=o[n].trim(),i=o[n+1].trim();s.length>40&&i.length>0&&!/[.!?:;]$/.test(s)&&t++}return t<2?null:e.split(/\n\s*\n/).map(n=>n.split(`
307
307
  `).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
308
308
 
@@ -310,29 +310,29 @@ The image is the region ${wf(o)}.`},{type:"image_url",image_url:{url:`data:image
310
310
  `).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
311
311
  `)}},{id:"quote",criterion:"Prefix every line with a markdown blockquote marker. For quoting someone else's words into a document, an issue or a message.",label:"blockquote",apply:e=>{let o=e.split(`
312
312
  `);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
313
- `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!Lf(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Mf.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
313
+ `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!Uf(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])qf.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
314
314
  `)||o.length>90||o.length<3)return null;let t=o.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t!==o?t:null}},{id:"collapseSpace",criterion:"Collapse runs of whitespace and trim the ends, leaving one clean line. For text copied out of a web page that arrived padded with stray spaces, tabs and newlines.",label:"tidy whitespace",apply:e=>{let o=e.replace(/[ \t]+/g," ").replace(/\s*\n\s*/g,`
315
315
  `).trim();return o===e?null:o}}];function Kd(e){let o=[];for(let t of xr){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Xd(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
316
316
  \u2026[${e.length-o} more characters]\u2026
317
317
  ${e.slice(-n)}`}function Qd(e){let o=e.trim();return o.includes(`
318
- `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var Sr=Uf(eg),tg=new qf().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${xr.map(e=>e.id).join(", ")})`).option("--min <p>","minimum P(worth changing) before transforming","0.45").option("--undo","restore the clipboard as it was before the last apply").option("--json","emit the decision as JSON").action(async e=>{if(e.undo){let c=Yf();c===null&&(console.log(qe.yellow(" nothing to undo")),process.exit(2)),await sg(c),console.log(` ${qe.green("\u2192")} clipboard restored`);return}let o=await Vf();if(o||(console.log(qe.yellow(" clipboard is empty")),process.exit(2)),Qd(o)){ng(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Kd(o),n=await Kf();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(qe.red(` "${e.as}" does not apply to this clipboard`)),console.log(qe.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Jt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Jt(e,"asIs",o,o,"nothing else applies",0);return}let s=await yo(vr,zd({preview:Xd(o),length:o.length,lineCount:o.split(`
319
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Yd(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Jt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${vr}.mode`,0);return}let i=Vd(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Jt(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await Jt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Jt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Jt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(zf(n),await sg(t)),ng(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Sr(Pe,["key","--name","v","--mod","command"]).catch(a=>{console.log(qe.red(` could not paste: ${a?.message??a}`))})}function ng(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${qe.dim("\u2192")} ${qe.bold("unchanged")} ${qe.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${qe.green("\u2192")} ${qe.bold(o.applied)} ${qe.dim(`\xB7 ${o.reason}`)}`),console.log(qe.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(qe.dim(Zd(o.original))),console.log(qe.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Zd(o.result)),!e.apply&&!e.paste&&console.log(qe.dim(`
318
+ `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var Sr=Wf(eg),tg=new Ff().name("paste").description("reshape the clipboard to fit where it is being pasted").option("--apply","write the result back to the clipboard").option("--paste","apply, then press cmd-V into the focused control").option("--as <id>",`force a transform (${xr.map(e=>e.id).join(", ")})`).option("--min <p>","minimum P(worth changing) before transforming","0.45").option("--undo","restore the clipboard as it was before the last apply").option("--json","emit the decision as JSON").action(async e=>{if(e.undo){let c=Kf();c===null&&(console.log(qe.yellow(" nothing to undo")),process.exit(2)),await sg(c),console.log(` ${qe.green("\u2192")} clipboard restored`);return}let o=await Xf();if(o||(console.log(qe.yellow(" clipboard is empty")),process.exit(2)),Qd(o)){ng(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Kd(o),n=await Qf();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(qe.red(` "${e.as}" does not apply to this clipboard`)),console.log(qe.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Jt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Jt(e,"asIs",o,o,"nothing else applies",0);return}let s=await yo(vr,zd({preview:Xd(o),length:o.length,lineCount:o.split(`
319
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Yd(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Jt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${vr}.mode`,0);return}let i=Vd(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Jt(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await Jt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Jt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Jt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(Vf(n),await sg(t)),ng(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Sr(Pe,["key","--name","v","--mod","command"]).catch(a=>{console.log(qe.red(` could not paste: ${a?.message??a}`))})}function ng(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${qe.dim("\u2192")} ${qe.bold("unchanged")} ${qe.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${qe.green("\u2192")} ${qe.bold(o.applied)} ${qe.dim(`\xB7 ${o.reason}`)}`),console.log(qe.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(qe.dim(Zd(o.original))),console.log(qe.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Zd(o.result)),!e.apply&&!e.paste&&console.log(qe.dim(`
320
320
  (dry run \u2014 pass --apply to write it back)`))}var Zd=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
321
321
  `).map(t=>` ${t}`).join(`
322
- `),Gs=Hf(Bf(),".agentx","paste-undo.txt");function zf(e){try{Jf(Gf(Gs),{recursive:!0}),og(Gs,e,{mode:384})}catch{}}function Yf(){try{let e=Wf(Gs,"utf-8");return og(Gs,"",{mode:384}),e.length?e:null}catch{return null}}async function Vf(){let{stdout:e}=await Sr("pbpaste",[],{maxBuffer:16777216});return e}async function sg(e){await new Promise((o,t)=>{eg("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Kf(){if(!Ff(Pe))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Sr(Pe,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Xf(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Xf(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as Qf}from"commander";import Be from"chalk";oe();function ig(e,o,t={}){let n={shot:null,error:"no banner was shown (held for Focus, or the banner is off)"};return{alert:async(s,i)=>{let{shot:r,error:a}=await Es(()=>e(s,i),o,{},t);n=r?.timedOut&&!r.changed?{shot:r,error:"the banner region did not change \u2014 Do Not Disturb, or notifications not allowed"}:{shot:r,error:a}},proof:()=>n}}var Zf=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function eh(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
323
- ${n}`:n,a=await fetch(`${Zf}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function oh(e){let o;try{o=j(e.config)}catch{o=void 0}let t=fs(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??ws(o);return{alert:Cc(t),banner:t.banner,channel:n}}var rg=new Qf().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","AgentX").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel (default: notifications.channel, else push when it is on, else ntfy)").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").option("--proof","capture the banner as it shows and print the frame's path").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new bc,n=oc(),{alert:s,banner:i,channel:r}=oh(o),a=s,c;if(o.proof&&!i)c=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(o.proof){let g=wo(o.config),d=ig(s,Ss("notifications",g),{settings:g});a=d.alert,c=d.proof}if(o.status){let g=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:g},null,2));return}console.log(` ${n.active?Be.yellow("\u25D0"):Be.green("\u25CB")} ${tc(n)} ${Be.dim(`\xB7 ${n.reason}`)}`),console.log(` ${g.length} held`);for(let d of g.slice(0,8)){let u=new Date(d.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Be.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=eh(r,o.chatId);if(o.flush){let g=await Rc(l,{queue:t,alert:s});console.log(g?Be.green(` delivered ${g} held notification(s)`):Be.dim(" nothing was held"));return}e?.trim()||(console.log(Be.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await Nc({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:r,chatId:o.chatId},l,{queue:t,alert:a,focus:n}),d=c?.();if(o.json){console.log(JSON.stringify(d?{...g,proof:d}:g,null,2));return}let u=g.delivered?Be.green("\u2192"):Be.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Be.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Be.yellow("?"):Be.green("\u2713")} banner: ${d.shot.path}${Be.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Be.yellow(` ${d.error}`))}catch(g){console.log(Be.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});import{Command as Bt}from"commander";import mo from"chalk";var ag=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function po(e,o,t,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${ag}${o}`,{method:e,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...n},body:t===void 0?void 0:JSON.stringify(t)}).catch(a=>{throw new Error(`daemon not reachable at ${ag}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function th(e,o,t){e.calls=e.calls??{};let n=Array.isArray(e.calls.allow)?e.calls.allow:[],s=n.includes(o);return t===s?`${o} is ${t?"already":"not"} in calls.allow`:(e.calls.allow=t?[...n,o]:n.filter(i=>i!==o),t?`${o} may now call you`:`${o} may no longer call you`)}function Ar(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?mo.yellow("missed"):e.status==="ringing"?mo.green("ringing"):mo.dim(e.status),n=e.note?mo.dim(` (${e.note})`):"";return` ${mo.dim(e.id)} ${o} ${e.agentId} ${t}${n}
322
+ `),Gs=zf(Gf(),".agentx","paste-undo.txt");function Vf(e){try{Hf(Yf(Gs),{recursive:!0}),og(Gs,e,{mode:384})}catch{}}function Kf(){try{let e=Bf(Gs,"utf-8");return og(Gs,"",{mode:384}),e.length?e:null}catch{return null}}async function Xf(){let{stdout:e}=await Sr("pbpaste",[],{maxBuffer:16777216});return e}async function sg(e){await new Promise((o,t)=>{eg("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Qf(){if(!Jf(Pe))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Sr(Pe,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Zf(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Zf(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as eh}from"commander";import Be from"chalk";oe();function ig(e,o,t={}){let n={shot:null,error:"no banner was shown (held for Focus, or the banner is off)"};return{alert:async(s,i)=>{let{shot:r,error:a}=await Es(()=>e(s,i),o,{},t);n=r?.timedOut&&!r.changed?{shot:r,error:"the banner region did not change \u2014 Do Not Disturb, or notifications not allowed"}:{shot:r,error:a}},proof:()=>n}}var oh=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function th(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
323
+ ${n}`:n,a=await fetch(`${oh}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function nh(e){let o;try{o=T(e.config)}catch{o=void 0}let t=fs(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??ws(o);return{alert:Ic(t),banner:t.banner,channel:n}}var rg=new eh().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","AgentX").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel (default: notifications.channel, else push when it is on, else ntfy)").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").option("--proof","capture the banner as it shows and print the frame's path").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new kc,n=tc(),{alert:s,banner:i,channel:r}=nh(o),a=s,c;if(o.proof&&!i)c=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(o.proof){let g=wo(o.config),d=ig(s,Ss("notifications",g),{settings:g});a=d.alert,c=d.proof}if(o.status){let g=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:g},null,2));return}console.log(` ${n.active?Be.yellow("\u25D0"):Be.green("\u25CB")} ${nc(n)} ${Be.dim(`\xB7 ${n.reason}`)}`),console.log(` ${g.length} held`);for(let d of g.slice(0,8)){let u=new Date(d.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Be.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=th(r,o.chatId);if(o.flush){let g=await _c(l,{queue:t,alert:s});console.log(g?Be.green(` delivered ${g} held notification(s)`):Be.dim(" nothing was held"));return}e?.trim()||(console.log(Be.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await Rc({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:r,chatId:o.chatId},l,{queue:t,alert:a,focus:n}),d=c?.();if(o.json){console.log(JSON.stringify(d?{...g,proof:d}:g,null,2));return}let u=g.delivered?Be.green("\u2192"):Be.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Be.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Be.yellow("?"):Be.green("\u2713")} banner: ${d.shot.path}${Be.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Be.yellow(` ${d.error}`))}catch(g){console.log(Be.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});import{Command as Bt}from"commander";import mo from"chalk";var ag=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function po(e,o,t,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${ag}${o}`,{method:e,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...n},body:t===void 0?void 0:JSON.stringify(t)}).catch(a=>{throw new Error(`daemon not reachable at ${ag}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function sh(e,o,t){e.calls=e.calls??{};let n=Array.isArray(e.calls.allow)?e.calls.allow:[],s=n.includes(o);return t===s?`${o} is ${t?"already":"not"} in calls.allow`:(e.calls.allow=t?[...n,o]:n.filter(i=>i!==o),t?`${o} may now call you`:`${o} may no longer call you`)}function Ar(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?mo.yellow("missed"):e.status==="ringing"?mo.green("ringing"):mo.dim(e.status),n=e.note?mo.dim(` (${e.note})`):"";return` ${mo.dim(e.id)} ${o} ${e.agentId} ${t}${n}
324
324
  ${e.reason}${e.summary?mo.dim(`
325
- summary: ${e.summary}`):""}`}async function Un(e){try{await e()}catch(o){console.log(mo.red(` ${o?.message??o}`)),process.exit(1)}}var nh=new Bt("request").description("ask the owner for a live voice call (rings AgentX Voice); runs inside an agent's turn").requiredOption("--reason <text>","why, in one line: said aloud when they answer").option("--urgent","ring even during Focus").option("--json","print the call as JSON").action(e=>Un(async()=>{let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let t=await po("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},kn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang==="widget"?"ringing on AgentX Voice":t.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${t.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${t.rang?mo.green("\u260E"):mo.yellow("\u23F8")} ${t.call.id} ${n}`)})),sh=new Bt("list").description("recent calls, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed, later (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Un(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await po("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(mo.dim(" no calls"));return}for(let n of t)console.log(Ar(n))}));function Er(e,o){return new Bt(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>Un(async()=>{let{call:n}=await po("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(Ar(n))}))}var ih=new Bt("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>Un(async()=>{let{call:t}=await po("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(Ar(t))}));function cg(e,o){return new Bt(e).description(o?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((t,n)=>Un(()=>{let{summary:s}=oo(i=>th(i,t,o),{configPath:n.config});console.log(mo.green(` ${s}`))}))}var lg=new Bt("call").description("agents ring you for a live voice call").addCommand(nh).addCommand(sh).addCommand(Er("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(Er("decline","decline a ringing call")).addCommand(ih).addCommand(Er("hangup","end an answered call")).addCommand(cg("allow",!0)).addCommand(cg("disallow",!1));import{Command as gt}from"commander";import Ye from"chalk";function dg(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?Ye.yellow("missed"):e.status==="ringing"?Ye.green("asking"):e.status==="answered"?Ye.green("showing"):Ye.dim(e.status),n=e.note?Ye.dim(` (${e.note})`):"";return` ${Ye.dim(e.id)} ${o} ${e.agentId} ${t}${n}
326
- ${e.reason}`}async function Ht(e){try{await e()}catch(o){console.log(Ye.red(` ${o?.message??o}`)),process.exit(1)}}function gg(e){let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error(`no agent: ${e} happens from inside an agent's run, which sets AGENTX_AGENT_ID`);return o}var rh=new gt("ask").description("ask the owner to show you their phone camera; runs inside an agent's turn").requiredOption("--reason <text>","what you want to see, in one line: shown on the phone").option("--urgent","ask even during Focus").option("--json","print the ask as JSON").action(e=>Ht(async()=>{let o=gg("a camera ask"),t=await po("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal",kind:"camera"},kn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang?"the owner's phone was told; when they tap Show, use `agentx camera look` for the newest picture":`not asked now: ${t.call.note??"held"} \u2014 it is listed as missed`;console.log(` ${t.rang?Ye.green("\u{1F4F7}"):Ye.yellow("\u23F8")} ${t.call.id} ${n}`)})),ah=new gt("look").description("the newest picture from the owner's camera, as a PNG path to open; runs inside an agent's turn").option("--json","print the frame as JSON").action(e=>Ht(async()=>{let o=gg("a look"),t=await po("POST","/webrtc/camera/look",{agentId:o},kn());if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(` ${t.frame.path}`),console.log(Ye.dim(` ${t.frame.width}x${t.frame.height}, taken ${new Date(t.frame.takenAt).toLocaleTimeString()} (share ${t.callId})`))})),ch=new gt("list").description("recent camera asks, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Ht(async()=>{let o=new URLSearchParams({limit:String(e.limit),kind:"camera"});e.status&&o.set("status",e.status);let{calls:t}=await po("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(Ye.dim(" no camera asks"));return}for(let n of t)console.log(dg(n))})),lh=new gt("watching").description("agents watching a phone camera right now").option("--json","print as JSON").action(e=>Ht(async()=>{let{active:o}=await po("GET","/webrtc/camera/watch");if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(Ye.dim(" no agent is watching a camera"));return}for(let t of o){let n=Math.max(0,Math.round((t.until-Date.now())/6e4));console.log(` ${Ye.dim(t.callId)} ${t.agentId} ${t.frames} frames, ${t.looks} looks, ${n} min left`)}})),dh=new gt("decline").description("turn down a camera ask").argument("<id>","ask id, from `agentx camera list`").action(e=>Ht(async()=>{let{call:o}=await po("POST",`/calls/${encodeURIComponent(e)}/decline`,{});console.log(dg(o))})),gh=new gt("stop").description("end a live watch (the share id from `agentx camera watching`)").argument("<id>","share id").action(e=>Ht(async()=>{await po("POST",`/webrtc/camera/watch/${encodeURIComponent(e)}/stop`,{}),console.log(Ye.green(` ${e} stopped`))})),mg=new gt("camera").description("agents ask to see through your phone camera").addCommand(rh).addCommand(ah).addCommand(ch).addCommand(lh).addCommand(dh).addCommand(gh);$n();Na();$a();wn();import{Command as mh}from"commander";import{readFileSync as ph}from"fs";var pg=new mh().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?ph(e.file,"utf8"):await uh()}catch(r){mt(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return mt("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return mt(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return mt("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return mt("spec needs at least one entry in `questions`");try{Aa(t.questions)}catch(r){return mt(r?.message??String(r))}let n=t.seat||e.seat;vt(),process.env[_a(n)]="active";let s=null;if(e.record!==!1)try{s=new is({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
327
- `)}Ra({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await yo(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return mt(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function mt(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function uh(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}$n();import{Command as Hh}from"commander";import{execFile as Gh,spawn as jg}from"child_process";import{promisify as zh}from"util";import{existsSync as Yh,statSync as Vh}from"fs";import{join as Og}from"path";import{tmpdir as Kh}from"os";import ne from"chalk";var fh={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},hh={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},yh={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},Tr=[fh,hh,yh];oe();oe();import uo from"chalk";import{execFile as wh}from"child_process";import{promisify as $h}from"util";import{createInterface as bh}from"readline";var ug=$h(wh);function kh(e){e.type==="step"?console.log(`${uo.cyan(` ${e.n}. ${e.action}`)}${e.target?uo.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(uo.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?uo.red(` failed: ${e.error}`):uo.dim(" done it")):e.type==="replanned"?console.log(uo.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(uo.cyan(` you: ${e.text}`)):e.type==="error"?console.log(uo.red(` error: ${e.error}`)):e.type==="end"&&console.log(uo.dim(` \xB7 ended (${e.reason})`))}async function vh(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await ug("open",["-a",e]).catch(()=>{});try{let s=(await Hi()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function fg(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await ug("open",["-a",o.app]),i=await vh(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=ks(n,t.agents,!1),a=t.voice.listener??yl,c=Ct(n,t.agents[n]),l=new bl({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:Hi,presence:new vs(c,Pe,n),speech:new It,model:Nt({system:$l(r.persona,a)}),act:kl});l.on(kh),console.log(uo.bold(`
325
+ summary: ${e.summary}`):""}`}async function Un(e){try{await e()}catch(o){console.log(mo.red(` ${o?.message??o}`)),process.exit(1)}}var ih=new Bt("request").description("ask the owner for a live voice call (rings AgentX Voice); runs inside an agent's turn").requiredOption("--reason <text>","why, in one line: said aloud when they answer").option("--urgent","ring even during Focus").option("--json","print the call as JSON").action(e=>Un(async()=>{let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let t=await po("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},kn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang==="widget"?"ringing on AgentX Voice":t.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${t.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${t.rang?mo.green("\u260E"):mo.yellow("\u23F8")} ${t.call.id} ${n}`)})),rh=new Bt("list").description("recent calls, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed, later (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Un(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await po("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(mo.dim(" no calls"));return}for(let n of t)console.log(Ar(n))}));function Er(e,o){return new Bt(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>Un(async()=>{let{call:n}=await po("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(Ar(n))}))}var ah=new Bt("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>Un(async()=>{let{call:t}=await po("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(Ar(t))}));function cg(e,o){return new Bt(e).description(o?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((t,n)=>Un(()=>{let{summary:s}=oo(i=>sh(i,t,o),{configPath:n.config});console.log(mo.green(` ${s}`))}))}var lg=new Bt("call").description("agents ring you for a live voice call").addCommand(ih).addCommand(rh).addCommand(Er("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(Er("decline","decline a ringing call")).addCommand(ah).addCommand(Er("hangup","end an answered call")).addCommand(cg("allow",!0)).addCommand(cg("disallow",!1));import{Command as gt}from"commander";import Ye from"chalk";function dg(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?Ye.yellow("missed"):e.status==="ringing"?Ye.green("asking"):e.status==="answered"?Ye.green("showing"):Ye.dim(e.status),n=e.note?Ye.dim(` (${e.note})`):"";return` ${Ye.dim(e.id)} ${o} ${e.agentId} ${t}${n}
326
+ ${e.reason}`}async function Ht(e){try{await e()}catch(o){console.log(Ye.red(` ${o?.message??o}`)),process.exit(1)}}function gg(e){let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error(`no agent: ${e} happens from inside an agent's run, which sets AGENTX_AGENT_ID`);return o}var ch=new gt("ask").description("ask the owner to show you their phone camera; runs inside an agent's turn").requiredOption("--reason <text>","what you want to see, in one line: shown on the phone").option("--urgent","ask even during Focus").option("--json","print the ask as JSON").action(e=>Ht(async()=>{let o=gg("a camera ask"),t=await po("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal",kind:"camera"},kn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang?"the owner's phone was told; when they tap Show, use `agentx camera look` for the newest picture":`not asked now: ${t.call.note??"held"} \u2014 it is listed as missed`;console.log(` ${t.rang?Ye.green("\u{1F4F7}"):Ye.yellow("\u23F8")} ${t.call.id} ${n}`)})),lh=new gt("look").description("the newest picture from the owner's camera, as a PNG path to open; runs inside an agent's turn").option("--json","print the frame as JSON").action(e=>Ht(async()=>{let o=gg("a look"),t=await po("POST","/webrtc/camera/look",{agentId:o},kn());if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(` ${t.frame.path}`),console.log(Ye.dim(` ${t.frame.width}x${t.frame.height}, taken ${new Date(t.frame.takenAt).toLocaleTimeString()} (share ${t.callId})`))})),dh=new gt("list").description("recent camera asks, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Ht(async()=>{let o=new URLSearchParams({limit:String(e.limit),kind:"camera"});e.status&&o.set("status",e.status);let{calls:t}=await po("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(Ye.dim(" no camera asks"));return}for(let n of t)console.log(dg(n))})),gh=new gt("watching").description("agents watching a phone camera right now").option("--json","print as JSON").action(e=>Ht(async()=>{let{active:o}=await po("GET","/webrtc/camera/watch");if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(Ye.dim(" no agent is watching a camera"));return}for(let t of o){let n=Math.max(0,Math.round((t.until-Date.now())/6e4));console.log(` ${Ye.dim(t.callId)} ${t.agentId} ${t.frames} frames, ${t.looks} looks, ${n} min left`)}})),mh=new gt("decline").description("turn down a camera ask").argument("<id>","ask id, from `agentx camera list`").action(e=>Ht(async()=>{let{call:o}=await po("POST",`/calls/${encodeURIComponent(e)}/decline`,{});console.log(dg(o))})),ph=new gt("stop").description("end a live watch (the share id from `agentx camera watching`)").argument("<id>","share id").action(e=>Ht(async()=>{await po("POST",`/webrtc/camera/watch/${encodeURIComponent(e)}/stop`,{}),console.log(Ye.green(` ${e} stopped`))})),mg=new gt("camera").description("agents ask to see through your phone camera").addCommand(ch).addCommand(lh).addCommand(dh).addCommand(gh).addCommand(mh).addCommand(ph);$n();Na();$a();wn();import{Command as uh}from"commander";import{readFileSync as fh}from"fs";var pg=new uh().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?fh(e.file,"utf8"):await hh()}catch(r){mt(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return mt("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return mt(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return mt("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return mt("spec needs at least one entry in `questions`");try{Aa(t.questions)}catch(r){return mt(r?.message??String(r))}let n=t.seat||e.seat;vt(),process.env[_a(n)]="active";let s=null;if(e.record!==!1)try{s=new is({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
327
+ `)}Ra({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await yo(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return mt(`the ${e.backend} backend did not answer \u2014 check the key and that the seat is reachable`);console.log(JSON.stringify({ok:!0,seat:n,callId:i.callId,answers:i.answers},null,2)),s?.close()});function mt(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function hh(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}$n();import{Command as zh}from"commander";import{execFile as Yh,spawn as jg}from"child_process";import{promisify as Vh}from"util";import{existsSync as Kh,statSync as Xh}from"fs";import{join as Og}from"path";import{tmpdir as Qh}from"os";import ne from"chalk";var yh={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Here's something about X search that almost nobody uses. It takes ten seconds and it changes what the site is good for."},{say:"Let's open search. This is it in the sidebar.",find:"the search and explore link in the sidebar",label:"Search",before:"Google Chrome is frontmost showing signed-in x.com with the search and explore sidebar link visible",click:!0,afterClickWaitMs:2600},{say:"Here's the box itself. Most people type a few words here and scroll. But it accepts commands, not just words.",find:"the search query input field where you type",label:"search field",before:"Google Chrome is frontmost showing x.com with the search query input visible",click:!0,afterClickWaitMs:900},{say:"Watch. From colon, then a username, limits it to that person. Then min underscore faves, colon, five hundred \u2014 only posts with at least five hundred likes.",before:"Google Chrome is frontmost on x.com and the empty search query input has keyboard focus",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",before:"Google Chrome is frontmost on x.com and the focused search input contains from:naval min_faves:500",key:"return",holdSeconds:3.2,verify:"the x.com page is displaying search results for the query from:naval min_faves:500, with at least one post visible"},{say:"There it is. That person's greatest hits \u2014 everything they wrote that actually landed. No scrolling through years of replies.",holdSeconds:2},{say:"Two more that pair well with it. Until colon, and since colon, with a date, pin it to a time period. Useful when you half remember something from a particular month."},{say:"And filter colon links, or filter colon media, narrows it to posts that shared something, which is usually where the substance is."},{say:"After you search, check the Latest tab. Top is ranked, Latest is chronological, and for research you almost always want chronological.",find:"the Latest tab",label:"Latest"},{say:"That's it. From colon someone, min underscore faves colon five hundred. It works on your own account too, which is a quick way to see what people actually responded to."}]},wh={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Opens X in Chrome; sign in before running the lesson.",start:{app:"Google Chrome",url:"https://x.com/home",ready:"Google Chrome is frontmost showing the signed-in x.com home page with its navigation sidebar"},steps:[{say:"Most people's bookmarks on X are a single pile they never open again. There's a fix that takes a minute."},{say:"Bookmarks live here in the sidebar. By default everything you save lands in one list, in the order you saved it.",find:"the Bookmarks link in the sidebar",label:"Bookmarks",before:"Google Chrome is frontmost showing signed-in x.com with the Bookmarks sidebar link visible",click:!0,verify:"Google Chrome is showing the x.com Bookmarks page"},{say:"But bookmarks support folders. Open bookmarks and look for the add folder control, usually a small plus at the top right.",find:"the add folder button",label:"new folder"},{say:"The trick is what you name them. Not topics like design or tech, which you'll never search for. Name them after decisions you're going to make, like hiring, or pricing.",holdSeconds:2},{say:"Then when you save a post, hold the bookmark button instead of tapping it, and it asks which folder. That one gesture is the whole difference between a pile and a library."}]},$h={id:"agentx-dashboard-tour",title:"AgentX: a tour of your agent team",appHint:"Start the demo first: docker compose -f docker-compose.demo.yml up -d",start:{app:"Google Chrome",url:"http://127.0.0.1:18931/live",cleanWindow:!0,ready:"The text laptop-paris is visible on the page"},steps:[{say:"This is AgentX: a team of AI agents running on your own machines. Everything here is real, except the model's replies, which are scripted for the demo."},{say:"Up top, three machines, one agent each, all online.",find:"the 3/3 machines count under Agents online",label:"3 machines online"},{say:"This machine is a laptop in Paris. Its agent, CX, talks to customers, and hands technical work to others.",find:"the laptop-paris machine name",label:"CX \xB7 laptop-paris"},{say:"And this is Builder, on a server in New York. When CX gets a code problem, it sends it here, across the mesh.",find:"the @builder Builder agent name in the vps-nyc section",label:"Builder \xB7 vps-nyc"},{say:"Operations shows what the whole team actually did.",find:"the Operations tab in the top navigation bar",label:"Operations",before:"The AgentX Live page is on screen with the Live tab selected",click:!0,verify:"The page shows the heading Mesh operations"},{say:"Machines online, work in progress, failures today, and jobs waiting for a person to review.",find:"the Nodes online summary",label:"The team at a glance"},{say:"Each lane is one kind of work. The demo's run landed here, as direct tasks.",find:"the Direct lane label in the What ran chart",label:"Direct tasks"},{say:"Workflows turn a job you repeat into steps you can review before they run.",find:"the Workflows tab in the top navigation bar",label:"Workflows",before:"The AgentX page with the heading Mesh operations is on screen",click:!0,verify:"The page shows a Workflows list that includes Draft the demo shop report"},{say:"This one drafts a report for the demo shop. It's saved switched off, so nothing runs until you say so.",find:"the Draft the demo shop report workflow title",label:"A saved workflow"},{say:"And on every page, you can ask an agent about what you're looking at.",find:"the Ask an agent about this page input",label:"Ask an agent"},{say:"That's the tour. Your machines, the work they did, and the jobs you can hand them."}]},Tr=[yh,wh,$h];oe();oe();import uo from"chalk";import{execFile as bh}from"child_process";import{promisify as kh}from"util";import{createInterface as vh}from"readline";var ug=kh(bh);function xh(e){e.type==="step"?console.log(`${uo.cyan(` ${e.n}. ${e.action}`)}${e.target?uo.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(uo.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?uo.red(` failed: ${e.error}`):uo.dim(" done it")):e.type==="replanned"?console.log(uo.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(uo.cyan(` you: ${e.text}`)):e.type==="error"?console.log(uo.red(` error: ${e.error}`)):e.type==="end"&&console.log(uo.dim(` \xB7 ended (${e.reason})`))}async function Sh(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await ug("open",["-a",e]).catch(()=>{});try{let s=(await Hi()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function fg(e,o){let t=T(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await ug("open",["-a",o.app]),i=await Sh(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=ks(n,t.agents,!1),a=t.voice.listener??wl,c=Ct(n,t.agents[n]),l=new kl({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:Hi,presence:new vs(c,Pe,n),speech:new It,model:Nt({system:bl(r.persona,a)}),act:vl});l.on(xh),console.log(uo.bold(`
328
328
  ${c.name} teaches: ${e}`)+uo.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
329
- `));let g=bh({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}oe();import fo from"chalk";import{execFile as Ph}from"child_process";import{existsSync as Cr,writeFileSync as Mh}from"fs";import{homedir as Lh}from"os";import{join as Ag,resolve as qh}from"path";import{promisify as Uh}from"util";var He={w:1e3,h:640},jr=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],wg=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],hg=["none","semi","solid","fill","pattern"],Or=180,$g=48,xh=["s","m","l","xl"],Sh=["draw","sans","serif","mono"];function bg(){return[`You are an illustrator drawing on a tldraw canvas ${He.w} wide and ${He.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${Or}. Draw back to front: background first, then midground, foreground, details, text last, arrows at the very end.`,'Palette (optional, first line): {"palette":{"blue":"#1f5fa6","white":"#f7f3ea"},"say":"Choosing a palette."} remaps any of the colour names to a hex value for this drawing; every later element uses the names.','Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":"","opacity":1}',`Path: {"id":"dome","say":"","path":[[400,200],[410,170],[440,150],[470,170],[480,200],[400,200]],"color":"white","fill":"fill","opacity":1} is a free outline of 3 to ${$g} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it, then an arrow from that text to the thing.",`geo is one of: ${wg.join(", ")}.`,`color is one of: ${jr.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
330
- `)}function Gt(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function pt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var ut=(e,o,t)=>Math.min(t,Math.max(o,e)),yg=e=>ut(pt(e)??1,.1,1),Eh=/^#[0-9a-f]{6}$/i;function Ah(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))jr.includes(t)&&typeof n=="string"&&Eh.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Th(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,$g)){if(!Array.isArray(t))return null;let n=pt(t[0]),s=pt(t[1]);if(n===null||s===null)return null;o.push([ut(n,0,He.w),ut(s,0,He.h)])}return o.length>=2?o:null}function kg(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=Ah(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Gt(n.color,jr,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Th(n.path),g=Gt(n.fill,hg,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:yg(n.opacity)}}let a=pt(n.x),c=pt(n.y);if(a===null||c===null)return null;if(typeof n.text=="string"&&n.text)return{kind:"text",id:s,say:i,text:n.text.slice(0,60),x:ut(a,0,He.w-20),y:ut(c,0,He.h-20),size:Gt(n.size,xh,"l"),color:r,font:Gt(n.font,Sh,"draw")};if(typeof n.geo=="string"){let l=pt(n.w),g=pt(n.h);if(l===null||g===null||l<4||g<4)return null;let d=ut(a,0,He.w-4),u=ut(c,0,He.h-4);return{kind:"geo",id:s,say:i,geo:Gt(n.geo,wg,"rectangle"),x:d,y:u,w:Math.min(l,He.w-d),h:Math.min(g,He.h-u),color:r,fill:Gt(n.fill,hg,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:yg(n.opacity)}}return null}var zs=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
331
- `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var jh=500,Oh=e=>`
329
+ `));let g=vh({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}oe();import fo from"chalk";import{execFile as Lh}from"child_process";import{existsSync as Cr,writeFileSync as qh}from"fs";import{homedir as Uh}from"os";import{join as Ag,resolve as Fh}from"path";import{promisify as Wh}from"util";var He={w:1e3,h:640},jr=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],wg=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],hg=["none","semi","solid","fill","pattern"],Or=180,$g=48,Eh=["s","m","l","xl"],Ah=["draw","sans","serif","mono"];function bg(){return[`You are an illustrator drawing on a tldraw canvas ${He.w} wide and ${He.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${Or}. Draw back to front: background first, then midground, foreground, details, text last, arrows at the very end.`,'Palette (optional, first line): {"palette":{"blue":"#1f5fa6","white":"#f7f3ea"},"say":"Choosing a palette."} remaps any of the colour names to a hex value for this drawing; every later element uses the names.','Shape: {"id":"sea","say":"First, the sea.","geo":"rectangle","x":0,"y":420,"w":1000,"h":220,"color":"blue","fill":"fill","label":"","opacity":1}',`Path: {"id":"dome","say":"","path":[[400,200],[410,170],[440,150],[470,170],[480,200],[400,200]],"color":"white","fill":"fill","opacity":1} is a free outline of 3 to ${$g} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it, then an arrow from that text to the thing.",`geo is one of: ${wg.join(", ")}.`,`color is one of: ${jr.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
330
+ `)}function Gt(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function pt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var ut=(e,o,t)=>Math.min(t,Math.max(o,e)),yg=e=>ut(pt(e)??1,.1,1),Th=/^#[0-9a-f]{6}$/i;function jh(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))jr.includes(t)&&typeof n=="string"&&Th.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Oh(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,$g)){if(!Array.isArray(t))return null;let n=pt(t[0]),s=pt(t[1]);if(n===null||s===null)return null;o.push([ut(n,0,He.w),ut(s,0,He.h)])}return o.length>=2?o:null}function kg(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=jh(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Gt(n.color,jr,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Oh(n.path),g=Gt(n.fill,hg,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:yg(n.opacity)}}let a=pt(n.x),c=pt(n.y);if(a===null||c===null)return null;if(typeof n.text=="string"&&n.text)return{kind:"text",id:s,say:i,text:n.text.slice(0,60),x:ut(a,0,He.w-20),y:ut(c,0,He.h-20),size:Gt(n.size,Eh,"l"),color:r,font:Gt(n.font,Ah,"draw")};if(typeof n.geo=="string"){let l=pt(n.w),g=pt(n.h);if(l===null||g===null||l<4||g<4)return null;let d=ut(a,0,He.w-4),u=ut(c,0,He.h-4);return{kind:"geo",id:s,say:i,geo:Gt(n.geo,wg,"rectangle"),x:d,y:u,w:Math.min(l,He.w-d),h:Math.min(g,He.h-u),color:r,fill:Gt(n.fill,hg,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:yg(n.opacity)}}return null}var zs=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
331
+ `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var Ch=500,Ih=e=>`
332
332
  editor.zoomToBounds({ x: 0, y: 0, w: ${He.w}, h: ${He.h} }, { inset: ${e}, immediate: true })
333
333
  const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${He.w}, y: 0 })
334
334
  const chrome = window.outerHeight - window.innerHeight
335
- return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${He.w} }`;function vg(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function xg(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function Ch(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function Sg(e){return`const hex = ${JSON.stringify(e.colors)}
335
+ return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${He.w} }`;function vg(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function xg(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function Nh(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function Sg(e){return`const hex = ${JSON.stringify(e.colors)}
336
336
  const tint = (h, t) => '#' + [1, 3, 5].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) * (1 - t) + 255 * t).toString(16).padStart(2, '0')).join('')
337
337
  const th = editor.getTheme('default')
338
338
  const colors = structuredClone(th.colors)
@@ -340,9 +340,9 @@ for (const mode of Object.keys(colors)) for (const [name, v] of Object.entries(h
340
340
  if (colors[mode][name]) Object.assign(colors[mode][name], { solid: v, fill: v, pattern: v, linedFill: tint(v, 0.25), semi: tint(v, 0.75), noteFill: v })
341
341
  }
342
342
  editor.updateTheme({ ...th, colors })
343
- return true`}function Ih(e,o){if(e.kind==="palette")return Sg(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
343
+ return true`}function Rh(e,o){if(e.kind==="palette")return Sg(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
344
344
  const el = ${JSON.stringify(e)}
345
- const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(jh/10)}))
345
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Ch/10)}))
346
346
  const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
347
347
  const id = createShapeId(${t(e.id)})
348
348
  editor.createShape({ id, type: 'geo', x: el.x, y: el.y, opacity: el.opacity, props: { geo: el.geo, w: 1, h: 1, color: el.color, fill: el.fill, dash: 'solid', size: 's' } })
@@ -382,69 +382,69 @@ return id`:`${n}
382
382
  const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
383
383
  const aid = typeof arrow === 'string' ? arrow : arrow?.id
384
384
  if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
385
- return aid ?? null`}function Nh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[To(s[0][0],s[0][1]),To(i[0],i[1])]}if(e.kind==="geo")return[To(e.x,e.y),To(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=xg(e);return[To(s.x,s.y+s.h/2),To(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[To(t.x+t.w/2,t.y+t.h/2),To(n.x+n.w/2,n.y+n.h/2)]}var To=(e,o)=>({x:e,y:o,w:0,h:0});async function Eg(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise(v=>setTimeout(v,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Oh(60)),g=new Set,d=new Map,u=[],f=!1,p=0,y=null,w=null,k=null,b=()=>{k?.(),k=null},$=x=>{if(g.size>=Or)return;let v=kg(x,g);if(!v){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add(v.id),y??=i()-c,u.push(v),n({type:"planned",n:g.size,el:v,atMs:i()-c}),b()},E=(async()=>{let x=new zs;try{for await(let v of o.model.reply(`Draw: ${e}`,t.signal))x.push(v).forEach($);x.flush().forEach($)}catch(v){w=v?.message??String(v)}finally{p=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let v=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,Sg(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-v});continue}let[R,I]=Nh(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(vg(l,R.x,R.y)),await s(250),o.presence.moveTo(vg(l,I.x,I.y));try{await o.api.exec(t.docId,Ih(x,a))}catch(P){n({type:"error",error:`${x.id}: ${P?.message??P}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?xg(x):x.kind==="path"?Ch(x.pts):To(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-v});let C=(x.say?r:0)-(i()-v);C>0&&await s(C)}return await E,w&&n({type:"error",error:`plan: ${w}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:y,planMs:p}}import{readFileSync as Rh}from"fs";import{homedir as _h}from"os";import{join as Dh}from"path";var Fn=Dh(_h(),"Library","Application Support","tldraw","server.json"),Ys=class{constructor(o=Fn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=Rh(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var Fh=Uh(Ph),Wh="claude-sonnet-5";function Jh(e){e.type==="planned"?console.log(fo.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${fo.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${fo.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(fo.yellow(` skipped: ${e.line}`)):console.log(fo.red(` error: ${e.error}`))}async function Bh(){if(!Cr(Fn)){await Fh("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Cr(Fn);e++)await new Promise(o=>setTimeout(o,500));if(!Cr(Fn))throw new Error("tldraw offline did not start")}}async function Tg(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||Wh,i=qh(o.out||Ag(Lh(),"Documents")),r=Ct(n,t.agents[n]),a=Nt({system:bg(),model:s}),c=new vs(r,Pe,n),l=new Ys;try{await Bh();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(fo.bold(`
385
+ return aid ?? null`}function _h(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[To(s[0][0],s[0][1]),To(i[0],i[1])]}if(e.kind==="geo")return[To(e.x,e.y),To(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=xg(e);return[To(s.x,s.y+s.h/2),To(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[To(t.x+t.w/2,t.y+t.h/2),To(n.x+n.w/2,n.y+n.h/2)]}var To=(e,o)=>({x:e,y:o,w:0,h:0});async function Eg(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise(v=>setTimeout(v,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Ih(60)),g=new Set,d=new Map,u=[],f=!1,p=0,y=null,w=null,k=null,b=()=>{k?.(),k=null},$=x=>{if(g.size>=Or)return;let v=kg(x,g);if(!v){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add(v.id),y??=i()-c,u.push(v),n({type:"planned",n:g.size,el:v,atMs:i()-c}),b()},E=(async()=>{let x=new zs;try{for await(let v of o.model.reply(`Draw: ${e}`,t.signal))x.push(v).forEach($);x.flush().forEach($)}catch(v){w=v?.message??String(v)}finally{p=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let v=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,Sg(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-v});continue}let[R,I]=_h(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(vg(l,R.x,R.y)),await s(250),o.presence.moveTo(vg(l,I.x,I.y));try{await o.api.exec(t.docId,Rh(x,a))}catch(P){n({type:"error",error:`${x.id}: ${P?.message??P}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?xg(x):x.kind==="path"?Nh(x.pts):To(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-v});let C=(x.say?r:0)-(i()-v);C>0&&await s(C)}return await E,w&&n({type:"error",error:`plan: ${w}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:y,planMs:p}}import{readFileSync as Dh}from"fs";import{homedir as Ph}from"os";import{join as Mh}from"path";var Fn=Mh(Ph(),"Library","Application Support","tldraw","server.json"),Ys=class{constructor(o=Fn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=Dh(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var Jh=Wh(Lh),Bh="claude-sonnet-5";function Hh(e){e.type==="planned"?console.log(fo.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${fo.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${fo.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(fo.yellow(` skipped: ${e.line}`)):console.log(fo.red(` error: ${e.error}`))}async function Gh(){if(!Cr(Fn)){await Jh("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Cr(Fn);e++)await new Promise(o=>setTimeout(o,500));if(!Cr(Fn))throw new Error("tldraw offline did not start")}}async function Tg(e,o){let t=T(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||Bh,i=Fh(o.out||Ag(Uh(),"Documents")),r=Ct(n,t.agents[n]),a=Nt({system:bg(),model:s}),c=new vs(r,Pe,n),l=new Ys;try{await Gh();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(fo.bold(`
386
386
  ${r.name} draws: ${e}`)+fo.dim(` (${s}, ${d.filePath})
387
- `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Eg(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Jh);await l.exec(d.id,"await helpers.saveDoc(); return true");let p=await l.exec(d.id,"const r = await editor.toImageDataUrl([...editor.getCurrentPageShapeIds()], { format: 'png', scale: 2, background: true }); return r.url"),y=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):Ag(i,`agentx-draw-${g}.png`);Mh(y,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(fo.bold(`
387
+ `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Eg(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Hh);await l.exec(d.id,"await helpers.saveDoc(); return true");let p=await l.exec(d.id,"const r = await editor.toImageDataUrl([...editor.getCurrentPageShapeIds()], { format: 'png', scale: 2, background: true }); return r.url"),y=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):Ag(i,`agentx-draw-${g}.png`);qh(y,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(fo.bold(`
388
388
  ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+fo.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`));let w=a.lastUsage;w&&console.log(fo.dim(` tokens: ${w.inputTokens} in, ${w.outputTokens} out, ${w.cacheReadTokens} cache read, ${w.cacheWriteTokens} cache write; cost ${w.costUsd===null?"not reported":`$${w.costUsd.toFixed(4)}`}`)),console.log(fo.dim(` ${d.filePath}
389
389
  ${y}
390
- `))}finally{a.close(),c.close()}}var Nr=zh(Gh),Cg=new Hh().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>",`system voice name, "${Lo}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await Tg(String(o.live),o):await fg(String(o.live),o),process.exit(0)}catch(g){console.log(ne.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(ne.bold(`
390
+ `))}finally{a.close(),c.close()}}var Nr=Vh(Yh),Cg=new zh().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <voice>",`system voice name, "${Lo}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await Tg(String(o.live),o):await fg(String(o.live),o),process.exit(0)}catch(g){console.log(ne.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(ne.bold(`
391
391
  lessons
392
392
  `));for(let g of Tr)console.log(` ${ne.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${ne.dim(g.appHint)}
393
- `);return}let t=Tr.find(g=>g.id===e);t||(console.log(ne.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Yh(Pe)||(console.log(ne.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Zh(o.voice,o.agent);console.log(ne.bold(`
393
+ `);return}let t=Tr.find(g=>g.id===e);t||(console.log(ne.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Kh(Pe)||(console.log(ne.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:oy(o.voice,o.agent);console.log(ne.bold(`
394
394
  ${t.title}`)),console.log(ne.dim(` ${t.appHint}
395
- `));try{t.start&&(await Nr("/usr/bin/open",Xh(t.start)),await Yo(2e3),await Vs(t.start.ready))}catch(g){console.log(ne.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Og(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(ne.dim(` recording \u2192 ${i}`)),s=jg("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Yo(2e3));let r=o.hud===!1?null:jg(Pe,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
396
- `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${ne.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await Vs(d.before)}let u=o.speak===!1?Promise.resolve():oy(d.say,n),f=d.find?await Qh(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${d.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Nr(Pe,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]),d.click)){let{error:p,changed:y}=await Ir(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:y!==!1,note:p??void 0}),y===!1&&console.log(ne.yellow(" \xB7 clicked, but the screen did not change")),await Yo(d.afterClickWaitMs??1500)}if(d.type){await Vs(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await Ir(["type","--text",d.type]);if(p)throw console.log(ne.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:p}),new Error(p)}if(d.key){await Vs(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Ir(["key","--name",d.key]);if(p)throw console.log(ne.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`press ${d.key}`,changed:!1,note:p}),new Error(p)}if(!f&&!d.type&&!d.key?await Yo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Yo(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),y;try{y=await Ln(d.verify,p?{settle:!0,screen:wo()}:{})}catch(w){y=null,console.log(ne.yellow(` ? could not check: ${w?.message??w}`))}if(!y&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(y){let w=y.outcome==="confirmed"?ne.green("\u2713"):y.outcome==="refuted"?ne.red("\u2717"):ne.yellow("?");if(console.log(` ${w} ${ne.dim(y.reason)}`),!y.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(ne.red(`
397
- stopping: could not confirm \u2014 ${d.verify}`)),console.log(ne.dim(` ${y.reason}`)),console.log(ne.dim(` screenshot: ${y.sighting.shot.path}`)),await Yo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(ne.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await Yo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Yo(2500);try{let{size:g}=Vh(i);console.log(ne.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(ne.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(ne.red(` lesson stopped before the end.
395
+ `));try{t.start&&(await Nr("/usr/bin/open",Zh(t.start)),await Yo(2e3),await Vs(t.start.ready))}catch(g){console.log(ne.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Og(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(ne.dim(` recording \u2192 ${i}`)),s=jg("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Yo(2e3));let r=o.hud===!1?null:jg(Pe,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
396
+ `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${ne.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await Vs(d.before)}let u=o.speak===!1?Promise.resolve():ny(d.say,n),f=d.find?await ey(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${d.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Nr(Pe,["point","--x",String(f.x),"--y",String(f.y),"--w",String(f.width),"--h",String(f.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]),d.click)){let{error:p,changed:y}=await Ir(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:y!==!1,note:p??void 0}),y===!1&&console.log(ne.yellow(" \xB7 clicked, but the screen did not change")),await Yo(d.afterClickWaitMs??1500)}if(d.type){await Vs(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await Ir(["type","--text",d.type]);if(p)throw console.log(ne.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:p}),new Error(p)}if(d.key){await Vs(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Ir(["key","--name",d.key]);if(p)throw console.log(ne.red(` \u2717 ${p}`)),a("Blocked",p,"waiting"),c.push({tried:`press ${d.key}`,changed:!1,note:p}),new Error(p)}if(!f&&!d.type&&!d.key?await Yo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Yo(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),y;try{y=await Ln(d.verify,p?{settle:!0,screen:wo()}:{})}catch(w){y=null,console.log(ne.yellow(` ? could not check: ${w?.message??w}`))}if(!y&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(y){let w=y.outcome==="confirmed"?ne.green("\u2713"):y.outcome==="refuted"?ne.red("\u2717"):ne.yellow("?");if(console.log(` ${w} ${ne.dim(y.reason)}`),!y.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(ne.red(`
397
+ stopping: could not confirm \u2014 ${d.verify}`)),console.log(ne.dim(` ${y.reason}`)),console.log(ne.dim(` screenshot: ${y.sighting.shot.path}`)),await Yo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(ne.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await Yo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Yo(2500);try{let{size:g}=Xh(i);console.log(ne.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(ne.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(ne.red(` lesson stopped before the end.
398
398
  `)),process.exitCode=3;return}console.log(ne.green(`
399
399
  done.
400
- `))});function Xh(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Og(Kh(),"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 Vs(e){let o=await Ln(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Ir(e){try{let{stdout:o}=await Nr(Pe,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 Qh(e,o=[]){try{let t=await xs({max:45});if(t.candidates.length<2)return null;let n=await yo(Pn,Fs({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Ws(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Js(n.answers,t.candidates);return s.present<.5?null:En(t,s.id)}catch{return null}}function Zh(e,o){if(e?.trim().toLowerCase()===Lo)return{provider:"system",elevenlabs:Sn(),system:null,fallback:!0};let t=e?bs(e,xn()):null;if(t)return{provider:"system",elevenlabs:Sn(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=j(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(ne.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?ll(al(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Sn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(ne.dim(` no agent voice (${String(n?.message??n).split(`
401
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Sn(),system:null,fallback:!0}}}var ey=new It;async function oy(e,o){o&&await ey.say({voice:o,text:e})}var Yo=e=>new Promise(o=>setTimeout(o,e));oe();import{Command as Ig}from"commander";import Ve from"chalk";import{createInterface as Ng}from"readline";var ty=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function zt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(ty()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function ny(e){e.type==="line"?console.log(`${Ve.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ve.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ve.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ve.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ve.dim(" \xB7 hushed")):e.type==="error"?console.log(Ve.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ve.dim(` \xB7 ended (${e.reason})`))}function Rg(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 sy(e,o,t){let n=j(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await zt("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new hl(()=>n,()=>d),i.usePool(await fl(rl()))}let r=e.map(d=>s[d]?ks(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 wl({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new It,listener:n.voice.listener,model:(d,u)=>Nt({system:u})});l.on(ny),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ve.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Ng({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(Ve.dim(` ${Rg(l.gaps)}`))}async function iy(e,o,t){let n=await zt("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=Ng({input:process.stdin});s.on("line",a=>{a.trim()&&zt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void zt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await zt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ve.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(Ve.dim(` ${Rg(r)}`))}var _g=new Ig().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?sy:iy)([e,o],s,n),process.exit(0)}catch(i){console.error(Ve.red(` ${i?.message??i}`)),process.exit(1)}}),Dg=new Ig().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(Ve.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await zt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ve.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});oe();import{Command as ry}from"commander";import Q from"chalk";import{existsSync as ay,readFileSync as Mg,writeFileSync as Lg}from"fs";import{resolve as Pg}from"path";Ep();var Yt=new ry().name("voice").description("list installed system voices and pick each agent's voice");function Rr(e){let o=e?[e]:[Pg(process.cwd(),"agentx.json"),Pg(process.cwd(),".agentx/config.json")],t=o.find(n=>ay(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function cy(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=y=>{if(!a){l.system=y;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:y}},f=a?` for ${a}`:"";if(t){let y=t.trim().toLowerCase()===Lo,w=y?null:bs(t,s,a??e?.voice?.locale),k=w?`system voice ${Fi(w)}`:"the OS default voice";if((w||y)&&g==="system")u(y?Lo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!y&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||y)u(y?Lo: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}}Yt.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=xn(),t;try{t=j(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?cl(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(Wi(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(Q.yellow(`
400
+ `))});function Zh(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Og(Qh(),"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 Vs(e){let o=await Ln(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Ir(e){try{let{stdout:o}=await Nr(Pe,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 ey(e,o=[]){try{let t=await xs({max:45});if(t.candidates.length<2)return null;let n=await yo(Pn,Fs({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Ws(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Js(n.answers,t.candidates);return s.present<.5?null:En(t,s.id)}catch{return null}}function oy(e,o){if(e?.trim().toLowerCase()===Lo)return{provider:"system",elevenlabs:Sn(),system:null,fallback:!0};let t=e?bs(e,xn()):null;if(t)return{provider:"system",elevenlabs:Sn(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=T(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(ne.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?dl(cl(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Sn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(ne.dim(` no agent voice (${String(n?.message??n).split(`
401
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Sn(),system:null,fallback:!0}}}var ty=new It;async function ny(e,o){o&&await ty.say({voice:o,text:e})}var Yo=e=>new Promise(o=>setTimeout(o,e));oe();import{Command as Ig}from"commander";import Ve from"chalk";import{createInterface as Ng}from"readline";var sy=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function zt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(sy()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function iy(e){e.type==="line"?console.log(`${Ve.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ve.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ve.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ve.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ve.dim(" \xB7 hushed")):e.type==="error"?console.log(Ve.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ve.dim(` \xB7 ended (${e.reason})`))}function Rg(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 ry(e,o,t){let n=T(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await zt("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new yl(()=>n,()=>d),i.usePool(await hl(al()))}let r=e.map(d=>s[d]?ks(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 $l({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new It,listener:n.voice.listener,model:(d,u)=>Nt({system:u})});l.on(iy),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ve.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Ng({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(Ve.dim(` ${Rg(l.gaps)}`))}async function ay(e,o,t){let n=await zt("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=Ng({input:process.stdin});s.on("line",a=>{a.trim()&&zt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void zt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await zt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ve.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(Ve.dim(` ${Rg(r)}`))}var _g=new Ig().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?ry:ay)([e,o],s,n),process.exit(0)}catch(i){console.error(Ve.red(` ${i?.message??i}`)),process.exit(1)}}),Dg=new Ig().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(Ve.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await zt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ve.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});oe();import{Command as cy}from"commander";import Q from"chalk";import{existsSync as ly,readFileSync as Mg,writeFileSync as Lg}from"fs";import{resolve as Pg}from"path";Tp();var Yt=new cy().name("voice").description("list installed system voices and pick each agent's voice");function Rr(e){let o=e?[e]:[Pg(process.cwd(),"agentx.json"),Pg(process.cwd(),".agentx/config.json")],t=o.find(n=>ly(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function dy(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=y=>{if(!a){l.system=y;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:y}},f=a?` for ${a}`:"";if(t){let y=t.trim().toLowerCase()===Lo,w=y?null:bs(t,s,a??e?.voice?.locale),k=w?`system voice ${Fi(w)}`:"the OS default voice";if((w||y)&&g==="system")u(y?Lo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!y&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||y)u(y?Lo: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}}Yt.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=xn(),t;try{t=T(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?ll(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(Wi(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(Q.yellow(`
402
402
  No system voices found (system voices need macOS).
403
403
  `));else{let a=e.all?Ui(o,""):Ui(o,n);console.log(Q.bold(`
404
404
  System voices${e.all?"":` (${n})`}, best first
405
405
  `));for(let c of a){let l=c.siri?Q.magenta("siri"):c.quality==="standard"?Q.dim("standard"):Q.green(c.quality),g=s.get(c.id)?.join(", ");console.log(` ${(c.siri?`siri:${c.name.toLowerCase()}`:c.name).padEnd(12)} ${c.locale.padEnd(6)} ${l.padEnd(18)} ${Q.dim((c.gender??"").padEnd(7))} ${g?Q.cyan(g):""}`)}o.some(c=>c.quality!=="standard")||(console.log(Q.dim(`
406
- More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Q.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}let r=t?gl(t,o):[];if(r.length){console.log(Q.bold.yellow(`
406
+ More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(Q.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}let r=t?ml(t,o):[];if(r.length){console.log(Q.bold.yellow(`
407
407
  Not installed
408
408
  `));for(let a of r)console.log(` ${Ji(a.voice).padEnd(24)} ${Q.cyan(a.agents.join(", "))}`);console.log(Q.dim(`
409
- Reinstall in ${dl}.`)),console.log(Q.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(t){console.log(Q.bold(`
409
+ Reinstall in ${gl}.`)),console.log(Q.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(t){console.log(Q.bold(`
410
410
  Agents
411
- `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=y=>y?Fi(y):Q.dim("system default"),d=Object.entries(Wi(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,y])=>(y?.id??null)!==(i.get(a)?.id??null)).map(([y,w])=>`${Q.dim(`${y}:`)} ${g(w)}`).join(Q.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??Q.dim("(default voice)")}`:`system ${g(i.get(a))}${d?Q.dim(" \xB7 ")+d:""}`,f=r.filter(y=>y.agents.includes(a)).map(y=>Ji(y.voice)),p=f.length?Q.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?Q.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});Yt.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Lo}" 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=Rr(t.config),{raw:s,summary:i}=cy(JSON.parse(Mg(n,"utf8")),e,o,t,xn());Lg(n,JSON.stringify(s,null,2)+`
412
- `),console.log(Q.green(` ${e}: ${i}`)),console.log(Q.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Q.red(` ${n.message}`)),process.exit(1)}});function qg(e,o){let t=pl(o,j(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
413
- `));let n=JSON.parse(Mg(e,"utf8"));ul(n,o),Lg(e,JSON.stringify(n,null,2)+`
414
- `)}Yt.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${ka.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=Rr(t.config);if(e&&o){let i=o==="default"?null:o;qg(n,{agents:{[e]:{palette:i}}}),console.log(Q.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(Q.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=j(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(Q.bold(`
411
+ `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=y=>y?Fi(y):Q.dim("system default"),d=Object.entries(Wi(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,y])=>(y?.id??null)!==(i.get(a)?.id??null)).map(([y,w])=>`${Q.dim(`${y}:`)} ${g(w)}`).join(Q.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??Q.dim("(default voice)")}`:`system ${g(i.get(a))}${d?Q.dim(" \xB7 ")+d:""}`,f=r.filter(y=>y.agents.includes(a)).map(y=>Ji(y.voice)),p=f.length?Q.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?Q.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});Yt.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Lo}" 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=Rr(t.config),{raw:s,summary:i}=dy(JSON.parse(Mg(n,"utf8")),e,o,t,xn());Lg(n,JSON.stringify(s,null,2)+`
412
+ `),console.log(Q.green(` ${e}: ${i}`)),console.log(Q.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(Q.red(` ${n.message}`)),process.exit(1)}});function qg(e,o){let t=ul(o,T(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
413
+ `));let n=JSON.parse(Mg(e,"utf8"));fl(n,o),Lg(e,JSON.stringify(n,null,2)+`
414
+ `)}Yt.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${ka.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=Rr(t.config);if(e&&o){let i=o==="default"?null:o;qg(n,{agents:{[e]:{palette:i}}}),console.log(Q.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(Q.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=T(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(Q.bold(`
415
415
  Orb palettes
416
416
  `));for(let i of ba)console.log(` ${i.id.padEnd(10)} ${Q.dim(i.colors.join(" "))}`);console.log(Q.bold(`
417
417
  Agents
418
- `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Ct(i,r).color,c=va(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${Q.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(Q.red(` ${n.message}`)),process.exit(1)}});Yt.command("card").description("the answer shown in the pill: how long it stays open and how tall it grows").option("--timeout <seconds>",`seconds it stays open once spoken, ${Bi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Bi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=Rr(e.config),t={};e.timeout!==void 0&&(t.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(t.maxHeight=Number(e.maxHeight)),Object.keys(t).length&&qg(o,{general:{card:t}});let n=j(o).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(t).length&&console.log(Q.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(o){console.log(Q.red(` ${o.message}`)),process.exit(1)}});import{Command as ly}from"commander";import N from"chalk";var Vo=new ly().name("attach").description("wear an agentx agent identity in this Claude Code session"),Ks=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${nt()}`;function Xs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Qs(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function Zs(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:o}function Fg(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function dy(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(t)} ${Fg(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function gy(e){let o=e.filter(n=>n.agentIds.length>0),t=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:o,watching:t,idle:e.length-o.length-t.length}}function my(e,o=!1){let t=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(t)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Vo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ni.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ks).action(async(e,o)=>{let t=Xs(o.session);t||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),Wa(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Ni.join(", ")}`)),process.exit(1)),jn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Qs(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${Fg(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(N.red(`Bind failed: ${Zs(n)}`)),process.exit(1)}});function Ug(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function py(e){let o=Ug(e.kinds),t=Ug(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}Vo.command("watch").description("watch this session: no identity, no messages, a short event digest on each prompt").option("--kinds <list>","event kinds or types to include, comma separated (default: failures, completions, approvals waiting, peers down)").option("--agents <list>","only events for these agents, comma separated").option("--match <text>","only events whose summary contains this text").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ks).action(async e=>{let o=Xs(e.session);o||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")}.`),process.exit(1)),jn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await Qs(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:py(e)}),console.log(`${N.green("\u2713")} This session is now ${N.bold("watching")}. It answers for no agent.`),console.log(N.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(N.gray(` Stop with ${N.cyan("agentx attach detach")}.`))}catch(t){console.error(N.red(`Watch failed: ${Zs(t)}`)),process.exit(1)}});Vo.command("detach").description("stop wearing an identity or watching in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ks).action(async e=>{let o=Xs(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Qs(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(N.red(`Detach failed: ${Zs(t)}`)),process.exit(1)}});Vo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Ks).option("--json","raw JSON output").action(async e=>{let o=Xs();try{let n=(await Qs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:jn(),sessions:n},null,2));return}console.log(),console.log(jn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(Tn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=gy(n);if(console.log(N.bold(" Identities")),s.length===0)console.log(N.gray(" No session is wearing an identity right now."));else for(let a of s)dy(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)my(a,a.sessionId===o)}r>0&&console.log(N.gray(`
418
+ `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Ct(i,r).color,c=va(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${Q.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(Q.red(` ${n.message}`)),process.exit(1)}});Yt.command("card").description("the answer shown in the pill: how long it stays open and how tall it grows").option("--timeout <seconds>",`seconds it stays open once spoken, ${Bi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Bi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=Rr(e.config),t={};e.timeout!==void 0&&(t.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(t.maxHeight=Number(e.maxHeight)),Object.keys(t).length&&qg(o,{general:{card:t}});let n=T(o).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(t).length&&console.log(Q.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(o){console.log(Q.red(` ${o.message}`)),process.exit(1)}});import{Command as gy}from"commander";import N from"chalk";var Vo=new gy().name("attach").description("wear an agentx agent identity in this Claude Code session"),Ks=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${nt()}`;function Xs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Qs(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function Zs(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:o}function Fg(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function my(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(t)} ${Fg(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function py(e){let o=e.filter(n=>n.agentIds.length>0),t=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:o,watching:t,idle:e.length-o.length-t.length}}function uy(e,o=!1){let t=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(t)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Vo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ni.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ks).action(async(e,o)=>{let t=Xs(o.session);t||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),Wa(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Ni.join(", ")}`)),process.exit(1)),jn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Qs(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${Fg(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(N.red(`Bind failed: ${Zs(n)}`)),process.exit(1)}});function Ug(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function fy(e){let o=Ug(e.kinds),t=Ug(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}Vo.command("watch").description("watch this session: no identity, no messages, a short event digest on each prompt").option("--kinds <list>","event kinds or types to include, comma separated (default: failures, completions, approvals waiting, peers down)").option("--agents <list>","only events for these agents, comma separated").option("--match <text>","only events whose summary contains this text").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ks).action(async e=>{let o=Xs(e.session);o||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")}.`),process.exit(1)),jn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await Qs(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:fy(e)}),console.log(`${N.green("\u2713")} This session is now ${N.bold("watching")}. It answers for no agent.`),console.log(N.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(N.gray(` Stop with ${N.cyan("agentx attach detach")}.`))}catch(t){console.error(N.red(`Watch failed: ${Zs(t)}`)),process.exit(1)}});Vo.command("detach").description("stop wearing an identity or watching in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ks).action(async e=>{let o=Xs(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Qs(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(N.red(`Detach failed: ${Zs(t)}`)),process.exit(1)}});Vo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Ks).option("--json","raw JSON output").action(async e=>{let o=Xs();try{let n=(await Qs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:jn(),sessions:n},null,2));return}console.log(),console.log(jn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(Tn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=py(n);if(console.log(N.bold(" Identities")),s.length===0)console.log(N.gray(" No session is wearing an identity right now."));else for(let a of s)my(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)uy(a,a.sessionId===o)}r>0&&console.log(N.gray(`
419
419
  ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(N.red(`Could not read attach state: ${Zs(t)}`)),process.exit(1)}});Vo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||nt()),t=nd(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${N.green("\u2713")} Installed attach hooks in ${N.gray(t.path)}`:`${N.green("\u2713")} Attach hooks already up to date in ${N.gray(t.path)}`),console.log(N.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(N.gray(" PreToolUse guard installed at user scope.")),console.log(N.gray(` (An attached session runs under your permissions, not the agent's workspace
420
420
  settings \u2014 without this an attached production identity would be less
421
- 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)}});Vo.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=sd({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)}});oe();import{Command as uy}from"commander";import be from"chalk";var ei=new uy().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Jg(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=j(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 Bg(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Wg(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 fy(e){return e==="busy"?be.magenta:e==="warm-hot"?be.green:e==="warm-cold"?be.cyan:e==="idle"?be.yellow:e==="dead"?be.red:be.dim}ei.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}=Jg(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Bg(t)})}catch(r){console.log(be.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(be.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(be.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(be.dim(" (no processes)"));return}for(let r of i){let a=fy(r.state)(r.state.padEnd(9)),c=Wg(r.spawnedAt),l=r.lastTurnAt?Wg(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?be.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?be.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):be.dim("sess=\u2014"),u=r.pendingTaskId?be.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${be.bold(r.key.agentId)}${be.dim(":"+r.key.channel+":"+r.key.chatId)} ${be.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${be.red("dead:")} ${r.deadReason}`)}});ei.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}=Jg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Bg(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(be.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(be.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(be.red(` ${a}`)),process.exit(1)}console.log(be.green(` killed ${e}:${o}:${t}`))});import{Command as hy}from"commander";import Ue from"chalk";import{existsSync as _r,rmSync as yy}from"fs";import{resolve as Dr}from"path";var Vt=new hy().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Vt.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(Ue.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Ga(e,o,{verbose:n}),r=Date.now()-s;console.log(Ue.green(` \u2713 indexed ${i.docs} doc(s) for ${Ue.bold(e)} in ${r}ms`)),console.log(Ue.dim(` \u2192 ${i.path}`))});Vt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Dr(e.cwd,".agentx","rag");if(!_r(o)){console.log(Ue.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>_r(Dr(o,s,"index.json")));if(n.length===0){console.log(Ue.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ri(s);console.log(` ${Ue.bold(s)} ${i.docs} doc(s) ${Ue.dim(i.path)}`)}});Vt.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=za(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ri(e);i.exists?console.log(Ue.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ue.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ue.bold(i.title)} ${Ue.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ue.dim(i.path)}`),console.log(` ${Ue.dim(i.snippet.slice(0,200))}`)});Vt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Dr(process.cwd(),".agentx","rag",e);if(!_r(o)){console.log(Ue.dim(` no index for ${e} \u2014 nothing to clear`));return}yy(o,{recursive:!0,force:!0}),console.log(Ue.green(` \u2713 cleared index for ${e}`))});oe();import{Command as wy}from"commander";import Z from"chalk";import Kt from"prompts";var ft=new wy().name("backlog").description("manage the local backlog used by business workSource=backlog");function Wn(e){let o=j(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new vl(n)}}function $y(e){return e?Z.cyan(`${e.type}:${e.project}#${e.iid}`):Z.dim("manual")}function by(e){return{todo:Z.gray("todo"),doing:Z.yellow("doing"),blocked:Z.red("blocked"),done:Z.green("done")}[e]}ft.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}=Wn(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(Z.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?Z.magenta(`@${n.assignee}`):Z.dim("unassigned");console.log(` ${by(n.status).padEnd(7)} ${$y(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Z.dim(` ${n.source.url}`))}console.log(),console.log(Z.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});ft.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=Wn(t.config);n.store.findById(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(Z.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=xl([o],i.source,n.config),a=await zi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Z.dim(" sync:"),...c));console.log(a.ok?Z.dim(` synced -> ${a.url??i.source.type}`):Z.yellow(` sync failed: ${a.error}`))}});ft.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=Wn(o.config);t.store.findById(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(Z.green(` done: ${s.title}`)),s.source){let i=await zi(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(Z.dim(" sync:"),...r));console.log(i.ok?Z.dim(` synced -> ${i.url??s.source.type}`):Z.yellow(` sync failed: ${i.error}`))}});ft.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}=Wn(o.config);t.remove(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1)),console.log(Z.green(` removed ${e}`))});ft.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=Wn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(Z.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 Kt({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(Z.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Z.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?vy(o.config):xy(o.config);w.length?(i=(await Kt({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 Kt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Kt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Kt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Z.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Sy(o.config,i,a):await Ey(o.config,i,a);if(!c.length){console.log(Z.yellow(" no open issues matched"));return}console.log(Z.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=Gi({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?Z.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Kt({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(Z.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?ky(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Gi(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()}}),y=o.store.addMany(p);console.log(Z.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let w of y)console.log(Z.dim(` ${w.id} \u2014 ${w.title}`))});function ky(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function vy(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 xy(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 Sy(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 Ey(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(Hg)}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(Hg):[]}function Hg(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 Ay}from"commander";import W from"chalk";import{existsSync as Ty,readFileSync as jy}from"fs";import{resolve as Oy}from"path";import Cy from"prompts";oe();function Gg(e){let o=e||Oy(process.cwd(),"agentx.json");return Ty(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(jy(o,"utf-8"))}async function Iy(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 Cy([{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 jo=new Ay().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');jo.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: ${Pi})`,Pi).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){jo.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=Di(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=Gg(o.config),s=Ea(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 Iy(o.notify,s),r=o.id||nc(t.matched,o.agent),a=ic({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:sc(o.onError),enabled:!o.disabled}),c=a.onError,l=await ie(d=>Ie(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."))});jo.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=Gg(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=ac(rc(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]])jo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await dc(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."))});jo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ie(t=>{if(!Ot(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Qa(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",cc,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",lc,"reject an agent's pending create/delete request (drops the request)"]])jo.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."))});jo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Di(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 Ny}from"commander";import ke from"chalk";import Oo from"chalk";function zg(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 Yg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Vg(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(Oo.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?zg():n?Fc(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(Oo.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={..._t().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await Hc(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(Oo.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(Oo.dim(` not answered${r.why?` (${r.why})`:""}; the card is still waiting`));return}let a=await $s({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(Oo.red(` ${a.error}`)),process.exitCode=1;return}console.log(Oo.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(`${Yg()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(Oo.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(Oo.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(Oo.red(` couldn't reach the daemon at ${Yg()}: ${n?.message??n}`)),process.exitCode=1}})}var Co=new Ny("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Ry={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function Kg(){return{root:process.cwd()}}function Pr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function _y(e){console.log(` ${ke.cyan(e.key)} ${ke.dim(`[${Ry[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ke.dim(` (later: until ${Pr(e.snoozed_until)})`):""}`),console.log(` ${ke.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ke.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,t)=>console.log(` ${ke.magenta(`${t+1}.`)} ${o}`)),e.expires&&console.log(ke.yellow(` Expires ${Pr(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ke.dim(` ${e.detail}`)),e.source&&console.log(ke.dim(` ${e.source}`)),console.log(ke.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Co.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=Bc(Kg(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ke.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ke.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)_y(t),console.log();console.log(ke.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Mr(e,o,t){let n=_t(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ke.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await $s(Kg(),e,o,{force:t.force,note:t.note,laterHours:s,choice:t.choice,text:t.text});if(!i.ok){console.error(ke.red(` ${i.error}`)),process.exitCode=1;return}console.log(ke.green(` \u2713 ${i.message}`))}Co.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)=>Mr(e,"yes",o));Co.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)=>Mr(e,"no",o));Co.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)=>Mr(e,"later",o));Co.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: ${Uc.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=_t(),t=Wc(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(ke.red(` ${t.error}`)),process.exitCode=1;return}console.log(ke.green(` \u2713 card:${t.card.id} raised; expires ${Pr(t.card.expires)}, then: ${t.card.if_silent}`))});Vg(Co);Co.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=Il(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=g}}catch(l){console.error(ke.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(o).some(l=>l!==void 0)){let l=await Nl(o);if(!l.success){console.error(ke.red(` ${l.error}`)),process.exitCode=1;return}console.log(ke.green(" \u2713 saved")+(l.reloaded?ke.dim(" (daemon reloaded)"):""))}let i=_t(),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 Dy}from"commander";import V from"chalk";oe();rs();Tp();var no=new Dy("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),Py=["owner","member","guest"];function oi(){let e=90;try{e=j().members.logRetentionDays}catch{}return new Dl(process.cwd(),Date.now,e)}var Xg=(e,o=[])=>[...o,e];async function Jn(e){let o="",t=await ie(n=>{n.people=Array.isArray(n.people)?n.people:[],o=e(n.people)});t.success||(console.error(V.red(`\u2717 ${(t.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(V.green(`\u2713 ${o}`)),t.reloaded&&console.log(V.dim(" daemon hot-reloaded"))}function ti(e,o){let t=e.find(n=>n?.id===o);if(!t)throw new Error(`No person "${o}". See \`agentx people list\`.`);return t.identities=Array.isArray(t.identities)?t.identities:[],t}function em(e,o){let t=Oi(e),n=Oi(o);return!!t&&!!n&&t.channel===n.channel&&t.value===n.value}function om(e){console.log(` ${V.bold(e.id)} ${e.name} ${V.dim(`\xB7 ${e.role}`)}${e.agents?.length?V.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}`),console.log(V.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}no.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let o=j().people;if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(),o.length===0&&(console.log(V.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${ji}"; senders on other channels are unknown.`)),console.log(V.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let t of o)om(t);console.log()});no.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${Py.join(" | ")}`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",Xg,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",Xg,[]).action(async(e,o)=>{await Jn(t=>{if(t.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);return t.push({id:e,name:o.name,role:o.role,identities:o.identity,agents:o.agent}),`added ${e} (${o.role})${o.agent.length?`, may reach ${o.agent.join(", ")}`:""}`})});no.command("allow <id> <agents...>").description('limit a person to these agents (ids, space-separated). "all" lifts the limit').action(async(e,o)=>{await Jn(t=>{let n=ti(t,e),s=o.length===1&&o[0].toLowerCase()==="all";return n.agents=s?[]:[...new Set(o)],s?`${e} may reach every agent`:`${e} may reach ${n.agents.join(", ")} and no other agent`})});no.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,o)=>{await Jn(t=>{let n=ti(t,e);return n.identities.some(s=>em(s,o))?`${e} already has ${o}`:(n.identities.push(o),`${o} is now ${e}`)})});no.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,o)=>{await Jn(t=>{let n=ti(t,e),s=n.identities.length;if(n.identities=n.identities.filter(i=>!em(i,o)),n.identities.length===s)throw new Error(`"${e}" has no identity ${o}.`);return`${o} is no longer ${e}`})});no.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown; every machine of theirs stops at once").action(async e=>{await Jn(t=>(ti(t,e),t.splice(t.findIndex(n=>n?.id===e),1),`removed ${e}`));let o=ql({tokens:new eo,members:oi()},e);o.length&&console.log(V.green(`\u2713 ended ${o.length} machine(s) of ${e}: ${o.map(t=>t.name).join(", ")}`)),console.log(V.dim(" If you shared this computer with them on the private network, remove that share too."))});no.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own work page (/member)").option("--url <origin>","address the person opens, e.g. https://my-mac.tailnet-name.ts.net (default: this computer's Tailscale name)").action((e,o)=>{try{let t=Nn(),n=ar(cr(),t);if(n.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the member page: ${n.join(", ")}`," Anyone you share this computer with could open it. Serve only the member paths instead:"," tailscale serve reset (removes every served path; add the phone app's /app lines back if you use it)",` tailscale serve --bg --set-path /member http://127.0.0.1:${t}/member`,` tailscale serve --bg --set-path /api/member http://127.0.0.1:${t}/api/member`].join(`
422
- `));let s=(o.url?String(o.url):rr()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(s))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${s}`);let i=j().people,r=Ml({tokens:new eo,codes:new ys,members:oi(),people:()=>i},e);if(!r.ok)throw new Error(r.error);console.log(),console.log(` Invite for ${V.bold(r.person.name)} (${r.person.id})`),console.log(),console.log(" 1. Share this computer with them on your private network, if you have not yet:"),console.log(V.dim(" Tailscale admin console \u2192 Machines \u2192 this computer \u2192 Share \u2192 send them the link.")),console.log(V.dim(' Limit what shared users can reach to port 443 in your access rules (see the docs page "Invite a teammate").')),console.log(" 2. Send them this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${V.cyan(`${s}/member`)}`),console.log(` ${V.bold(hs(r.code))}`),console.log(),console.log(` 3. When they pair, a card "New machine for ${r.person.name}" asks you to approve that machine.`),console.log(V.dim(` Their key stops after ${Pl} days; invite again then. Machine id: ${r.tokenId}`)),console.log()}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});no.command("devices [id]").description("the machines paired to people's work pages: state, where from, first and last use").option("--json","machine-readable output").action((e,o)=>{let t=oi().devices(e);if(o.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(V.dim(`
421
+ 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)}});Vo.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=sd({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)}});oe();import{Command as hy}from"commander";import be from"chalk";var ei=new hy().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Jg(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=T(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 Bg(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Wg(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 yy(e){return e==="busy"?be.magenta:e==="warm-hot"?be.green:e==="warm-cold"?be.cyan:e==="idle"?be.yellow:e==="dead"?be.red:be.dim}ei.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}=Jg(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Bg(t)})}catch(r){console.log(be.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(be.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(be.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(be.dim(" (no processes)"));return}for(let r of i){let a=yy(r.state)(r.state.padEnd(9)),c=Wg(r.spawnedAt),l=r.lastTurnAt?Wg(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?be.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?be.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):be.dim("sess=\u2014"),u=r.pendingTaskId?be.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${be.bold(r.key.agentId)}${be.dim(":"+r.key.channel+":"+r.key.chatId)} ${be.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${be.red("dead:")} ${r.deadReason}`)}});ei.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}=Jg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Bg(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(be.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(be.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(be.red(` ${a}`)),process.exit(1)}console.log(be.green(` killed ${e}:${o}:${t}`))});import{Command as wy}from"commander";import Ue from"chalk";import{existsSync as _r,rmSync as $y}from"fs";import{resolve as Dr}from"path";var Vt=new wy().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Vt.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(Ue.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Ga(e,o,{verbose:n}),r=Date.now()-s;console.log(Ue.green(` \u2713 indexed ${i.docs} doc(s) for ${Ue.bold(e)} in ${r}ms`)),console.log(Ue.dim(` \u2192 ${i.path}`))});Vt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Dr(e.cwd,".agentx","rag");if(!_r(o)){console.log(Ue.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>_r(Dr(o,s,"index.json")));if(n.length===0){console.log(Ue.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ri(s);console.log(` ${Ue.bold(s)} ${i.docs} doc(s) ${Ue.dim(i.path)}`)}});Vt.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=za(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ri(e);i.exists?console.log(Ue.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ue.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ue.bold(i.title)} ${Ue.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ue.dim(i.path)}`),console.log(` ${Ue.dim(i.snippet.slice(0,200))}`)});Vt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Dr(process.cwd(),".agentx","rag",e);if(!_r(o)){console.log(Ue.dim(` no index for ${e} \u2014 nothing to clear`));return}$y(o,{recursive:!0,force:!0}),console.log(Ue.green(` \u2713 cleared index for ${e}`))});oe();import{Command as by}from"commander";import Z from"chalk";import Kt from"prompts";var ft=new by().name("backlog").description("manage the local backlog used by business workSource=backlog");function Wn(e){let o=T(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new xl(n)}}function ky(e){return e?Z.cyan(`${e.type}:${e.project}#${e.iid}`):Z.dim("manual")}function vy(e){return{todo:Z.gray("todo"),doing:Z.yellow("doing"),blocked:Z.red("blocked"),done:Z.green("done")}[e]}ft.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}=Wn(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(Z.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?Z.magenta(`@${n.assignee}`):Z.dim("unassigned");console.log(` ${vy(n.status).padEnd(7)} ${ky(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Z.dim(` ${n.source.url}`))}console.log(),console.log(Z.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});ft.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=Wn(t.config);n.store.findById(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(Z.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Sl([o],i.source,n.config),a=await zi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Z.dim(" sync:"),...c));console.log(a.ok?Z.dim(` synced -> ${a.url??i.source.type}`):Z.yellow(` sync failed: ${a.error}`))}});ft.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=Wn(o.config);t.store.findById(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(Z.green(` done: ${s.title}`)),s.source){let i=await zi(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(Z.dim(" sync:"),...r));console.log(i.ok?Z.dim(` synced -> ${i.url??s.source.type}`):Z.yellow(` sync failed: ${i.error}`))}});ft.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}=Wn(o.config);t.remove(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1)),console.log(Z.green(` removed ${e}`))});ft.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=Wn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(Z.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 Kt({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(Z.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Z.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Sy(o.config):Ey(o.config);w.length?(i=(await Kt({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 Kt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Kt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Kt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Z.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Ay(o.config,i,a):await Ty(o.config,i,a);if(!c.length){console.log(Z.yellow(" no open issues matched"));return}console.log(Z.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=Gi({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?Z.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Kt({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(Z.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?xy(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Gi(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()}}),y=o.store.addMany(p);console.log(Z.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let w of y)console.log(Z.dim(` ${w.id} \u2014 ${w.title}`))});function xy(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Sy(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 Ey(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 Ay(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 Ty(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(Hg)}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(Hg):[]}function Hg(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 jy}from"commander";import W from"chalk";import{existsSync as Oy,readFileSync as Cy}from"fs";import{resolve as Iy}from"path";import Ny from"prompts";oe();function Gg(e){let o=e||Iy(process.cwd(),"agentx.json");return Oy(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Cy(o,"utf-8"))}async function Ry(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 Ny([{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 jo=new jy().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');jo.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: ${Pi})`,Pi).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){jo.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=Di(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=Gg(o.config),s=Ea(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 Ry(o.notify,s),r=o.id||sc(t.matched,o.agent),a=rc({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:ic(o.onError),enabled:!o.disabled}),c=a.onError,l=await ie(d=>Ie(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."))});jo.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=Gg(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=cc(ac(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]])jo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await gc(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."))});jo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ie(t=>{if(!Ot(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Qa(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",lc,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",dc,"reject an agent's pending create/delete request (drops the request)"]])jo.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."))});jo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Di(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 _y}from"commander";import ke from"chalk";import Oo from"chalk";function zg(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 Yg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Vg(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(Oo.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?zg():n?Wc(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(Oo.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={..._t().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await Gc(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(Oo.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(Oo.dim(` not answered${r.why?` (${r.why})`:""}; the card is still waiting`));return}let a=await $s({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(Oo.red(` ${a.error}`)),process.exitCode=1;return}console.log(Oo.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(`${Yg()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(Oo.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(Oo.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(Oo.red(` couldn't reach the daemon at ${Yg()}: ${n?.message??n}`)),process.exitCode=1}})}var Co=new _y("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Dy={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function Kg(){return{root:process.cwd()}}function Pr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Py(e){console.log(` ${ke.cyan(e.key)} ${ke.dim(`[${Dy[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ke.dim(` (later: until ${Pr(e.snoozed_until)})`):""}`),console.log(` ${ke.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ke.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,t)=>console.log(` ${ke.magenta(`${t+1}.`)} ${o}`)),e.expires&&console.log(ke.yellow(` Expires ${Pr(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ke.dim(` ${e.detail}`)),e.source&&console.log(ke.dim(` ${e.source}`)),console.log(ke.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Co.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=Hc(Kg(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ke.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ke.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Py(t),console.log();console.log(ke.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Mr(e,o,t){let n=_t(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ke.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await $s(Kg(),e,o,{force:t.force,note:t.note,laterHours:s,choice:t.choice,text:t.text});if(!i.ok){console.error(ke.red(` ${i.error}`)),process.exitCode=1;return}console.log(ke.green(` \u2713 ${i.message}`))}Co.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)=>Mr(e,"yes",o));Co.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)=>Mr(e,"no",o));Co.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)=>Mr(e,"later",o));Co.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=_t(),t=Jc(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(ke.red(` ${t.error}`)),process.exitCode=1;return}console.log(ke.green(` \u2713 card:${t.card.id} raised; expires ${Pr(t.card.expires)}, then: ${t.card.if_silent}`))});Vg(Co);Co.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=Nl(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=g}}catch(l){console.error(ke.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(o).some(l=>l!==void 0)){let l=await Rl(o);if(!l.success){console.error(ke.red(` ${l.error}`)),process.exitCode=1;return}console.log(ke.green(" \u2713 saved")+(l.reloaded?ke.dim(" (daemon reloaded)"):""))}let i=_t(),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 My}from"commander";import Y from"chalk";oe();rs();Op();var no=new My("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),Ly=["owner","member","guest"];function oi(){let e=90;try{e=T().members.logRetentionDays}catch{}return new ec(process.cwd(),Date.now,e)}var Xg=(e,o=[])=>[...o,e];function em(e){let o=[];try{o=Object.keys(T().agents)}catch{return}let t=e.filter(n=>!o.includes(n));t.length&&(console.log(Y.yellow(` ! not an agent on this machine: ${t.join(", ")}. Agents here: ${o.join(", ")||"none"}.`)),console.log(Y.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var om="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.";async function Jn(e){let o="",t=await ie(n=>{n.people=Array.isArray(n.people)?n.people:[],o=e(n.people)});t.success||(console.error(Y.red(`\u2717 ${(t.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(Y.green(`\u2713 ${o}`)),t.reloaded&&console.log(Y.dim(" daemon hot-reloaded"))}function ti(e,o){let t=e.find(n=>n?.id===o);if(!t)throw new Error(`No person "${o}". See \`agentx people list\`.`);return t.identities=Array.isArray(t.identities)?t.identities:[],t}function tm(e,o){let t=Oi(e),n=Oi(o);return!!t&&!!n&&t.channel===n.channel&&t.value===n.value}function nm(e){console.log(` ${Y.bold(e.id)} ${e.name} ${Y.dim(`\xB7 ${e.role}`)}${e.agents?.length?Y.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}`),console.log(Y.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}no.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let o=T().people;if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(),o.length===0&&(console.log(Y.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${ji}"; senders on other channels are unknown.`)),console.log(Y.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let t of o)nm(t);console.log()});no.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${Ly.join(" | ")}`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",Xg,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",Xg,[]).action(async(e,o)=>{await Jn(t=>{if(t.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);if(o.role==="owner"&&o.agent.length)throw new Error(om);return t.push({id:e,name:o.name,role:o.role,identities:o.identity,agents:o.agent}),`added ${e} (${o.role})${o.agent.length?`, may reach ${o.agent.join(", ")}`:""}`}),em(o.agent)});no.command("allow <id> <agents...>").description('limit a person to these agents (ids, space-separated). "all" lifts the limit').action(async(e,o)=>{let t=o.length===1&&o[0].toLowerCase()==="all";await Jn(n=>{let s=ti(n,e);if(!t&&s.role==="owner")throw new Error(om);return s.agents=t?[]:[...new Set(o)],t?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),t||em(o)});no.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,o)=>{await Jn(t=>{let n=ti(t,e);return n.identities.some(s=>tm(s,o))?`${e} already has ${o}`:(n.identities.push(o),`${o} is now ${e}`)})});no.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,o)=>{await Jn(t=>{let n=ti(t,e),s=n.identities.length;if(n.identities=n.identities.filter(i=>!tm(i,o)),n.identities.length===s)throw new Error(`"${e}" has no identity ${o}.`);return`${o} is no longer ${e}`})});no.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown; every machine of theirs stops at once").action(async e=>{await Jn(t=>(ti(t,e),t.splice(t.findIndex(n=>n?.id===e),1),`removed ${e}`));let o=ql({tokens:new eo,members:oi()},e);o.length&&console.log(Y.green(`\u2713 ended ${o.length} machine(s) of ${e}: ${o.map(t=>t.name).join(", ")}`)),console.log(Y.dim(" If you shared this computer with them on the private network, remove that share too."))});no.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own work page (/member)").option("--url <origin>","address the person opens, e.g. https://my-mac.tailnet-name.ts.net (default: this computer's Tailscale name)").action((e,o)=>{try{let t=Nn(),n=ar(cr(),t);if(n.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the member page: ${n.join(", ")}`," Anyone you share this computer with could open it. Serve only the member paths instead:"," tailscale serve reset (removes every served path; add the phone app's /app lines back if you use it)",` tailscale serve --bg --set-path /member http://127.0.0.1:${t}/member`,` tailscale serve --bg --set-path /api/member http://127.0.0.1:${t}/api/member`].join(`
422
+ `));let s=(o.url?String(o.url):rr()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(s))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${s}`);let i=T().people,r=Ml({tokens:new eo,codes:new ys,members:oi(),people:()=>i},e);if(!r.ok)throw new Error(r.error);console.log(),console.log(` Invite for ${Y.bold(r.person.name)} (${r.person.id})`),console.log(),console.log(" 1. Share this computer with them on your private network, if you have not yet:"),console.log(Y.dim(" Tailscale admin console \u2192 Machines \u2192 this computer \u2192 Share \u2192 send them the link.")),console.log(Y.dim(' Limit what shared users can reach to port 443 in your access rules (see the docs page "Invite a teammate").')),console.log(" 2. Send them this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${Y.cyan(`${s}/member`)}`),console.log(` ${Y.bold(hs(r.code))}`),console.log(),console.log(` 3. When they pair, a card "New machine for ${r.person.name}" asks you to approve that machine.`),console.log(Y.dim(` Their key stops after ${Pl} days; invite again then. Machine id: ${r.tokenId}`)),console.log()}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});no.command("devices [id]").description("the machines paired to people's work pages: state, where from, first and last use").option("--json","machine-readable output").action((e,o)=>{let t=oi().devices(e);if(o.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Y.dim(`
423
423
  No machines${e?` for ${e}`:""}. Run \`agentx people invite <id>\`.
424
- `));return}console.log();for(let n of t){let s=n.state==="active"?V.green("active"):n.state==="pending"?V.yellow("waiting for your approval"):V.red(`removed${n.removedReason?`: ${n.removedReason}`:""}`);console.log(` ${V.cyan(n.tokenId)} ${V.bold(n.personId)} ${n.name} ${s}`),console.log(V.dim(` paired: ${n.createdAt} from ${n.address??"?"}${n.network?` as ${n.network}`:""}${n.lastSeenAt?` last used: ${n.lastSeenAt} from ${n.lastAddress??"?"}`:""}`))}console.log()});no.command("revoke-device <tokenId>").description("end one machine's access at once").action(e=>{let o=Ll({tokens:new eo,members:oi()},e);o||(console.log(V.red(` No machine with id ${e}. See \`agentx people devices\`.`)),process.exit(1)),console.log(V.green(`
424
+ `));return}console.log();for(let n of t){let s=n.state==="active"?Y.green("active"):n.state==="pending"?Y.yellow("waiting for your approval"):Y.red(`removed${n.removedReason?`: ${n.removedReason}`:""}`);console.log(` ${Y.cyan(n.tokenId)} ${Y.bold(n.personId)} ${n.name} ${s}`),console.log(Y.dim(` paired: ${n.createdAt} from ${n.address??"?"}${n.network?` as ${n.network}`:""}${n.lastSeenAt?` last used: ${n.lastSeenAt} from ${n.lastAddress??"?"}`:""}`))}console.log()});no.command("revoke-device <tokenId>").description("end one machine's access at once").action(e=>{let o=Ll({tokens:new eo,members:oi()},e);o||(console.log(Y.red(` No machine with id ${e}. See \`agentx people devices\`.`)),process.exit(1)),console.log(Y.green(`
425
425
  \u2713 Ended ${e} (${o.name}, ${o.personId})
426
- `))});var Qg=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC",Zg=(e,o=100)=>(e??"").replace(/\s+/g," ").trim().slice(0,o);no.command("show <id>").description("one person and what they asked for, on every channel").option("--limit <n>","how many runs to list","20").option("--json","machine-readable output").action((e,o)=>{let t=j().people.find(r=>r.id===e),n=Do({quiet:!0}),s=n?Rl(n,e,Number(o.limit)||20):[],i=n?_l(n,e):[];if(o.json){console.log(JSON.stringify({person:t??null,openRequests:i,runs:s},null,2));return}if(console.log(),t?om(t):console.log(V.dim(` "${e}" is not in the list${e===ji?" (it is the built-in owner of this machine)":""}; showing what is recorded under that id`)),!n){console.log(V.yellow(`
426
+ `))});var Qg=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC",Zg=(e,o=100)=>(e??"").replace(/\s+/g," ").trim().slice(0,o);no.command("show <id>").description("one person and what they asked for, on every channel").option("--limit <n>","how many runs to list","20").option("--json","machine-readable output").action((e,o)=>{let t=T().people.find(r=>r.id===e),n=Do({quiet:!0}),s=n?_l(n,e,Number(o.limit)||20):[],i=n?Dl(n,e):[];if(o.json){console.log(JSON.stringify({person:t??null,openRequests:i,runs:s},null,2));return}if(console.log(),t?nm(t):console.log(Y.dim(` "${e}" is not in the list${e===ji?" (it is the built-in owner of this machine)":""}; showing what is recorded under that id`)),!n){console.log(Y.yellow(`
427
427
  couldn't open .agentx/db.sqlite: run this from the folder that holds agentx.json
428
428
  `));return}if(i.length){console.log(`
429
- Open requests (${i.length})`);for(let r of i)console.log(` ${V.cyan(r.id)} ${V.dim(`${Qg(r.createdAt)} \xB7 ${r.channel} \xB7 ${r.agentId} \xB7 ${r.state.replace(/_/g," ")}`)}
429
+ Open requests (${i.length})`);for(let r of i)console.log(` ${Y.cyan(r.id)} ${Y.dim(`${Qg(r.createdAt)} \xB7 ${r.channel} \xB7 ${r.agentId} \xB7 ${r.state.replace(/_/g," ")}`)}
430
430
  ${Zg(r.text,200)}`)}console.log(`
431
- Latest runs (${s.length})`),s.length===0&&console.log(V.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?V.green("ok"):r.status==="in-flight"?V.yellow("running"):V.red(r.status);console.log(` ${V.dim(Qg(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${Zg(r.messagePreview)}`)}console.log()});rs();Ap();import{Command as My}from"commander";import{existsSync as Ly}from"fs";import he from"chalk";var Xt=new My("requests").description("what you asked agents for that is not finished, oldest first"),tm={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function Lr(){if(!Ly(Xa()))return console.error(he.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=Do();return e?new xa(e):(process.exitCode=1,null)}var ni=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function nm(e){let o=e.state==="needs_attention"?he.red:e.state==="waiting_owner"?he.yellow:he.dim;console.log(` ${he.cyan(e.id)} ${o(`[${tm[e.state]??e.state}]`)} ${he.dim(`${ni(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(he.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(he.red(` ${e.attentionReason}`)),e.evidence&&console.log(he.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(he.dim(` Reason: ${e.closeReason}`))}Xt.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Lr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Li().enabled||console.log(he.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(he.dim(" no open requests"));return}for(let n of t)nm(n);console.log(he.dim(`
432
- ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});Xt.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Lr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(he.red(` no request "${e}"`)),process.exitCode=1;return}nm(t),console.log(he.dim(` Last activity ${ni(t.updatedAt)}${t.closedAt?` \xB7 closed ${ni(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(he.dim(` ${n.kind} ${n.ref} (${ni(n.at)})`))});function sm(e,o,t,n){Xt.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=Lr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(he.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(he.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(he.red(` ${s} is already closed (${tm[c.state]??c.state})`)),process.exitCode=1;return}console.log(he.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}sm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");sm("drop","drop a request you no longer want","--reason <text>","");Xt.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(he.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await Jc(o);if(!n.success){console.error(he.red(` ${n.error}`)),process.exitCode=1;return}console.log(he.green(" \u2713 saved")+(n.reloaded?he.dim(" (daemon reloaded)"):""))}let t=Li();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as qy}from"commander";import Qt from"chalk";oe();var im=new qy("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Ki.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(Qt.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await ie(i=>{n=Ul(i,e,o==="on")});s.success||(console.error(Qt.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Qt.green(`\u2713 ${n}`)),s.reloaded&&console.log(Qt.dim(" daemon hot-reloaded"))}let t=j().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Ki)console.log(` ${n.padEnd(8)} ${t.includes(n)?Qt.green("on"):Qt.dim("off")}`)});import{Command as cw}from"commander";import Zt from"chalk";import ae from"chalk";import Hn from"prompts";import{readFileSync as Uy,writeFileSync as Fy,existsSync as Wy}from"fs";import{resolve as rm}from"path";var Jy=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function By(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function qr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function am(e=".env"){let o=rm(e);if(!Wy(o))return[];let t=Uy(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(Jy);i?n.push({kind:"kv",key:i[1],value:By(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Hy(e){return e.map(o=>o.kind==="kv"?`${o.key}=${qr(o.value)}`:o.raw).join(`
431
+ Latest runs (${s.length})`),s.length===0&&console.log(Y.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?Y.green("ok"):r.status==="in-flight"?Y.yellow("running"):Y.red(r.status);console.log(` ${Y.dim(Qg(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${Zg(r.messagePreview)}`)}console.log()});rs();jp();import{Command as qy}from"commander";import{existsSync as Uy}from"fs";import he from"chalk";var Xt=new qy("requests").description("what you asked agents for that is not finished, oldest first"),sm={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function Lr(){if(!Uy(Xa()))return console.error(he.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=Do();return e?new xa(e):(process.exitCode=1,null)}var ni=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function im(e){let o=e.state==="needs_attention"?he.red:e.state==="waiting_owner"?he.yellow:he.dim;console.log(` ${he.cyan(e.id)} ${o(`[${sm[e.state]??e.state}]`)} ${he.dim(`${ni(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(he.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(he.red(` ${e.attentionReason}`)),e.evidence&&console.log(he.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(he.dim(` Reason: ${e.closeReason}`))}Xt.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Lr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Li().enabled||console.log(he.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(he.dim(" no open requests"));return}for(let n of t)im(n);console.log(he.dim(`
432
+ ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});Xt.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Lr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(he.red(` no request "${e}"`)),process.exitCode=1;return}im(t),console.log(he.dim(` Last activity ${ni(t.updatedAt)}${t.closedAt?` \xB7 closed ${ni(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(he.dim(` ${n.kind} ${n.ref} (${ni(n.at)})`))});function rm(e,o,t,n){Xt.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=Lr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(he.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(he.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(he.red(` ${s} is already closed (${sm[c.state]??c.state})`)),process.exitCode=1;return}console.log(he.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}rm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");rm("drop","drop a request you no longer want","--reason <text>","");Xt.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(he.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await Bc(o);if(!n.success){console.error(he.red(` ${n.error}`)),process.exitCode=1;return}console.log(he.green(" \u2713 saved")+(n.reloaded?he.dim(" (daemon reloaded)"):""))}let t=Li();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as Fy}from"commander";import Qt from"chalk";oe();var am=new Fy("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Ki.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(Qt.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await ie(i=>{n=Ul(i,e,o==="on")});s.success||(console.error(Qt.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Qt.green(`\u2713 ${n}`)),s.reloaded&&console.log(Qt.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Ki)console.log(` ${n.padEnd(8)} ${t.includes(n)?Qt.green("on"):Qt.dim("off")}`)});import{Command as dw}from"commander";import Zt from"chalk";import ae from"chalk";import Hn from"prompts";import{readFileSync as Wy,writeFileSync as Jy,existsSync as By}from"fs";import{resolve as cm}from"path";var Hy=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Gy(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function qr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function lm(e=".env"){let o=cm(e);if(!By(o))return[];let t=Wy(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(Hy);i?n.push({kind:"kv",key:i[1],value:Gy(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function zy(e){return e.map(o=>o.kind==="kv"?`${o.key}=${qr(o.value)}`:o.raw).join(`
433
433
  `)+`
434
- `}function Bn(e,o,t=".env"){let n=rm(t),s=am(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${qr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${qr(o)}`})),Fy(n,Hy(s))}function Ur(e,o=".env"){return am(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var cm="https://t.me/BotFather";async function Gy(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 zy(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 lm(e={}){console.log(),console.log(ae.bold(" Connect Telegram")),console.log(),console.log(ae.dim(` 1. Open ${cm}`)),console.log(ae.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ae.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Hn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&st(cm);let{token:t}=await Hn({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(ae.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gy(t.trim());n||(console.log(ae.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ae.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(ae.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(ae.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Hn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ae.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Hn({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(ae.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Bn(f,t.trim()),process.env[f]=t.trim();let p=await ie(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Ot(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ae.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ae.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ae.dim(` Token stored in .env as ${f}`)),console.log(ae.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ae.dim(" Daemon hot-reloaded.")):console.log(ae.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Hn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ae.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ae.dim(" Waiting up to 90s..."));let w=await zy(t.trim(),9e4);if(!w){console.log(ae.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ae.dim(" agentx config set notifications.destination.channel telegram")),console.log(ae.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ae.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ie(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ae.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ae.green(" \u2713 Default --notify target set")),console.log(ae.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ae.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ae.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Fr from"prompts";import{existsSync as Jr,mkdirSync as Yy,readdirSync as Vy,readFileSync as dm}from"fs";import{resolve as Wr}from"path";var Ky=".agentx/whatsapp-sessions";function Xy(){let e=Wr(process.cwd(),".agentx/daemon.pid");if(!Jr(e))return!1;try{let o=parseInt(dm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Qy(e){if(!Jr(e))return!1;try{return Vy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Zy(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Yy(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(ve.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(ve.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(ve.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(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function gm(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),Xy()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Fr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Wr(process.cwd(),"agentx.json");Jr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(dm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Ky,s=Wr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Fr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Qy(s)&&a){let{keep:l}=await Fr({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Zy(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ie(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as ew}from"crypto";import je from"chalk";import mm from"prompts";var si="agentx-mesh:",ii="//join/";function ow(e){return Buffer.from(e,"utf-8").toString("base64url")}function tw(e){return Buffer.from(e,"base64url").toString("utf-8")}function nw(e){return`${si}${ii}${ow(JSON.stringify(e))}`}function sw(e){if(!e.startsWith(`${si}${ii}`))throw new Error(`Not a mesh invite link \u2014 expected ${si}${ii}\u2026`);let o=e.slice(si.length+ii.length),t=JSON.parse(tw(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 iw(){return ew(32).toString("hex")}function rw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function aw(e){return e?.node?.name||e?.node?.id||"node"}async function pm(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(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Ur("MESH_TOKEN");r||(r=iw(),Bn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await mm({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(je.red(" Aborted")),process.exit(1)),a=d}let l=await ie(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=nw({url:a,token:r,name:aw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function um(e,o={}){let t;try{t=sw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Ur("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await mm({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Bn("MESH_TOKEN",t.token);let s=await ie(i=>{Ie(i,"mesh.enabled",!0);let r=Ot(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),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.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(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var en=new cw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");en.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 lm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});en.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 gm({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var fm=en.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");fm.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 pm({url:e.url,configPath:e.config})});fm.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 um(e,{configPath:o.config})});en.action(()=>{console.log(),console.log(Zt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Zt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Zt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Zt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Zt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Zt.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as lw}from"commander";import ye from"chalk";var Gn=new lw().name("usage").description("token usage analysis and reporting");Gn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=j(),[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(ye.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ye.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ye.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: ${ye.red(String(s.totalErrors))}`),console.log(),console.log(ye.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(` ${ye.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ye.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ye.red(" Daemon not running. Start with: agentx daemon start")):console.log(ye.red(` ${e.message}`))}});Gn.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(ye.red(` Script not found: ${s}`)),console.log(ye.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ye.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ye.red(" Analysis failed. Is Python 3 installed?"))}});Gn.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-O5L4KLGS.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-Y5BSOGQQ.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(ye.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ye.dim("\xB7")} ${d}`);console.log(),console.log(ye.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ye.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(ye.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ye.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ye.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ye.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ye.dim(`${i.days}d`);console.log(` ${ye.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ye.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as dw}from"commander";import xe from"chalk";import{readFileSync as gw}from"fs";import{resolve as mw}from"path";oe();var Ko=new dw().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ko.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{Da(mw(process.cwd(),".env"))}catch{}let o=pw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-7B2GNISR.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function pw(e,o){try{let t=j();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
435
- `)),{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}}}}Ko.command("list").description("list configured boards").action(()=>{try{let e=j();if(!e.boards?.length){console.log(xe.dim(`
434
+ `}function Bn(e,o,t=".env"){let n=cm(t),s=lm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${qr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${qr(o)}`})),Jy(n,zy(s))}function Ur(e,o=".env"){return lm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var dm="https://t.me/BotFather";async function Yy(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 Vy(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 gm(e={}){console.log(),console.log(ae.bold(" Connect Telegram")),console.log(),console.log(ae.dim(` 1. Open ${dm}`)),console.log(ae.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ae.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Hn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&st(dm);let{token:t}=await Hn({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(ae.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Yy(t.trim());n||(console.log(ae.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ae.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(ae.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(ae.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Hn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ae.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Hn({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(ae.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Bn(f,t.trim()),process.env[f]=t.trim();let p=await ie(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Ot(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ae.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ae.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ae.dim(` Token stored in .env as ${f}`)),console.log(ae.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ae.dim(" Daemon hot-reloaded.")):console.log(ae.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Hn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ae.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ae.dim(" Waiting up to 90s..."));let w=await Vy(t.trim(),9e4);if(!w){console.log(ae.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ae.dim(" agentx config set notifications.destination.channel telegram")),console.log(ae.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ae.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ie(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ae.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ae.green(" \u2713 Default --notify target set")),console.log(ae.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ae.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ae.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Fr from"prompts";import{existsSync as Jr,mkdirSync as Ky,readdirSync as Xy,readFileSync as mm}from"fs";import{resolve as Wr}from"path";var Qy=".agentx/whatsapp-sessions";function Zy(){let e=Wr(process.cwd(),".agentx/daemon.pid");if(!Jr(e))return!1;try{let o=parseInt(mm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function ew(e){if(!Jr(e))return!1;try{return Xy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function ow(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Ky(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(ve.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(ve.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(ve.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(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function pm(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),Zy()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Fr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Wr(process.cwd(),"agentx.json");Jr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(mm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Qy,s=Wr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Fr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(ew(s)&&a){let{keep:l}=await Fr({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await ow(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ie(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as tw}from"crypto";import je from"chalk";import um from"prompts";var si="agentx-mesh:",ii="//join/";function nw(e){return Buffer.from(e,"utf-8").toString("base64url")}function sw(e){return Buffer.from(e,"base64url").toString("utf-8")}function iw(e){return`${si}${ii}${nw(JSON.stringify(e))}`}function rw(e){if(!e.startsWith(`${si}${ii}`))throw new Error(`Not a mesh invite link \u2014 expected ${si}${ii}\u2026`);let o=e.slice(si.length+ii.length),t=JSON.parse(sw(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 aw(){return tw(32).toString("hex")}function cw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function lw(e){return e?.node?.name||e?.node?.id||"node"}async function fm(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(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Ur("MESH_TOKEN");r||(r=aw(),Bn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||cw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await um({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(je.red(" Aborted")),process.exit(1)),a=d}let l=await ie(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=iw({url:a,token:r,name:lw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function hm(e,o={}){let t;try{t=rw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Ur("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await um({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Bn("MESH_TOKEN",t.token);let s=await ie(i=>{Ie(i,"mesh.enabled",!0);let r=Ot(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),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.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(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var en=new dw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");en.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 gm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});en.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 pm({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var ym=en.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");ym.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 fm({url:e.url,configPath:e.config})});ym.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 hm(e,{configPath:o.config})});en.action(()=>{console.log(),console.log(Zt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Zt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Zt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Zt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Zt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Zt.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as gw}from"commander";import ye from"chalk";var Gn=new gw().name("usage").description("token usage analysis and reporting");Gn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[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(ye.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ye.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ye.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: ${ye.red(String(s.totalErrors))}`),console.log(),console.log(ye.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(` ${ye.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ye.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ye.red(" Daemon not running. Start with: agentx daemon start")):console.log(ye.red(` ${e.message}`))}});Gn.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(ye.red(` Script not found: ${s}`)),console.log(ye.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ye.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ye.red(" Analysis failed. Is Python 3 installed?"))}});Gn.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-O5L4KLGS.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-QKNNDRP6.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(ye.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ye.dim("\xB7")} ${d}`);console.log(),console.log(ye.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ye.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(ye.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ye.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ye.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ye.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ye.dim(`${i.days}d`);console.log(` ${ye.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ye.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as mw}from"commander";import xe from"chalk";import{readFileSync as pw}from"fs";import{resolve as uw}from"path";oe();var Ko=new mw().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ko.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{Da(uw(process.cwd(),".env"))}catch{}let o=fw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-DJMGIUXC.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function fw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
435
+ `)),{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}}}}Ko.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(xe.dim(`
436
436
  No boards configured.
437
- `));return}console.log();for(let o of e.boards){console.log(` ${xe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(xe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(xe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(xe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Ko.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{zn(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(xe.red(` ${t.message}`)),process.exit(1)}});Ko.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{zn(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(xe.red(` ${t.message}`)),process.exit(1)}});var Br=Ko.command("column").description("manage a board's columns (add / remove / edit / list)");Br.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(gw("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(xe.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(` ${xe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${xe.dim(i)}`)}}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Br.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{zn(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(xe.red(` ${n.message}`)),process.exit(1)}});Br.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{zn(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(xe.red(` ${t.message}`)),process.exit(1)}});Ko.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{zn(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(xe.red(` ${o.message}`)),process.exit(1)}});function zn(e){let{summary:o,backupPath:t}=oo(n=>e(n));console.log(xe.green(`
437
+ `));return}console.log();for(let o of e.boards){console.log(` ${xe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(xe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(xe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(xe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Ko.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{zn(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(xe.red(` ${t.message}`)),process.exit(1)}});Ko.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{zn(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(xe.red(` ${t.message}`)),process.exit(1)}});var Br=Ko.command("column").description("manage a board's columns (add / remove / edit / list)");Br.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(pw("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(xe.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(` ${xe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${xe.dim(i)}`)}}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Br.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{zn(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(xe.red(` ${n.message}`)),process.exit(1)}});Br.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{zn(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(xe.red(` ${t.message}`)),process.exit(1)}});Ko.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{zn(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(xe.red(` ${o.message}`)),process.exit(1)}});function zn(e){let{summary:o,backupPath:t}=oo(n=>e(n));console.log(xe.green(`
438
438
  \u2713 ${o}
439
439
  `)),t&&console.log(xe.dim(` Backup: ${t}`)),console.log(xe.dim(` Restart the dashboard to pick up the change if not auto-reloading.
440
- `))}import{Command as hw}from"commander";import m from"chalk";import Ae from"chalk";import{resolve as uw}from"path";var fw=e=>e||uw(process.cwd(),".agentx/wiki");async function on(e){let{FactLedger:o}=await import("./ledger-CH7R756S.js");return new o(fw(e))}function tn(e){return async(...o)=>{try{await e(...o)}catch(t){t?.name!=="LedgerCorruptError"&&console.error(Ae.red(` ${t?.message??t}`)),process.exitCode=1}}}function hm(e){let o=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");o.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(tn(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await on(n.dir)).list().filter(r=>!n.stale||s(r));if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Ae.dim(" no facts recorded"));return}for(let r of i){let a=r.undated?Ae.yellow(" UNCHECKED"):s(r)?Ae.yellow(" STALE"):"";console.log(` ${Ae.cyan(r.id)} ${Ae.bold(r.subject)} \xB7 ${r.attribute}: ${r.value}${a}`),console.log(Ae.dim(` ${r.volatility} \xB7 ${r.source} \xB7 checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy}`))}})),o.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(tn(async(n,s)=>{let i=(await on(s.dir)).get(n);if(!i){console.error(Ae.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(i,null,2))})),o.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${Ii.join(" | ")}`).option("--ttl-days <n>","days it stays trusted, overriding the class").option("--confirm","a person confirms this value: replace a newer-dated one").option("--dir <path>","wiki directory").action(tn(async n=>{if(n.class&&!qa(n.class)){console.error(Ae.red(` --class must be one of ${Ii.join(", ")}`)),process.exitCode=1;return}let i=(await on(n.dir)).write({subject:n.subject,attribute:n.attribute,value:n.value,source:n.source,verifiedBy:n.by,verifiedAt:n.checkedAt,volatility:n.class,ttlDays:n.ttlDays!==void 0?Number(n.ttlDays):void 0},n.confirm?{confirmedBy:n.by}:{});if(i.status==="contradiction"){let r=i.fact.confirmedBy?`${i.fact.confirmedBy} confirmed it, so only a person can change it`:n.checkedAt?"and this check is not newer":"and this value has no --checked-at";console.log(Ae.yellow(` not replaced: the wiki says "${i.fact.value}" (checked ${i.fact.verifiedAt.slice(0,10)}), ${r}.`)),console.log(i.questionId?Ae.dim(` Queued question ${i.questionId}: agentx wiki questions \xB7 agentx wiki answer ${i.questionId} "<true value>"`):i.questionClosed?Ae.dim(` A person already ${i.questionClosed} this same claim, so it is not asked again.`):Ae.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Ae.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))}));let t=o.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");t.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(tn(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await on(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Ae.dim(" no fact proposals waiting"));return}for(let r of i)console.log(` ${Ae.cyan(r.id)} ${r.status==="pending"?"":Ae.dim(`[${r.status}] `)}${r.claim}`),console.log(Ae.dim(` ${r.agentId} \xB7 ${r.origin} \xB7 ${r.source} \xB7 ${r.verifiedAt.slice(0,10)}`));console.log(Ae.dim(`
441
- Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),t.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(tn(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await on(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Ae.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))})),t.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(tn(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await on(s.dir),n,s.by,s.reason);console.log(Ae.dim(` rejected: ${r.claim}`))}))}import{resolve as q,relative as ym,dirname as wm}from"path";import{execSync as ht}from"child_process";import{writeFileSync as yt,mkdirSync as Io,readFileSync as Yn,readdirSync as yw,renameSync as ri,rmSync as ww,existsSync as Ze}from"fs";function Oe(e,o){return new Ci(wt(e),void 0,o||"graph")}function wt(e){return e||q(process.cwd(),".agentx/wiki")}function Gr(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var te=new hw().name("wiki").description("wiki knowledge base management");hm(te);te.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=Oe(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Gr(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});te.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let o=Oe(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let r of t){let c=o.getAgentWiki(r).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(r)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(r)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-CH7R756S.js"),i=s(wt(e.dir));if(n+=i.length,i.length>0){console.log(` ${m.cyan("facts")}: ${m.yellow(`${i.length} contradiction(s)`)}`);for(let r of i)console.log(` [!] ${m.dim(r.type)} ${r.articles[0]}: ${r.message}`)}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});te.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=Oe(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=q(process.cwd(),".agentx/graph");return Ze(u)?new Po({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[f,p]of Object.entries(u.entries))r.set(f,p.path)}catch{}let a,c=u=>{let f=u.meta?.intentPath;if(Array.isArray(f)&&f.every(w=>typeof w=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),y=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(y)},l=(u,f)=>{let p=new Map;for(let w of u){let k=f.find(S=>S.id===w);if(!k)continue;let b=c(k);if(!b?.length)continue;let $=b.join("/"),E=p.get($);E?E.n++:p.set($,{path:b,n:1})}if(p.size===0)return;let y;for(let w of p.values())(!y||w.n>y.n)&&(y=w);return y?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter(v=>!f||(v.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let v of p.slice(0,3))console.log(m.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let y=t.getAgentWiki(u),w=y.rebuildIndex(),k=y.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
440
+ `))}import{Command as ww}from"commander";import m from"chalk";import Ae from"chalk";import{resolve as hw}from"path";var yw=e=>e||hw(process.cwd(),".agentx/wiki");async function on(e){let{FactLedger:o}=await import("./ledger-CH7R756S.js");return new o(yw(e))}function tn(e){return async(...o)=>{try{await e(...o)}catch(t){t?.name!=="LedgerCorruptError"&&console.error(Ae.red(` ${t?.message??t}`)),process.exitCode=1}}}function wm(e){let o=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");o.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(tn(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await on(n.dir)).list().filter(r=>!n.stale||s(r));if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Ae.dim(" no facts recorded"));return}for(let r of i){let a=r.undated?Ae.yellow(" UNCHECKED"):s(r)?Ae.yellow(" STALE"):"";console.log(` ${Ae.cyan(r.id)} ${Ae.bold(r.subject)} \xB7 ${r.attribute}: ${r.value}${a}`),console.log(Ae.dim(` ${r.volatility} \xB7 ${r.source} \xB7 checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy}`))}})),o.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(tn(async(n,s)=>{let i=(await on(s.dir)).get(n);if(!i){console.error(Ae.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(i,null,2))})),o.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${Ii.join(" | ")}`).option("--ttl-days <n>","days it stays trusted, overriding the class").option("--confirm","a person confirms this value: replace a newer-dated one").option("--dir <path>","wiki directory").action(tn(async n=>{if(n.class&&!qa(n.class)){console.error(Ae.red(` --class must be one of ${Ii.join(", ")}`)),process.exitCode=1;return}let i=(await on(n.dir)).write({subject:n.subject,attribute:n.attribute,value:n.value,source:n.source,verifiedBy:n.by,verifiedAt:n.checkedAt,volatility:n.class,ttlDays:n.ttlDays!==void 0?Number(n.ttlDays):void 0},n.confirm?{confirmedBy:n.by}:{});if(i.status==="contradiction"){let r=i.fact.confirmedBy?`${i.fact.confirmedBy} confirmed it, so only a person can change it`:n.checkedAt?"and this check is not newer":"and this value has no --checked-at";console.log(Ae.yellow(` not replaced: the wiki says "${i.fact.value}" (checked ${i.fact.verifiedAt.slice(0,10)}), ${r}.`)),console.log(i.questionId?Ae.dim(` Queued question ${i.questionId}: agentx wiki questions \xB7 agentx wiki answer ${i.questionId} "<true value>"`):i.questionClosed?Ae.dim(` A person already ${i.questionClosed} this same claim, so it is not asked again.`):Ae.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Ae.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))}));let t=o.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");t.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(tn(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await on(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Ae.dim(" no fact proposals waiting"));return}for(let r of i)console.log(` ${Ae.cyan(r.id)} ${r.status==="pending"?"":Ae.dim(`[${r.status}] `)}${r.claim}`),console.log(Ae.dim(` ${r.agentId} \xB7 ${r.origin} \xB7 ${r.source} \xB7 ${r.verifiedAt.slice(0,10)}`));console.log(Ae.dim(`
441
+ Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),t.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(tn(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await on(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Ae.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))})),t.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(tn(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await on(s.dir),n,s.by,s.reason);console.log(Ae.dim(` rejected: ${r.claim}`))}))}import{resolve as q,relative as $m,dirname as bm}from"path";import{execSync as ht}from"child_process";import{writeFileSync as yt,mkdirSync as Io,readFileSync as Yn,readdirSync as $w,renameSync as ri,rmSync as bw,existsSync as Ze}from"fs";function Oe(e,o){return new Ci(wt(e),void 0,o||"graph")}function wt(e){return e||q(process.cwd(),".agentx/wiki")}function Gr(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var te=new ww().name("wiki").description("wiki knowledge base management");wm(te);te.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=Oe(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Gr(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});te.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let o=Oe(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let r of t){let c=o.getAgentWiki(r).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(r)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(r)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-CH7R756S.js"),i=s(wt(e.dir));if(n+=i.length,i.length>0){console.log(` ${m.cyan("facts")}: ${m.yellow(`${i.length} contradiction(s)`)}`);for(let r of i)console.log(` [!] ${m.dim(r.type)} ${r.articles[0]}: ${r.message}`)}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});te.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=Oe(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=q(process.cwd(),".agentx/graph");return Ze(u)?new Po({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[f,p]of Object.entries(u.entries))r.set(f,p.path)}catch{}let a,c=u=>{let f=u.meta?.intentPath;if(Array.isArray(f)&&f.every(w=>typeof w=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),y=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(y)},l=(u,f)=>{let p=new Map;for(let w of u){let k=f.find(S=>S.id===w);if(!k)continue;let b=c(k);if(!b?.length)continue;let $=b.join("/"),E=p.get($);E?E.n++:p.set($,{path:b,n:1})}if(p.size===0)return;let y;for(let w of p.values())(!y||w.n>y.n)&&(y=w);return y?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter(v=>!f||(v.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let v of p.slice(0,3))console.log(m.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let y=t.getAgentWiki(u),w=y.rebuildIndex(),k=y.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
442
442
  ${v.content}
443
443
  --- END ENTRY ---`).join(`
444
444
 
445
- `),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:P,defaultSources:J,recordsFromEntries:L}=await import("./facts-ROUMKS7I.js");if(!a){let B=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&B.add(Se.meta.title);a=[...B]}let G=v(p.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ue=L(p);if(G.length>0||ue.length>0){let B=J(),{records:Ce,results:Se}=G.length>0?await R(G,{sources:B}):{records:[],results:[]},M=I([...ue,...Ce]);$=C(M);let Qe=[...ue.length>0?[`entries:${ue.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Qe.length?` (${Qe.join(" ")})`:""}`));for(let Ee of P(Se,B))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=yc(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${Gr(o)}`));let S=q(y.baseDir,"_tmp");Io(S,{recursive:!0});let x=q(S,"absorb-prompt.txt");yt(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=ht(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:xt({...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,C=[],P=R.indexOf("{"),J=R.indexOf("["),L=P>=0&&(J<0||P<J)?P:J;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],ue=G==="{"?"}":"]",B=0,Ce=-1;for(let M=L;M<R.length;M++)if(R[M]===G)B++;else if(R[M]===ue&&(B--,B===0)){Ce=M+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let Se=R.slice(L,Ce);try{let M=JSON.parse(Se);Array.isArray(M)?I=M:(I=M.articles||[],C=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${Se.slice(0,300)}`));continue}for(let M of I){let Qe=new Date().toISOString().slice(0,10),Ee=l(M.sources||[],p);y.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:Qe,lastUpdated:Qe,sources:M.sources||[],graphPath:Ee},M.content,u);let ot=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("+")} ${ot}${M.path}: ${M.title}${m.dim(_)}`);let $e=(M.tags||[]).slice(0,4).join(", ");$e&&console.log(m.dim(` tags: ${$e}`)),Ee?.length&&(console.log(m.dim(` graphPath: ${Ee.join(" \u203A ")}`)),d++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let M of C)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Qe=new M(wt(e.dir)).add(C.map(Ee=>({kind:"article",agentId:u,path:"",subject:String(Ee).slice(0,120),question:`No article yet for: ${String(Ee).slice(0,160)}`})));Qe.added>0&&console.log(m.dim(` queued ${Qe.added} for follow-up (agentx wiki questions)`))}catch{}}y.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()});te.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=$w(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-UFVMO3IT.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!Ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(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-PBPF45GN.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Ze(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 y=p[0];y&&console.log(m.dim(` most recurrent (${y.occurrences} sessions, ${y.failure.runs} runs): ${y.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await wc({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(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 ai=te.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ci(e){return e?q(e):q(process.cwd(),".agentx","wiki")}ai.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(ci(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}`))}});ai.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(ci(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(`
445
+ `),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:P,defaultSources:J,recordsFromEntries:L}=await import("./facts-ROUMKS7I.js");if(!a){let B=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&B.add(Se.meta.title);a=[...B]}let G=v(p.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),ue=L(p);if(G.length>0||ue.length>0){let B=J(),{records:Ce,results:Se}=G.length>0?await R(G,{sources:B}):{records:[],results:[]},M=I([...ue,...Ce]);$=C(M);let Qe=[...ue.length>0?[`entries:${ue.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Qe.length?` (${Qe.join(" ")})`:""}`));for(let Ee of P(Se,B))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=wc(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${Gr(o)}`));let S=q(y.baseDir,"_tmp");Io(S,{recursive:!0});let x=q(S,"absorb-prompt.txt");yt(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=ht(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:xt({...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,C=[],P=R.indexOf("{"),J=R.indexOf("["),L=P>=0&&(J<0||P<J)?P:J;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],ue=G==="{"?"}":"]",B=0,Ce=-1;for(let M=L;M<R.length;M++)if(R[M]===G)B++;else if(R[M]===ue&&(B--,B===0)){Ce=M+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let Se=R.slice(L,Ce);try{let M=JSON.parse(Se);Array.isArray(M)?I=M:(I=M.articles||[],C=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${Se.slice(0,300)}`));continue}for(let M of I){let Qe=new Date().toISOString().slice(0,10),Ee=l(M.sources||[],p);y.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:Qe,lastUpdated:Qe,sources:M.sources||[],graphPath:Ee},M.content,u);let ot=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("+")} ${ot}${M.path}: ${M.title}${m.dim(_)}`);let $e=(M.tags||[]).slice(0,4).join(", ");$e&&console.log(m.dim(` tags: ${$e}`)),Ee?.length&&(console.log(m.dim(` graphPath: ${Ee.join(" \u203A ")}`)),d++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let M of C)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Qe=new M(wt(e.dir)).add(C.map(Ee=>({kind:"article",agentId:u,path:"",subject:String(Ee).slice(0,120),question:`No article yet for: ${String(Ee).slice(0,160)}`})));Qe.added>0&&console.log(m.dim(` queued ${Qe.added} for follow-up (agentx wiki questions)`))}catch{}}y.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()});te.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=kw(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-27LHBY44.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!Ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(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-PBPF45GN.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Ze(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 y=p[0];y&&console.log(m.dim(` most recurrent (${y.occurrences} sessions, ${y.failure.runs} runs): ${y.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await $c({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(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 ai=te.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ci(e){return e?q(e):q(process.cwd(),".agentx","wiki")}ai.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(ci(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}`))}});ai.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(ci(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(`
446
446
  `).map(s=>` ${s}`).join(`
447
- `)),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>)`))}});ai.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-KLA3DBKX.js"),n=t(ci(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`))});ai.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-KLA3DBKX.js"),n=t(ci(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 $w(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)}te.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",q(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-N3BRQU6S.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Oe(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(`
447
+ `)),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>)`))}});ai.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-7BCIFXE7.js"),n=t(ci(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`))});ai.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-7BCIFXE7.js"),n=t(ci(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 kw(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)}te.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",q(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-QHUQDZ3P.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Oe(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(`
448
448
  `)||"_(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:**
449
449
 
450
450
  ${S.answer}
@@ -461,14 +461,14 @@ Q: ${_.q}
461
461
  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(`
462
462
  `),E=q(a.baseDir,"_tmp");Io(E,{recursive:!0});let S=q(E,`interview-${t().slice(0,8)}.txt`);yt(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"`,$e=ht(_,{env:xt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let so=JSON.parse($e);x=String(so.result||so.content||"")}catch{x=$e}}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 C={};for(let _ of I[1].split(`
463
463
  `)){let $e=_.match(/^(\w+):\s*(.+)$/);$e&&(C[$e[1]]=$e[2].trim().replace(/^"(.*)"$/,"$1"))}let P=I[2],J=C.title||g,L=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ue=`${{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: ${ue}`)),console.log(),console.log(x),console.log();let B=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/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 Ce=P,Se={title:J,type:C.type||d,related:C.related?C.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:C.tags?C.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:C.access||"public",created:C.created||new Date().toISOString().slice(0,10),lastUpdated:C.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let _=process.env.EDITOR||"vi",$e=q(E,`draft-${t().slice(0,8)}.md`);yt($e,x);try{ht(`${_} '${$e}'`,{stdio:"inherit"});let Ei=Yn($e,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Ei){let _o={};for(let yn of Ei[1].split(`
464
- `)){let Ai=yn.match(/^(\w+):\s*(.+)$/);Ai&&(_o[Ai[1]]=Ai[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=Ei[2],Se={...Se,title:_o.title||Se.title,type:_o.type||Se.type,access:_o.access||Se.access,related:_o.related?_o.related.replace(/^\[|\]$/g,"").split(",").map(yn=>yn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:_o.tags?_o.tags.replace(/^\[|\]$/g,"").split(",").map(yn=>yn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(so){console.log(m.red(` editor failed: ${so.message}`));return}}if(!a.writeArticle(ue,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ue} saved.`));let Qe=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let ot=Qe.filter(_=>!Ee.has(_.toLowerCase()));if(ot.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of ot.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});te.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-N3BRQU6S.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Oe(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=Yn(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);r=[];for(let y of p){let w=y.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,y;if(r){let G=r[f];if(!G)break;p=G.q,y=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;y=""}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(ue=>`${ue.title} [${ue.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
465
- `)),console.log(m.dim(" citations: "+G))}r||(y=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+y);let k={q:p,answer:w.answer,citations:w.citations,verdict:y},b=y.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=kw(x.content,$,E,x.meta.title,x.meta.type),R=q(i.baseDir,"_tmp");Io(R,{recursive:!0});let I=q(R,`quiz-patch-${t().slice(0,8)}.txt`);yt(I,v);let C="";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"`,ue=ht(G,{env:xt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(ue);C=String(Ce.result||Ce.content||"")}catch{C=ue}let B=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(C=B[1].trim()),C=C.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
464
+ `)){let Ai=yn.match(/^(\w+):\s*(.+)$/);Ai&&(_o[Ai[1]]=Ai[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=Ei[2],Se={...Se,title:_o.title||Se.title,type:_o.type||Se.type,access:_o.access||Se.access,related:_o.related?_o.related.replace(/^\[|\]$/g,"").split(",").map(yn=>yn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:_o.tags?_o.tags.replace(/^\[|\]$/g,"").split(",").map(yn=>yn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(so){console.log(m.red(` editor failed: ${so.message}`));return}}if(!a.writeArticle(ue,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ue} saved.`));let Qe=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let ot=Qe.filter(_=>!Ee.has(_.toLowerCase()));if(ot.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of ot.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});te.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-QHUQDZ3P.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Oe(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=Yn(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);r=[];for(let y of p){let w=y.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,y;if(r){let G=r[f];if(!G)break;p=G.q,y=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;y=""}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(ue=>`${ue.title} [${ue.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
465
+ `)),console.log(m.dim(" citations: "+G))}r||(y=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+y);let k={q:p,answer:w.answer,citations:w.citations,verdict:y},b=y.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=xw(x.content,$,E,x.meta.title,x.meta.type),R=q(i.baseDir,"_tmp");Io(R,{recursive:!0});let I=q(R,`quiz-patch-${t().slice(0,8)}.txt`);yt(I,v);let C="";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"`,ue=ht(G,{env:xt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(ue);C=String(Ce.result||Ce.content||"")}catch{C=ue}let B=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(C=B[1].trim()),C=C.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
466
466
  `).length,J=C.split(`
467
467
  `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${J} lines (${J-P>=0?"+":""}${J-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)},C,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 y=d[p];f.push(`## ${p+1}. Q: ${y.q}`,"",`**A:** ${y.answer}`,"",`**Citations:** ${y.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${y.verdict}\``+(y.patched?` \u2192 patched \`${y.patched}\``:""),"")}yt(e.out,f.join(`
468
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});te.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=Oe(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=km(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{ht(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(g.some(f=>!d.includes(f))||d.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});te.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=Oe(n.dir),a;try{a=r.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=km(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=bw(l.content,l.meta.title,l.meta.type,t),d=q(a.baseDir,"_tmp");Io(d,{recursive:!0});let u=q(d,`patch-${i().slice(0,8)}.txt`);yt(u,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let S=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=ht(S,{env:xt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(x);f=String(R.result||R.content||"")}catch{f=x}let v=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(f=v[1].trim()),f=f.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let p=l.content.split(`
468
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});te.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=Oe(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=xm(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{ht(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,g=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(g.some(f=>!d.includes(f))||d.some(f=>!g.includes(f)))&&(s.writeArticle(i,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});te.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=Oe(n.dir),a;try{a=r.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=xm(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=vw(l.content,l.meta.title,l.meta.type,t),d=q(a.baseDir,"_tmp");Io(d,{recursive:!0});let u=q(d,`patch-${i().slice(0,8)}.txt`);yt(u,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let S=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=ht(S,{env:xt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(x);f=String(R.result||R.content||"")}catch{f=x}let v=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(f=v[1].trim()),f=f.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let p=l.content.split(`
469
469
  `).length,y=f.split(`
470
- `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${y} lines (${y-p>=0?"+":""}${y-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let w=!!n.yes;if(!w){let S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),w=x==="y"||x==="yes"}if(!w){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let E=(l.meta.related||[]).filter(S=>!b.includes(S));E.length&&console.log(m.dim(` (pruned stale related: ${E.slice(0,3).join(", ")}${E.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function km(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function bw(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
471
- `)}function kw(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
470
+ `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${y} lines (${y-p>=0?"+":""}${y-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let w=!!n.yes;if(!w){let S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),w=x==="y"||x==="yes"}if(!w){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let E=(l.meta.related||[]).filter(S=>!b.includes(S));E.length&&console.log(m.dim(` (pruned stale related: ${E.slice(0,3).join(", ")}${E.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function xm(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function vw(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
471
+ `)}function xw(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
472
472
 
473
473
  ${t}
474
474
 
@@ -481,8 +481,8 @@ Incorporate it into the most relevant existing section, or create a short new se
481
481
  ${t}
482
482
 
483
483
  Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${t}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${n}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",i[o]||`Make a minimal edit per: ${t}`,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
484
- `)}te.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,g=0;for(let d of t){let u=q(s,"agents",d);if(!Ze(u))continue;let f=q(u,i),p=r.map(b=>({mode:b,dir:q(u,b)})).filter(b=>Ze(b.dir));if(p.length===0)continue;let y=new Map;Hr(f,b=>{let $=ym(f,b);if($.startsWith("_")||$.startsWith("raw/")||$.includes("_tmp/"))return;let E=$m(Yn(b,"utf-8"));E?.meta.title&&y.set(E.meta.title.trim().toLowerCase(),{relPath:$,type:E.meta.type,lastUpdated:E.meta.lastUpdated||""})});let w=[];for(let b of p)Hr(b.dir,$=>{let E=ym(b.dir,$);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=$m(Yn($,"utf-8"));S?.meta.title&&w.push({mode:b.mode,relPath:E,absPath:$,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${k}`));for(let b of w){let $=b.title.toLowerCase(),E=y.get($),S;E?!E.type&&b.type||!!E.type==!!b.type&&b.lastUpdated&&E.lastUpdated&&b.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),v=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${v} ${x} ${m.dim(b.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${E.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let I=q(f,b.relPath);Ze(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),bm(u,b),g++):(Io(wm(I),{recursive:!0}),ri(b.absPath,I),y.set($,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let I=q(f,E.relPath);if(Ze(I)){let C=q(u,"_versions",E.relPath.replace(/\.md$/,""));Io(C,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");ri(I,q(C,`${P}.md`))}Io(wm(I),{recursive:!0}),ri(b.absPath,I),y.set($,{relPath:E.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else bm(u,b),g++}catch(I){console.log(m.red(` ! ${S} failed: ${I.message?.slice(0,120)}`))}}if(n){for(let b of p)try{ww(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Hr(e,o){if(Ze(e))for(let t of yw(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?Hr(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function $m(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
485
- `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function bm(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));Io(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");ri(o.absPath,q(t,`${n}.md`))}te.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let y=g.baseDir,w=q(y,"_tmp");Io(w,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),$=xw(b),E=q(w,"migrate-prompt.txt");yt(E,$);let S;try{let x=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=ht(x,{env:xt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(v),C=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!C)throw new Error("no JSON array in classifier response");S=JSON.parse(C[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let v=S.find(L=>L.path===x.path),R=vw(v?.type);if(!v||!R){console.log(m.yellow(` ? ${x.path}: unclassified${v?` (got "${v.type}")`:""}`));continue}let I=g.extractWikilinks(x.content),C={...x.meta,type:R.type,related:I.length?I:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=I.length?m.dim(` \u2192 ${I.slice(0,3).join(", ")}${I.length>3?", \u2026":""}`):"",J=R.alias?m.dim(` (from "${R.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+R.type+"]")}${J} ${x.path}${P}`),i&&(g.writeArticle(x.path,C,x.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function vw(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function xw(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
484
+ `)}te.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,g=0;for(let d of t){let u=q(s,"agents",d);if(!Ze(u))continue;let f=q(u,i),p=r.map(b=>({mode:b,dir:q(u,b)})).filter(b=>Ze(b.dir));if(p.length===0)continue;let y=new Map;Hr(f,b=>{let $=$m(f,b);if($.startsWith("_")||$.startsWith("raw/")||$.includes("_tmp/"))return;let E=km(Yn(b,"utf-8"));E?.meta.title&&y.set(E.meta.title.trim().toLowerCase(),{relPath:$,type:E.meta.type,lastUpdated:E.meta.lastUpdated||""})});let w=[];for(let b of p)Hr(b.dir,$=>{let E=$m(b.dir,$);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=km(Yn($,"utf-8"));S?.meta.title&&w.push({mode:b.mode,relPath:E,absPath:$,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${k}`));for(let b of w){let $=b.title.toLowerCase(),E=y.get($),S;E?!E.type&&b.type||!!E.type==!!b.type&&b.lastUpdated&&E.lastUpdated&&b.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),v=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${v} ${x} ${m.dim(b.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${E.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let I=q(f,b.relPath);Ze(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),vm(u,b),g++):(Io(bm(I),{recursive:!0}),ri(b.absPath,I),y.set($,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let I=q(f,E.relPath);if(Ze(I)){let C=q(u,"_versions",E.relPath.replace(/\.md$/,""));Io(C,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");ri(I,q(C,`${P}.md`))}Io(bm(I),{recursive:!0}),ri(b.absPath,I),y.set($,{relPath:E.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else vm(u,b),g++}catch(I){console.log(m.red(` ! ${S} failed: ${I.message?.slice(0,120)}`))}}if(n){for(let b of p)try{bw(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Hr(e,o){if(Ze(e))for(let t of $w(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?Hr(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function km(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
485
+ `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function vm(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));Io(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");ri(o.absPath,q(t,`${n}.md`))}te.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let y=g.baseDir,w=q(y,"_tmp");Io(w,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),$=Ew(b),E=q(w,"migrate-prompt.txt");yt(E,$);let S;try{let x=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=ht(x,{env:xt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(v),C=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!C)throw new Error("no JSON array in classifier response");S=JSON.parse(C[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let v=S.find(L=>L.path===x.path),R=Sw(v?.type);if(!v||!R){console.log(m.yellow(` ? ${x.path}: unclassified${v?` (got "${v.type}")`:""}`));continue}let I=g.extractWikilinks(x.content),C={...x.meta,type:R.type,related:I.length?I:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=I.length?m.dim(` \u2192 ${I.slice(0,3).join(", ")}${I.length>3?", \u2026":""}`):"",J=R.alias?m.dim(` (from "${R.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+R.type+"]")}${J} ${x.path}${P}`),i&&(g.writeArticle(x.path,C,x.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Sw(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function Ew(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
486
486
  title: "${t.meta.title}"
487
487
  tags: [${i}]
488
488
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -522,51 +522,51 @@ Output (JSON array, one entry per input article, same order):
522
522
  [
523
523
  {"path": "path/to/article.md", "type": "project"},
524
524
  ...
525
- ]`}te.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(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()});te.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||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-ZBNH2DMN.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(),Hl(o,t,e.agent,n,e.mode)});te.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-E4FYHBIC.js"),c=Oe(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))),y=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(y(f)));for(let w of u)console.log(y(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
525
+ ]`}te.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(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()});te.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||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-PTBPLRVQ.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(),Hl(o,t,e.agent,n,e.mode)});te.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-PUTTNNVU.js"),c=Oe(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))),y=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(y(f)));for(let w of u)console.log(y(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
526
526
  ${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(`
527
- ${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."))});te.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-N3BRQU6S.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=q(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()}});te.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=Oe(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()});te.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=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Po({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(),y=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=y.get(x);if(!v)continue;let R=String(v.meta?.sender??""),I=s.fingerprint({text:v.content,channel:v.source,sender:R}),C=r.get(I);if(!C?.length)continue;let P=C.join("/"),J=E.get(P);J?J.n++:E.set(P,{path:C,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()});te.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=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-ZBNH2DMN.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()});te.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||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Ci(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,y=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);y+=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:Gr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(y/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()});te.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?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Ze(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Sw(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});te.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-E4FYHBIC.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(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 C=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(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,C.answers);for(let J of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&J.needsHuman||(e.ask&&J.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:I.meta.title,field:J.field,tier:J.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${J.label}?`}),p.push({tier:J.tier,need:J.field,how:J.needsHuman?m.yellow("ask"):J.sources.join("/"),uncertain:J.uncertain?"?":"",agent:x,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(wt(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 ${y.added} question(s) for a person (${y.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&y.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-ZBNH2DMN.js"),C=I(),P=C?.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 J=R.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
527
+ ${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."))});te.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-QHUQDZ3P.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=q(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()}});te.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=Oe(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()});te.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=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Po({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(),y=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=y.get(x);if(!v)continue;let R=String(v.meta?.sender??""),I=s.fingerprint({text:v.content,channel:v.source,sender:R}),C=r.get(I);if(!C?.length)continue;let P=C.join("/"),J=E.get(P);J?J.n++:E.set(P,{path:C,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()});te.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=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-PTBPLRVQ.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()});te.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||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Ci(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,y=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);y+=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:Gr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(y/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()});te.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?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Ze(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Aw(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});te.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-PUTTNNVU.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(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 C=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(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,C.answers);for(let J of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&J.needsHuman||(e.ask&&J.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:I.meta.title,field:J.field,tier:J.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${J.label}?`}),p.push({tier:J.tier,need:J.field,how:J.needsHuman?m.yellow("ask"):J.sources.join("/"),uncertain:J.uncertain?"?":"",agent:x,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(wt(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 ${y.added} question(s) for a person (${y.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&y.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-PTBPLRVQ.js"),C=I(),P=C?.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 J=R.slice(0,10).map(B=>`\u2022 ${B.question}`).join(`
528
528
  `),L=R.length>10?`
529
529
  \u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
530
530
  ${J}${L}
531
531
 
532
- agentx wiki questions`,ue=C?.daemon?.port??C?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ue}/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(B.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});te.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-E4FYHBIC.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),y=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],x=!1;e:for(let C of p){let P=f.getAgentWiki(C);for(let J of P.listArticles(C)){if($>=y)break e;if(J.meta.type!=="person")continue;let L=P.readArticle(J.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:J.path}],features:{agent:C,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(B.length===0)continue;let{records:Ce,results:Se}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Qe=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(Qe.length===0)continue;let{content:Ee,edits:ot}=u(L.content,Qe[0],B);if(ot.length!==0){for(let _ of ot)S.push({agent:C,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(J.path,L.meta,Ee,C)?E++:console.log(m.red(` could not write ${J.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(C=>Math.max(C.length,...S.map(P=>String(P[C]).length))),I=C=>C.map((P,J)=>String(P).padEnd(R[J])).join(" ");console.log(),console.log(m.bold(I(v)));for(let C of S)console.log(I(v.map(P=>C[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.")))});te.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(wt(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`))});te.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(wt(t.dir)),a=r.list().find(y=>(y.id===e||y.id.startsWith(e))&&y.status!=="open"&&y.kind==="contradiction");if(a&&!r.list("open").some(y=>y.id===e||y.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let y=r.resolve(e,"dismissed");console.log(y?m.dim(` dismissed: ${y.question}`):m.red(` no question matching "${e}"`))}catch(y){console.log(m.red(` ${y?.message??y}`)),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(y=>y.id===e||y.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:y}=await import("./ledger-CH7R756S.js"),w=new y(wt(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(y){console.log(m.red(` ${y?.message??y}`)),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=Oe(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}`))});te.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-E4FYHBIC.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=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),y=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,y),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 ue=G.answers;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:ue.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}),C=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:I,failures:S,elapsed:C},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 J=v.positiveMeans;if(console.log(m.dim(` positives avg: worth ${J.worth.toFixed(2)} \xB7 durability ${J.durability.toFixed(2)} \xB7 typeConf ${J.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}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:ue}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ue.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 B=ue.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];B&&console.log(m.dim(` Best recall available: ${P(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${P(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});te.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=q(process.cwd(),e);Ze(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Ze(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(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 Sw(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"}Ip();import{Command as Ew}from"commander";import D from"chalk";import{resolve as li}from"path";import{existsSync as Aw}from"fs";oe();var nn=new Ew().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");nn.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=j();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 Po({baseDir:li(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 y=r[p],w=cs(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(y.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Tw(y,a,c),b=null;try{b=await jw(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{Ow(i,y,a,c,t),i.updateClassificationStatus(y.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(y.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()});nn.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=j();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=li(process.cwd(),o.graph.baseDir);if(!Aw(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 Po({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()});nn.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=j();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 Po({baseDir:li(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 C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);d=(await C.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 y=p?r:l,w=new Map;y.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 Tw(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(`
532
+ agentx wiki questions`,ue=C?.daemon?.port??C?.port??18800;try{let B=await fetch(`http://127.0.0.1:${ue}/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(B.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).slice(0,80)}) \u2014 questions are still queued.`))}}}}});te.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-PUTTNNVU.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),y=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],x=!1;e:for(let C of p){let P=f.getAgentWiki(C);for(let J of P.listArticles(C)){if($>=y)break e;if(J.meta.type!=="person")continue;let L=P.readArticle(J.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:J.path}],features:{agent:C,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(B.length===0)continue;let{records:Ce,results:Se}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Qe=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(Qe.length===0)continue;let{content:Ee,edits:ot}=u(L.content,Qe[0],B);if(ot.length!==0){for(let _ of ot)S.push({agent:C,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(J.path,L.meta,Ee,C)?E++:console.log(m.red(` could not write ${J.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(C=>Math.max(C.length,...S.map(P=>String(P[C]).length))),I=C=>C.map((P,J)=>String(P).padEnd(R[J])).join(" ");console.log(),console.log(m.bold(I(v)));for(let C of S)console.log(I(v.map(P=>C[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.")))});te.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(wt(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`))});te.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(wt(t.dir)),a=r.list().find(y=>(y.id===e||y.id.startsWith(e))&&y.status!=="open"&&y.kind==="contradiction");if(a&&!r.list("open").some(y=>y.id===e||y.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let y=r.resolve(e,"dismissed");console.log(y?m.dim(` dismissed: ${y.question}`):m.red(` no question matching "${e}"`))}catch(y){console.log(m.red(` ${y?.message??y}`)),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(y=>y.id===e||y.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:y}=await import("./ledger-CH7R756S.js"),w=new y(wt(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(y){console.log(m.red(` ${y?.message??y}`)),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=Oe(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}`))});te.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-PUTTNNVU.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=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),y=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,y),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 ue=G.answers;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:ue.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}),C=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:I,failures:S,elapsed:C},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 J=v.positiveMeans;if(console.log(m.dim(` positives avg: worth ${J.worth.toFixed(2)} \xB7 durability ${J.durability.toFixed(2)} \xB7 typeConf ${J.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}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:ue}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${ue.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 B=ue.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];B&&console.log(m.dim(` Best recall available: ${P(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${P(B.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});te.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=q(process.cwd(),e);Ze(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Ze(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(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 Aw(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"}Rp();import{Command as Tw}from"commander";import D from"chalk";import{resolve as li}from"path";import{existsSync as jw}from"fs";oe();var nn=new Tw().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");nn.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=T();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 Po({baseDir:li(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 y=r[p],w=cs(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(y.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Ow(y,a,c),b=null;try{b=await Cw(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{Iw(i,y,a,c,t),i.updateClassificationStatus(y.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(y.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()});nn.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=T();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=li(process.cwd(),o.graph.baseDir);if(!jw(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 Po({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()});nn.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=T();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 Po({baseDir:li(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 C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);d=(await C.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 y=p?r:l,w=new Map;y.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 Ow(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(`
533
533
  `),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(`
534
- `)}async function jw(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 Ia((c?.content||"").toString())}finally{clearTimeout(r)}}function Ow(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function zr(){let e=j();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=li(process.cwd(),e.graph.baseDir);return{store:new Po({baseDir:o}),baseDir:o}}var Yr=nn.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Yr.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=zr();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(cs(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]"))});Yr.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=zr();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}: ${cs(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});Yr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=zr();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 Dw}from"commander";import K from"chalk";import{Command as xm}from"commander";import me from"chalk";import{existsSync as Cw}from"fs";import{resolve as Iw}from"path";import Nw from"better-sqlite3";function Rw(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(me.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function _w(e){let o=Iw(process.cwd(),e);return Cw(o)||(console.log(me.red(` No db at ${o}`)),process.exit(1)),new Nw(o,{readonly:!0})}var Sm=new xm().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(vn)).option("--max <n>","max clusters distilled per run",String(ms)).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(me.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=_w(e.path),t=await $c(o,{since:Rw(e.since),agentId:e.agent,sessions:new La(process.cwd()),minOccurrences:Number(e.minOccurrences)||vn,max:Number(e.max)||ms,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(me.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(` ${me.cyan(n.key)} ${me.bold(`\xD7${n.count}`)} ${me.dim(n.status)}`),n.sampleMessage&&console.log(me.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(me.dim(`
534
+ `)}async function Cw(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 Ia((c?.content||"").toString())}finally{clearTimeout(r)}}function Iw(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function zr(){let e=T();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=li(process.cwd(),e.graph.baseDir);return{store:new Po({baseDir:o}),baseDir:o}}var Yr=nn.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Yr.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=zr();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(cs(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]"))});Yr.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=zr();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}: ${cs(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});Yr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=zr();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 Mw}from"commander";import K from"chalk";import{Command as Em}from"commander";import me from"chalk";import{existsSync as Nw}from"fs";import{resolve as Rw}from"path";import _w from"better-sqlite3";function Dw(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(me.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Pw(e){let o=Rw(process.cwd(),e);return Nw(o)||(console.log(me.red(` No db at ${o}`)),process.exit(1)),new _w(o,{readonly:!0})}var Am=new Em().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(vn)).option("--max <n>","max clusters distilled per run",String(ms)).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(me.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Pw(e.path),t=await bc(o,{since:Dw(e.since),agentId:e.agent,sessions:new La(process.cwd()),minOccurrences:Number(e.minOccurrences)||vn,max:Number(e.max)||ms,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(me.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(` ${me.cyan(n.key)} ${me.bold(`\xD7${n.count}`)} ${me.dim(n.status)}`),n.sampleMessage&&console.log(me.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(me.dim(`
535
535
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(me.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(me.green(` \u2713 draft written: ${n.id}`)+me.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(me.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(me.yellow(` \u26A0 ${n}`));t.dryRun?console.log(me.dim(`
536
536
  dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(me.dim(`
537
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),vm={hourly:"0 * * * *",daily:"0 3 * * *"},Em=new xm().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(vn)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?vm.hourly:e.daily?vm.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(me.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(me.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||vn,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${ms} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
538
- `),i=await ie(a=>{Ie(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Ie(a,"crons.procedure-extract.enabled",!1):o&&Ie(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(me.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(me.green(` \u2713 ${r} procedure extraction: off`)):(console.log(me.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(me.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(me.dim(" on-task counting: enabled")),console.log(me.dim(` threshold: ${t} occurrences`))),console.log(me.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var ho=new Dw().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");ho.addCommand(Sm);ho.addCommand(Em);ho.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new Mo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(K.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?K.green(n.meta.status):n.meta.status==="draft"?K.yellow(n.meta.status):K.dim(n.meta.status);console.log(` ${K.cyan(n.meta.id)} ${K.bold(n.meta.title)} ${s}`),console.log(` ${K.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${K.dim("source:")} ${K.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${K.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(K.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});ho.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new Mo,t=e.steps?String(e.steps):`## Steps
537
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Sm={hourly:"0 * * * *",daily:"0 3 * * *"},Tm=new Em().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(vn)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?Sm.hourly:e.daily?Sm.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(me.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(me.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||vn,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${ms} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
538
+ `),i=await ie(a=>{Ie(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Ie(a,"crons.procedure-extract.enabled",!1):o&&Ie(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(me.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(me.green(` \u2713 ${r} procedure extraction: off`)):(console.log(me.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(me.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(me.dim(" on-task counting: enabled")),console.log(me.dim(` threshold: ${t} occurrences`))),console.log(me.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var ho=new Mw().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");ho.addCommand(Am);ho.addCommand(Tm);ho.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new Mo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(K.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?K.green(n.meta.status):n.meta.status==="draft"?K.yellow(n.meta.status):K.dim(n.meta.status);console.log(` ${K.cyan(n.meta.id)} ${K.bold(n.meta.title)} ${s}`),console.log(` ${K.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${K.dim("source:")} ${K.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${K.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(K.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});ho.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new Mo,t=e.steps?String(e.steps):`## Steps
539
539
 
540
540
  1. (fill in)
541
541
 
542
542
  ## Notes
543
543
 
544
- `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(K.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(K.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(K.red(` add failed: ${n.message}`)),process.exit(1)}});ho.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new Mo,t=o.get(e)??o.getDraft(e);t||(console.log(K.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(K.bold(` ${t.meta.title}`)+K.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(K.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(K.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(K.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(K.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(K.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(K.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(K.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});ho.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new Mo;try{let t=o.promoteDraft(e);console.log(K.green(` \u2713 promoted: ${t.meta.id}`)),console.log(K.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(K.red(` ${t.message}`)),process.exit(1)}});ho.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new Mo;try{o.rejectDraft(e),console.log(K.green(` \u2713 rejected: ${e}`))}catch(t){console.log(K.red(` ${t.message}`)),process.exit(1)}});ho.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new Mo;try{o.deprecate(e),console.log(K.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(K.red(` ${t.message}`)),process.exit(1)}});ho.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new Mo,n=Za(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(K.dim(" no matching procedures"));return}for(let s of n)console.log(` ${K.cyan(s.procedure.meta.id)} ${K.bold(s.score.toFixed(2))} ${K.dim(s.reasons.join(", "))}`),console.log(K.dim(` ${s.procedure.meta.trigger}`))});import{Command as Lw}from"commander";import A from"chalk";import{resolve as rn,basename as qw}from"path";import{existsSync as Vr,readFileSync as Kr,writeFileSync as di}from"fs";import ZT from"better-sqlite3";import{readFileSync as Pw}from"fs";import{resolve as sn,dirname as Am}from"path";import{fileURLToPath as Mw}from"url";var Vn=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function Tm(e){let o=Am(Mw(import.meta.url)),t=process.argv[1]?Am(process.argv[1]):"",n=[sn(o,`${e}.yaml`),sn(o,"workflows/templates",`${e}.yaml`),sn(o,"..","workflows/templates",`${e}.yaml`),sn(o,"../..","workflows/templates",`${e}.yaml`),t?sn(t,"workflows/templates",`${e}.yaml`):"",t?sn(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Pw(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
544
+ `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(K.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(K.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(K.red(` add failed: ${n.message}`)),process.exit(1)}});ho.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new Mo,t=o.get(e)??o.getDraft(e);t||(console.log(K.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(K.bold(` ${t.meta.title}`)+K.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(K.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(K.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(K.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(K.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(K.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(K.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(K.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});ho.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new Mo;try{let t=o.promoteDraft(e);console.log(K.green(` \u2713 promoted: ${t.meta.id}`)),console.log(K.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(K.red(` ${t.message}`)),process.exit(1)}});ho.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new Mo;try{o.rejectDraft(e),console.log(K.green(` \u2713 rejected: ${e}`))}catch(t){console.log(K.red(` ${t.message}`)),process.exit(1)}});ho.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new Mo;try{o.deprecate(e),console.log(K.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(K.red(` ${t.message}`)),process.exit(1)}});ho.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new Mo,n=Za(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(K.dim(" no matching procedures"));return}for(let s of n)console.log(` ${K.cyan(s.procedure.meta.id)} ${K.bold(s.score.toFixed(2))} ${K.dim(s.reasons.join(", "))}`),console.log(K.dim(` ${s.procedure.meta.trigger}`))});import{Command as Uw}from"commander";import A from"chalk";import{resolve as rn,basename as Fw}from"path";import{existsSync as Vr,readFileSync as Kr,writeFileSync as di}from"fs";import o1 from"better-sqlite3";import{readFileSync as Lw}from"fs";import{resolve as sn,dirname as jm}from"path";import{fileURLToPath as qw}from"url";var Vn=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function Om(e){let o=jm(qw(import.meta.url)),t=process.argv[1]?jm(process.argv[1]):"",n=[sn(o,`${e}.yaml`),sn(o,"workflows/templates",`${e}.yaml`),sn(o,"..","workflows/templates",`${e}.yaml`),sn(o,"../..","workflows/templates",`${e}.yaml`),t?sn(t,"workflows/templates",`${e}.yaml`):"",t?sn(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Lw(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
545
545
  ${n.join(`
546
- `)}`)}var Ke=new Lw().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ke.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new tt().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"}.`))});Ke.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 tt().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(Ja(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))});Ke.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=rn(process.cwd(),e);Vr(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=Kr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Tt(r,{filePath:e}):JSON.parse(r),l=At.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=ls(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 ds?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let t=new tt().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)});Ke.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Vn.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");Vn.some(a=>a.name===t)||(console.log(A.red(` unknown template "${o.template}"`)),console.log(A.dim(` available: ${Vn.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 tt;!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=Tm(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=Tt(s,{filePath:`${e}.yaml`}),c=At.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=rn(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Tt(s,{filePath:`${e}.yaml`}),c=At.parse(a);di(r,JSON.stringify(c,null,2)+`
547
- `)}else di(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()});Ke.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Vn)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()});Ke.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=rn(process.cwd(),e);Vr(t)||(console.log(A.red(` file not found: ${t}`)),process.exit(1));let n=Kr(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Tt(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof ds?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=At.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=ls(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 tt,l=s?qw(e).match(/\.yml$/i)?"yml":"yaml":"json",g=rn(c.baseDir,`${r.data.id}.${l}`);if(di(g,s?n:JSON.stringify(r.data,null,2)+`
546
+ `)}`)}var Ke=new Uw().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ke.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new tt().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"}.`))});Ke.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 tt().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(Ja(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))});Ke.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=rn(process.cwd(),e);Vr(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=Kr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Tt(r,{filePath:e}):JSON.parse(r),l=At.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=ls(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 ds?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let t=new tt().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)});Ke.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Vn.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");Vn.some(a=>a.name===t)||(console.log(A.red(` unknown template "${o.template}"`)),console.log(A.dim(` available: ${Vn.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 tt;!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=Om(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=Tt(s,{filePath:`${e}.yaml`}),c=At.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=rn(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Tt(s,{filePath:`${e}.yaml`}),c=At.parse(a);di(r,JSON.stringify(c,null,2)+`
547
+ `)}else di(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()});Ke.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Vn)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()});Ke.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=rn(process.cwd(),e);Vr(t)||(console.log(A.red(` file not found: ${t}`)),process.exit(1));let n=Kr(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Tt(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof ds?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=At.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=ls(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 tt,l=s?Fw(e).match(/\.yml$/i)?"yml":"yaml":"json",g=rn(c.baseDir,`${r.data.id}.${l}`);if(di(g,s?n:JSON.stringify(r.data,null,2)+`
548
548
  `),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`))}});Ke.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 bn({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"}.`))});Ke.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=rn(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Vr(s)){let c=Kr(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?Tt(c,{filePath:e}):JSON.parse(c)}catch(b){let $=b instanceof ds?b.message:`parse error: ${b?.message??b}`;console.log(A.red(` ${$}`)),process.exit(1)}let d=At.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=ls(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 tt,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,y=l?"yaml":"json",w=rn(f.baseDir,`${p}.${y}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
549
- `;di(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 Uw({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Uw(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())}Ke.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}jm(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)jm(i)});function jm(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()}Ke.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 bn({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Ke.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 bn({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Ke.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 bn({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 Om}from"commander";import ce from"chalk";import $t from"prompts";import{readFileSync as Fw,existsSync as Ww}from"fs";import{resolve as Jw}from"path";var Kn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Xr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Cm={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 Im(){let e=Jw(process.cwd(),"agentx.json");if(!Ww(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Fw(e,"utf-8"))}function Bw(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ce.yellow("\u26A0 no signing secret"):ce.green("\u2713 active"):ce.dim("disabled")}function Hw(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Xr.has(e.source)?ce.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ce.cyan(e.id)} ${Bw(e)}`),console.log(` ${ce.dim(e.source)} \u2192 ${ce.bold(e.agentId)}${n}`),console.log(` POST ${ce.dim(t)}`),e.secretEnv&&console.log(` secret: ${ce.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${ce.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${ce.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${ce.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var No=new Om().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");No.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Im(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ce.dim(`
549
+ `;di(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 Ww({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Ww(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())}Ke.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}Cm(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)Cm(i)});function Cm(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()}Ke.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 bn({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Ke.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 bn({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Ke.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 bn({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 Im}from"commander";import ce from"chalk";import $t from"prompts";import{readFileSync as Jw,existsSync as Bw}from"fs";import{resolve as Hw}from"path";var Kn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Xr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Nm={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 Rm(){let e=Hw(process.cwd(),"agentx.json");if(!Bw(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Jw(e,"utf-8"))}function Gw(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ce.yellow("\u26A0 no signing secret"):ce.green("\u2713 active"):ce.dim("disabled")}function zw(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Xr.has(e.source)?ce.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ce.cyan(e.id)} ${Gw(e)}`),console.log(` ${ce.dim(e.source)} \u2192 ${ce.bold(e.agentId)}${n}`),console.log(` POST ${ce.dim(t)}`),e.secretEnv&&console.log(` secret: ${ce.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${ce.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${ce.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${ce.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var No=new Im().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");No.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Rm(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ce.dim(`
550
550
  No webhooks registered. Add one with: agentx webhook add
551
- `));return}console.log();for(let n of t)Hw(n)});No.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Kn.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=Im(),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 $t({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 $t({type:"select",name:"source",message:"Source",choices:Kn.map(p=>({title:`${p}${Xr.has(p)?" \u2713 wired":""}`,value:p,description:Cm[p]}))})).source),!Kn.includes(a))throw new Error(`Source must be one of: ${Kn.join(", ")}`);if(!c&&d&&(i?c=((await $t({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await $t({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 $t({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await $t({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ie(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(y=>y.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(ce.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(ce.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(ce.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});No.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await $t({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await ie(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(ce.green(`\u2713 removed webhook "${e}"`))});function Nm(e){return async o=>{let t=await ie(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(ce.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}No.command("enable <id>").description("enable a webhook entry").action(Nm(!0));No.command("disable <id>").description("disable a webhook entry").action(Nm(!1));var gi=new Om().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");gi.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await ie(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(ce.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});gi.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await ie(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(ce.green(`\u2713 removed trigger ${o} from "${e}"`))});gi.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 ie(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(ce.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});No.addCommand(gi);No.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Kn.map(t=>({source:t,wired:Xr.has(t),hint:Cm[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?ce.green("\u2713 wired"):ce.dim("inbound-only");console.log(` ${ce.cyan(t.source.padEnd(8))} ${n} ${ce.dim(t.hint)}`)}console.log(),console.log(ce.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(ce.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Gw}from"commander";import le from"chalk";oe();function an(e){let{summary:o,backupPath:t}=oo(n=>e(n));console.log(le.green(`
551
+ `));return}console.log();for(let n of t)zw(n)});No.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Kn.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=Rm(),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 $t({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 $t({type:"select",name:"source",message:"Source",choices:Kn.map(p=>({title:`${p}${Xr.has(p)?" \u2713 wired":""}`,value:p,description:Nm[p]}))})).source),!Kn.includes(a))throw new Error(`Source must be one of: ${Kn.join(", ")}`);if(!c&&d&&(i?c=((await $t({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await $t({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 $t({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await $t({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ie(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(y=>y.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(ce.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(ce.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(ce.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});No.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await $t({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await ie(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(ce.green(`\u2713 removed webhook "${e}"`))});function _m(e){return async o=>{let t=await ie(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(ce.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}No.command("enable <id>").description("enable a webhook entry").action(_m(!0));No.command("disable <id>").description("disable a webhook entry").action(_m(!1));var gi=new Im().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");gi.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await ie(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(ce.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});gi.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await ie(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(ce.green(`\u2713 removed trigger ${o} from "${e}"`))});gi.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 ie(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(ce.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});No.addCommand(gi);No.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Kn.map(t=>({source:t,wired:Xr.has(t),hint:Nm[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?ce.green("\u2713 wired"):ce.dim("inbound-only");console.log(` ${ce.cyan(t.source.padEnd(8))} ${n} ${ce.dim(t.hint)}`)}console.log(),console.log(ce.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(ce.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Yw}from"commander";import le from"chalk";oe();function an(e){let{summary:o,backupPath:t}=oo(n=>e(n));console.log(le.green(`
552
552
  \u2713 ${o}`)),t&&console.log(le.dim(` Backup: ${t}`)),console.log(le.dim(` Restart the daemon (or POST /reload) for the change to take effect.
553
- `))}function mi(){try{return j().business||{}}catch{return{}}}var cn=new Gw().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");cn.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=mi();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(le.yellow(" business block not enabled (or missing).")),console.log(le.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(le.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(le.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?le.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?le.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${le.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(le.bold(` Projects (${n.length})`)),n.length===0)console.log(le.dim(" (empty)"));else for(let r of n){let a=r.pm?le.dim(` \xB7 pm=${r.pm}`):"",c=r.client?le.dim(` \xB7 client=${r.client}`):"";console.log(` ${le.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(le.bold(` Contact map (${s.length})`)),s.length===0)console.log(le.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${le.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?le.dim(` (${r.displayName})`):""}`)}console.log()});var Qr=cn.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Qr.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=mi(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(le.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${le.cyan(n)} ${s.role}${s.reportsTo?le.dim(` \u2192 ${s.reportsTo}`):""}`)});Qr.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);an(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});Qr.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{an(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var Zr=cn.command("project").description("manage business.projects \u2014 id, pm, client");Zr.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=mi().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(le.dim(" no projects"));return}for(let n of t)console.log(` ${le.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Zr.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{an(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Zr.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{an(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var ea=cn.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");ea.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=mi().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(le.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${le.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});ea.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(le.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),an(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});ea.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{an(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as zw}from"commander";import Fe from"chalk";oe();var Yw={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function oa(e){let o=Yw[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function pi(){let o=j().business?.standup?.plansDir||".agentx/plans";return new Sl(o)}var ln=new zw().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");ln.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=oa(e),n=pi(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
554
- `):(console.error(Fe.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Fe.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Yi(s);if(r.length){console.log(Fe.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Fe.dim(` \u2022 ${a}`))}});ln.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=pi();if(e){let n=oa(e),s=o.read(n);if(!s){console.log(Fe.dim(` No ${n} plan set.`));return}Rm(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Fe.yellow(" No plan set at any tier.")),console.log(Fe.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Fe.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Rm(t.tier,t.date,t.content)});ln.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=pi().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Fe.dim(" No plans yet."));return}for(let n of t)console.log(` ${Fe.cyan(n.tier.padEnd(5))} ${Fe.bold(n.date.padEnd(11))} ${Fe.dim(n.path)}`)});ln.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=oa(e),n=pi().read(o);if(!n){console.log(Fe.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Fe.green(` \u2713 ${o} plan cleared (${n.path})`))});function Rm(e,o,t){console.log(Fe.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
555
- `))console.log(` ${s}`);console.log();let n=Yi(t);n.length&&console.log(Fe.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Vw}from"commander";import Y from"chalk";oe();function Kw(){try{return j().notifications||{}}catch{return{}}}function Xw(){try{return j().channels?.ntfy}catch{return}}function Qw(){try{return j().channels?.push}catch{return}}function dn(e){let{summary:o,backupPath:t}=oo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Y.green(`
556
- \u2713 ${o}`)),t&&console.log(Y.dim(` Backup: ${t}`)),console.log(Y.dim(` Restart the daemon (or POST /reload) for the change to take effect.
557
- `))}var xo=new Vw().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");xo.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=Kw();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let c=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Y.cyan(o.destination.channel+":"+o.destination.chatId)}${Y.dim(c)}`)}else console.log(` destination ${Y.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Y.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Y.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Y.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Y.dim("off")}`);let n=fs(o.local);if(console.log(` local.banner ${n.banner?"on":Y.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:Y.dim("off")}`),console.log(` local.icon ${n.icon??Y.dim("AgentX logo")}`),n.banner){let c=await Ol();c.state!=="unsupported"&&(console.log(` local.helper ${c.state==="ready"?c.message:Y.yellow(c.message)}`),c.fix&&console.log(` ${Y.dim("Fix: "+c.fix)}`))}let s;try{s=j()}catch{s=void 0}console.log(` channel ${ws(s)} ${Y.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=Mi(Qw()),r=i.role==="relay"?`relays to ${i.relayTo}`:`this node sends \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing (agentx app push-keys)"}`;console.log(` push ${i.enabled?"on":Y.dim("off")} ${Y.dim(r)}`);let a=Xi(Xw());console.log(` ntfy ${a.enabled?"on":Y.dim("off")} ${Y.dim(`${a.server} \xB7 topic ${a.topicSet?"set":"unset"} \xB7 token ${a.tokenSet?"set":"unset"}`)}`),console.log()});xo.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){dn(o=>(delete o.destination,"notifications destination cleared"));return}dn(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});xo.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(Y.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(Y.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";dn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});xo.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(Y.red(" threshold must be a non-negative integer")),process.exit(1)),dn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});xo.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(Y.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{dn(n=>(n.local=Ic(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(Y.dim(` Run agentx desktop install to put the new icon on the helper.
558
- `))}catch(n){console.log(Y.red(` ${n?.message??n}`)),process.exit(1)}});xo.command("channel <name>").description("channel agentx notify uses when --channel is not given: push, ntfy, telegram\u2026 (unset: push when it is on, else ntfy)").action(e=>{let o=e.trim();/^[\w-]+$/.test(o)||(console.log(Y.red(` not a channel name: ${e}`)),process.exit(1)),dn(t=>(t.channel=o,`notifications.channel = ${o}`))});xo.command("push").description("set up notifications on the phone app: on/off, contact, or relay to the node that hosts the app").option("--subject <contact>","contact for the push services: mailto:you@example.com or an https:// URL").option("--relay-to <peer>",'mesh peer that hosts the phone app (on every other node); "" makes this node the host').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.subject!==void 0&&(o.subject=e.subject),e.relayTo!==void 0&&(o.relayTo=e.relayTo),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=oo(s=>{s.channels=s.channels||{},s.channels.push=qc(s.channels.push,o);let i=Mi(s.channels.push);return`channels.push ${i.enabled?"on":"off"} \xB7 ${i.role==="relay"?`relays to ${i.relayTo}`:`host \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing"}`}`});console.log(Y.green(`
559
- \u2713 ${t}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
560
- `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});xo.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=oo(s=>{s.channels=s.channels||{},s.channels.ntfy=Bl(s.channels.ntfy,o);let i=Xi(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(Y.green(`
561
- \u2713 ${t}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
562
- `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as Zw}from"commander";import Xo from"chalk";import{readdirSync as ta,statSync as _m,unlinkSync as e$,rmSync as o$,existsSync as Dm}from"fs";import{resolve as Pm,join as Mm}from"path";var Lm=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function na(e,o){if(!Dm(e))return[];let t=[];for(let n of ta(e,{withFileTypes:!0})){let s=Mm(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...na(s,!0))}return t}var fi=new Zw().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");fi.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Lm){let t=Pm(process.cwd(),o.dir),n=na(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=_m(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${Xo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ui(s).padStart(10)} oldest=${r}`)}console.log(Xo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ui(e).padStart(10)} total`)),console.log(),console.log(Xo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});fi.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Xo.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Xo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Xo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Lm){if(n&&r.dir!==n)continue;let a=Pm(process.cwd(),r.dir),c=na(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=_m(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{e$(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{qm(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Xo.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${ui(g)})`),s+=l,i+=g}console.log(),console.log(Xo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${ui(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function qm(e){if(Dm(e))for(let o of ta(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Mm(e,o.name);qm(t);try{ta(t).length===0&&o$(t,{recursive:!1})}catch{}}}function ui(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"}import{Command as t$}from"commander";import U from"chalk";var Qo=new t$().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Qo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new jt().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});Qo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new jt().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});Qo.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=n$(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=Ba.safeParse(n);if(!s.success){console.log(U.red(" validation failed:"));for(let a of s.error.issues)console.log(U.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new jt().save(s.data);console.log(U.green(`
553
+ `))}function mi(){try{return T().business||{}}catch{return{}}}var cn=new Yw().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");cn.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=mi();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(le.yellow(" business block not enabled (or missing).")),console.log(le.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(le.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(le.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?le.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?le.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${le.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(le.bold(` Projects (${n.length})`)),n.length===0)console.log(le.dim(" (empty)"));else for(let r of n){let a=r.pm?le.dim(` \xB7 pm=${r.pm}`):"",c=r.client?le.dim(` \xB7 client=${r.client}`):"";console.log(` ${le.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(le.bold(` Contact map (${s.length})`)),s.length===0)console.log(le.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${le.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?le.dim(` (${r.displayName})`):""}`)}console.log()});var Qr=cn.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Qr.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=mi(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(le.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${le.cyan(n)} ${s.role}${s.reportsTo?le.dim(` \u2192 ${s.reportsTo}`):""}`)});Qr.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);an(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});Qr.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{an(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var Zr=cn.command("project").description("manage business.projects \u2014 id, pm, client");Zr.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=mi().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(le.dim(" no projects"));return}for(let n of t)console.log(` ${le.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Zr.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{an(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Zr.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{an(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var ea=cn.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");ea.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=mi().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(le.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${le.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});ea.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(le.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),an(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});ea.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{an(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as Vw}from"commander";import Fe from"chalk";oe();var Kw={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function oa(e){let o=Kw[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function pi(){let o=T().business?.standup?.plansDir||".agentx/plans";return new El(o)}var ln=new Vw().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");ln.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=oa(e),n=pi(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
554
+ `):(console.error(Fe.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Fe.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Yi(s);if(r.length){console.log(Fe.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Fe.dim(` \u2022 ${a}`))}});ln.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=pi();if(e){let n=oa(e),s=o.read(n);if(!s){console.log(Fe.dim(` No ${n} plan set.`));return}Dm(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Fe.yellow(" No plan set at any tier.")),console.log(Fe.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Fe.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Dm(t.tier,t.date,t.content)});ln.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=pi().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Fe.dim(" No plans yet."));return}for(let n of t)console.log(` ${Fe.cyan(n.tier.padEnd(5))} ${Fe.bold(n.date.padEnd(11))} ${Fe.dim(n.path)}`)});ln.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=oa(e),n=pi().read(o);if(!n){console.log(Fe.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Fe.green(` \u2713 ${o} plan cleared (${n.path})`))});function Dm(e,o,t){console.log(Fe.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
555
+ `))console.log(` ${s}`);console.log();let n=Yi(t);n.length&&console.log(Fe.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Xw}from"commander";import V from"chalk";oe();function Qw(){try{return T().notifications||{}}catch{return{}}}function Zw(){try{return T().channels?.ntfy}catch{return}}function e$(){try{return T().channels?.push}catch{return}}function dn(e){let{summary:o,backupPath:t}=oo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(V.green(`
556
+ \u2713 ${o}`)),t&&console.log(V.dim(` Backup: ${t}`)),console.log(V.dim(` Restart the daemon (or POST /reload) for the change to take effect.
557
+ `))}var xo=new Xw().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");xo.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=Qw();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let c=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${V.cyan(o.destination.channel+":"+o.destination.chatId)}${V.dim(c)}`)}else console.log(` destination ${V.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${V.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?V.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?V.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":V.dim("off")}`);let n=fs(o.local);if(console.log(` local.banner ${n.banner?"on":V.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:V.dim("off")}`),console.log(` local.icon ${n.icon??V.dim("AgentX logo")}`),n.banner){let c=await Cl();c.state!=="unsupported"&&(console.log(` local.helper ${c.state==="ready"?c.message:V.yellow(c.message)}`),c.fix&&console.log(` ${V.dim("Fix: "+c.fix)}`))}let s;try{s=T()}catch{s=void 0}console.log(` channel ${ws(s)} ${V.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=Mi(e$()),r=i.role==="relay"?`relays to ${i.relayTo}`:`this node sends \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing (agentx app push-keys)"}`;console.log(` push ${i.enabled?"on":V.dim("off")} ${V.dim(r)}`);let a=Xi(Zw());console.log(` ntfy ${a.enabled?"on":V.dim("off")} ${V.dim(`${a.server} \xB7 topic ${a.topicSet?"set":"unset"} \xB7 token ${a.tokenSet?"set":"unset"}`)}`),console.log()});xo.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){dn(o=>(delete o.destination,"notifications destination cleared"));return}dn(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});xo.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(V.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(V.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";dn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});xo.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(V.red(" threshold must be a non-negative integer")),process.exit(1)),dn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});xo.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(V.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(V.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{dn(n=>(n.local=Nc(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(V.dim(` Run agentx desktop install to put the new icon on the helper.
558
+ `))}catch(n){console.log(V.red(` ${n?.message??n}`)),process.exit(1)}});xo.command("channel <name>").description("channel agentx notify uses when --channel is not given: push, ntfy, telegram\u2026 (unset: push when it is on, else ntfy)").action(e=>{let o=e.trim();/^[\w-]+$/.test(o)||(console.log(V.red(` not a channel name: ${e}`)),process.exit(1)),dn(t=>(t.channel=o,`notifications.channel = ${o}`))});xo.command("push").description("set up notifications on the phone app: on/off, contact, or relay to the node that hosts the app").option("--subject <contact>","contact for the push services: mailto:you@example.com or an https:// URL").option("--relay-to <peer>",'mesh peer that hosts the phone app (on every other node); "" makes this node the host').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.subject!==void 0&&(o.subject=e.subject),e.relayTo!==void 0&&(o.relayTo=e.relayTo),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(V.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=oo(s=>{s.channels=s.channels||{},s.channels.push=Uc(s.channels.push,o);let i=Mi(s.channels.push);return`channels.push ${i.enabled?"on":"off"} \xB7 ${i.role==="relay"?`relays to ${i.relayTo}`:`host \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing"}`}`});console.log(V.green(`
559
+ \u2713 ${t}`)),n&&console.log(V.dim(` Backup: ${n}`)),console.log(V.dim(` Restart the daemon for a channel change to take effect.
560
+ `))}catch(t){console.log(V.red(` ${t?.message??t}`)),process.exit(1)}});xo.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(V.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=oo(s=>{s.channels=s.channels||{},s.channels.ntfy=Bl(s.channels.ntfy,o);let i=Xi(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(V.green(`
561
+ \u2713 ${t}`)),n&&console.log(V.dim(` Backup: ${n}`)),console.log(V.dim(` Restart the daemon for a channel change to take effect.
562
+ `))}catch(t){console.log(V.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as o$}from"commander";import Xo from"chalk";import{readdirSync as ta,statSync as Pm,unlinkSync as t$,rmSync as n$,existsSync as Mm}from"fs";import{resolve as Lm,join as qm}from"path";var Um=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function na(e,o){if(!Mm(e))return[];let t=[];for(let n of ta(e,{withFileTypes:!0})){let s=qm(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...na(s,!0))}return t}var fi=new o$().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");fi.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Um){let t=Lm(process.cwd(),o.dir),n=na(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=Pm(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${Xo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ui(s).padStart(10)} oldest=${r}`)}console.log(Xo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ui(e).padStart(10)} total`)),console.log(),console.log(Xo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});fi.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Xo.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Xo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Xo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Um){if(n&&r.dir!==n)continue;let a=Lm(process.cwd(),r.dir),c=na(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=Pm(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{t$(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Fm(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Xo.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${ui(g)})`),s+=l,i+=g}console.log(),console.log(Xo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${ui(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Fm(e){if(Mm(e))for(let o of ta(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=qm(e,o.name);Fm(t);try{ta(t).length===0&&n$(t,{recursive:!1})}catch{}}}function ui(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"}import{Command as s$}from"commander";import U from"chalk";var Qo=new s$().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Qo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new jt().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});Qo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new jt().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});Qo.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=i$(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=Ba.safeParse(n);if(!s.success){console.log(U.red(" validation failed:"));for(let a of s.error.issues)console.log(U.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new jt().save(s.data);console.log(U.green(`
563
563
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
564
- `))});Qo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new jt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Qo.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new jt().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Ha(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});Qo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function n$(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}oe();import{Command as s$}from"commander";import se from"chalk";var Um=new s$().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=j(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(se.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(se.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(se.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let u;for(;(u=l.indexOf(`
564
+ `))});Qo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new jt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Qo.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new jt().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Ha(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});Qo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function i$(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}oe();import{Command as r$}from"commander";import se from"chalk";var Wm=new r$().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=T(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(se.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(se.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(se.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let u;for(;(u=l.indexOf(`
565
565
 
566
- `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),i$(f)}}}catch(r){console.error(se.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function i$(e){let o="message",t="";for(let i of e.split(`
567
- `))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?se.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=se.cyan(n.phase?.padEnd(9)??"run"),r=se.bold(n.workflowId??""),a=se.dim((n.runId??"").slice(0,8)),c=n.nodeId?se.yellow(n.nodeId):"",l=n.note?se.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=se.magenta(`task.${n.phase}`.padEnd(14)),r=se.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?se.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${se.cyan(a)} ${c}`);break}case"signal":{let i=se.green("signal".padEnd(9)),r=se.bold(n.name),a=se.dim(`(${n.scope})`),c=n.workflowId?se.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=se.blue("mesh".padEnd(9)),r=se.bold(n.peer),a=n.healthy?se.green("\u2713 healthy"):se.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${se.dim(n.delta??"")}`);break}case"channel":{let i=se.yellow("channel".padEnd(9)),r=n.direction==="in"?se.cyan("\u2190"):se.magenta("\u2192"),a=se.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?se.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(se.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)}`)}}oe();import{Command as r$}from"commander";import gn from"chalk";function a$(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 Fm=new r$().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=j(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(a$(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(gn.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(gn.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(gn.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(gn.dim(" no events"));return}for(let a of i)console.log(` ${Fa(a)} ${gn.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(gn.dim(`
568
- ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as l$}from"commander";import Xn from"chalk";import{spawn as d$}from"node:child_process";import{execFileSync as c$}from"node:child_process";function Wm(e=()=>c$("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 Jm=new l$().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(Xn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-K5ZISLAI.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Wm();if(n?.ok){let{fetchAgents:l}=await import("./client-K5ZISLAI.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(Xn.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:y}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:y,spawnImpl:d$,log:k=>console.error(Xn.dim(k))});return}n&&!n.ok&&(console.error(Xn.yellow(n.reason)),console.error(Xn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-CREMUAHS.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 g$}from"commander";import X from"chalk";import{randomUUID as Gm}from"crypto";import{createInterface as m$}from"node:readline/promises";import p$ from"ora";import hi from"chalk";function Bm(e){console.error(),console.error(hi.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(hi.dim(` ${e.why}`)),console.error(),console.error(` Use ${hi.cyan(e.instead)} instead.`),e.note&&console.error(hi.dim(` ${e.note}`)),console.error()}var Hm={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 zm=new g$().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)=>{Bm({what:"agentx chat",...Hm});let t=Gl({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Gm().slice(0,12)}`,r=[];try{r=await As(t)}catch(g){console.error(X.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(X.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(X.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(X.red(` unknown agent: @${n}`)),console.error(X.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(X.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-YX3YNPNS.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}f$(t.baseUrl,n,i,s);let a=m$({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(X.dim(`
569
- bye`)),process.exit(0)});;){let g;try{g=(await a.question(X.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(X.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Gm().slice(0,12)}`,console.log(X.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await As(t);for(let y of p){let w=y.id===n?X.green("\u25CF"):X.dim("\u25CB");console.log(` ${w} @${y.id} ${X.dim(y.tier)} ${y.model??""}`)}}catch(p){console.error(X.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(X.red(" usage: /agent <id>"));continue}try{if(!(await As(t)).find(w=>w.id===p)){console.log(X.red(` unknown agent: @${p}`));continue}n=p,console.log(X.dim(` now talking to @${n}`))}catch(y){console.error(X.red(` failed to switch agent: ${y?.message||y}`))}continue}if(g.startsWith("/")){console.log(X.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(X.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=p$({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=u$(n);try{let p=await zl(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 y=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(y,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(X.dim(" bye"));return}}});function u$(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${X.green(`@${e}`)}
566
+ `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),a$(f)}}}catch(r){console.error(se.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function a$(e){let o="message",t="";for(let i of e.split(`
567
+ `))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?se.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=se.cyan(n.phase?.padEnd(9)??"run"),r=se.bold(n.workflowId??""),a=se.dim((n.runId??"").slice(0,8)),c=n.nodeId?se.yellow(n.nodeId):"",l=n.note?se.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=se.magenta(`task.${n.phase}`.padEnd(14)),r=se.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?se.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${se.cyan(a)} ${c}`);break}case"signal":{let i=se.green("signal".padEnd(9)),r=se.bold(n.name),a=se.dim(`(${n.scope})`),c=n.workflowId?se.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=se.blue("mesh".padEnd(9)),r=se.bold(n.peer),a=n.healthy?se.green("\u2713 healthy"):se.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${se.dim(n.delta??"")}`);break}case"channel":{let i=se.yellow("channel".padEnd(9)),r=n.direction==="in"?se.cyan("\u2190"):se.magenta("\u2192"),a=se.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?se.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(se.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)}`)}}oe();import{Command as c$}from"commander";import gn from"chalk";function l$(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 Jm=new c$().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=T(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(l$(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(gn.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(gn.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(gn.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(gn.dim(" no events"));return}for(let a of i)console.log(` ${Fa(a)} ${gn.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(gn.dim(`
568
+ ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as g$}from"commander";import Xn from"chalk";import{spawn as m$}from"node:child_process";import{execFileSync as d$}from"node:child_process";function Bm(e=()=>d$("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 Hm=new g$().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(Xn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-CGZ3XXAA.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Bm();if(n?.ok){let{fetchAgents:l}=await import("./client-CGZ3XXAA.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(Xn.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:y}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:y,spawnImpl:m$,log:k=>console.error(Xn.dim(k))});return}n&&!n.ok&&(console.error(Xn.yellow(n.reason)),console.error(Xn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-3CNSN65B.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 p$}from"commander";import X from"chalk";import{randomUUID as Ym}from"crypto";import{createInterface as u$}from"node:readline/promises";import f$ from"ora";import hi from"chalk";function Gm(e){console.error(),console.error(hi.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(hi.dim(` ${e.why}`)),console.error(),console.error(` Use ${hi.cyan(e.instead)} instead.`),e.note&&console.error(hi.dim(` ${e.note}`)),console.error()}var zm={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 Vm=new p$().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)=>{Gm({what:"agentx chat",...zm});let t=Gl({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Ym().slice(0,12)}`,r=[];try{r=await As(t)}catch(g){console.error(X.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(X.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(X.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(X.red(` unknown agent: @${n}`)),console.error(X.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(X.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-6RBH5UEC.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}y$(t.baseUrl,n,i,s);let a=u$({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(X.dim(`
569
+ bye`)),process.exit(0)});;){let g;try{g=(await a.question(X.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(X.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Ym().slice(0,12)}`,console.log(X.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await As(t);for(let y of p){let w=y.id===n?X.green("\u25CF"):X.dim("\u25CB");console.log(` ${w} @${y.id} ${X.dim(y.tier)} ${y.model??""}`)}}catch(p){console.error(X.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(X.red(" usage: /agent <id>"));continue}try{if(!(await As(t)).find(w=>w.id===p)){console.log(X.red(` unknown agent: @${p}`));continue}n=p,console.log(X.dim(` now talking to @${n}`))}catch(y){console.error(X.red(` failed to switch agent: ${y?.message||y}`))}continue}if(g.startsWith("/")){console.log(X.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(X.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=f$({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=h$(n);try{let p=await zl(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 y=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(y,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(X.dim(" bye"));return}}});function h$(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${X.green(`@${e}`)}
570
570
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
571
571
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
572
572
  `&&(t=!0)}},tool(r){if(i(),r.status==="start"&&r.name){let a=r.id||`${r.name}:${s.size}`;if(s.has(a))return;s.add(a),t||(process.stdout.write(`
@@ -581,17 +581,17 @@ agentx wiki questions`,ue=C?.daemon?.port??C?.port??18800;try{let B=await fetch(
581
581
  `))},finishError(r){o&&!t&&process.stdout.write(`
582
582
  `),process.stdout.write(X.red(` \u2717 ${r}
583
583
 
584
- `))}}}function f$(e,o,t,n){console.log(),console.log(X.bold(" agentx chat")),console.log(X.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(X.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as h$}from"commander";import ee from"chalk";import{readFileSync as y$}from"fs";import{existsSync as w$,readdirSync as $$}from"fs";import{resolve as b$}from"path";var yi=["user","feedback","project","reference"],Zo=new h$().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Zo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!yi.includes(e.type)){console.error(ee.red(` --type must be one of: ${yi.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await k$();else try{o=y$(e.file,"utf-8")}catch(s){console.error(ee.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(ee.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Et().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(ee.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Zo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new Et().list(e.agent);if(e.type){if(!yi.includes(e.type)){console.error(ee.red(` --type must be one of: ${yi.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(ee.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(ee.bold(` ${s.type}`)),n=s.type),console.log(` ${ee.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(ee.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Zo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new Et().get(o.agent,e);if(!n){console.error(ee.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ee.bold(`${n.type}/${n.name}`)+ee.dim(` (${n.description})`)),console.log(ee.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Zo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Et().remove(o.agent,e)){console.error(ee.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ee.green(` \u2713 memory "${e}" removed`))});Zo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new Et().indexMarkdown(e.agent);if(!t){console.log(ee.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var Qn=Zo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function wi(e){if(e)return[e];let o=b$(process.cwd(),".agentx/memory");return w$(o)?$$(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}Qn.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let o=new St;for(let t of wi(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${ee.bold(t)} ${n||ee.dim("(none)")}`)}});Qn.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new St,t=0;for(let n of wi(e.agent))for(let s of o.held(n))t++,console.log(` ${ee.bold(n)} ${ee.cyan(s.id)} ${ee.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(ee.dim(" nothing held"))});for(let e of["approve","reject"])Qn.command(e).description(e==="approve"?"let a held fact be used in prompts":"keep a held fact out of prompts for good").requiredOption("--agent <id>","agent id").argument("<id>","fact id (from `agentx memory facts held`)").action((o,t)=>{if(!new St().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(ee.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ee.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});Qn.command("scrub").description("find stored facts that contain credentials; --apply deletes them").option("--agent <id>","one agent (default: all)").option("--apply","delete them (default: count only)").action(e=>{let o=new St,t=0;for(let n of wi(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${ee.bold(n)} ${s}`),t+=s}console.log(e.apply?ee.green(` \u2713 deleted ${t} fact(s) containing credentials`):ee.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});Qn.command("flag-unsourced").description("mark facts about billing, accounts, outages or deploys that name no source as unverified; --apply writes (with a backup)").option("--agent <id>","one agent (default: all)").option("--apply","flag them (default: list only)").action(async e=>{let{flagUnsourced:o}=await import("./memory-migrate-ED37IBEL.js"),t=new St,n=0;for(let s of wi(e.agent)){let i=o(t,s,{apply:!!e.apply});if(i.flagged.length!==0){n+=i.flagged.length,console.log(` ${ee.bold(s)} ${i.flagged.length}${i.backup?ee.dim(` (backup: ${i.backup})`):""}`);for(let r of i.flagged.slice(0,10))console.log(ee.dim(` ${r.id} [${r.volatility}] ${r.content.slice(0,100)}`))}}console.log(e.apply?ee.green(` \u2713 flagged ${n} fact(s) as unverified`):ee.dim(` ${n} fact(s) state billing, account, outage or deploy state with no source. Run with --apply to flag them.`))});async function k$(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}xp();import sa from"chalk";import{Command as v$}from"commander";import{resolve as x$}from"path";var Ym=new v$().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(x$(e.cwd)),e.stdio!==!1?await gc():(So.error("Only stdio transport is currently supported."),So.info(`Usage: ${sa.green("agentx serve --stdio")} or configure in your MCP client.`),So.break(),So.info("Add to Claude Code:"),So.info(sa.dim(" claude mcp add agentx -- npx agentx serve --stdio")),So.break(),So.info("Add to Cursor/MCP config:"),So.info(sa.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Tl(o)}});import{Command as N$}from"commander";import de from"chalk";import{spawn as ep}from"child_process";import{mkdirSync as R$,writeFileSync as ki,readFileSync as _$,readdirSync as D$,rmSync as op,openSync as tp,existsSync as $i}from"fs";import{resolve as P$,join as We}from"path";import{randomBytes as M$}from"crypto";var Vm={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};oe();import{existsSync as S$,readFileSync as E$}from"fs";import{cpus as A$,loadavg as T$}from"os";import{resolve as j$}from"path";var Km="AGENTX_DEMO_STARTUP_TIMEOUT",O$=60,C$=300;function I$(e,o){let t=Math.max(1,e/Math.max(1,o));return Math.min(C$,Math.ceil(O$*t))}function Xm(e,o){if(e===void 0||e.trim()==="")return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error(`${o} must be a positive number of seconds, got "${e}"`);return t}function Qm(e){let o=j$(e,"agentx.json");if(!S$(o))return;let t;try{t=JSON.parse(E$(o,"utf8"))}catch{return}let n=Sa.shape.demo.safeParse(t?.demo);if(!n.success)throw new Error(`${o}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function Zm(e){let o=Xm(e.flag,"--startup-timeout");if(o!==void 0)return{seconds:o,source:"--startup-timeout"};let t=Xm(e.env,Km);if(t!==void 0)return{seconds:t,source:Km};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??T$()[0],s=e.cpuCount??A$().length;return{seconds:I$(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var np="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",L$="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function q$(e,o){return[{dir:We(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(Vm,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:We(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:We(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function U$(e,o,t){let n=We(e.dir,"workspaces",e.agentId);R$(n,{recursive:!0}),ki(We(n,"CLAUDE.md"),`# ${e.agentName}
584
+ `))}}}function y$(e,o,t,n){console.log(),console.log(X.bold(" agentx chat")),console.log(X.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(X.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as w$}from"commander";import ee from"chalk";import{readFileSync as $$}from"fs";import{existsSync as b$,readdirSync as k$}from"fs";import{resolve as v$}from"path";var yi=["user","feedback","project","reference"],Zo=new w$().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Zo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!yi.includes(e.type)){console.error(ee.red(` --type must be one of: ${yi.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await x$();else try{o=$$(e.file,"utf-8")}catch(s){console.error(ee.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(ee.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Et().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(ee.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Zo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new Et().list(e.agent);if(e.type){if(!yi.includes(e.type)){console.error(ee.red(` --type must be one of: ${yi.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(ee.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of t)s.type!==n&&(console.log(ee.bold(` ${s.type}`)),n=s.type),console.log(` ${ee.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(ee.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Zo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new Et().get(o.agent,e);if(!n){console.error(ee.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ee.bold(`${n.type}/${n.name}`)+ee.dim(` (${n.description})`)),console.log(ee.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Zo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Et().remove(o.agent,e)){console.error(ee.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(ee.green(` \u2713 memory "${e}" removed`))});Zo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new Et().indexMarkdown(e.agent);if(!t){console.log(ee.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var Qn=Zo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function wi(e){if(e)return[e];let o=v$(process.cwd(),".agentx/memory");return b$(o)?k$(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}Qn.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let o=new St;for(let t of wi(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${ee.bold(t)} ${n||ee.dim("(none)")}`)}});Qn.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new St,t=0;for(let n of wi(e.agent))for(let s of o.held(n))t++,console.log(` ${ee.bold(n)} ${ee.cyan(s.id)} ${ee.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(ee.dim(" nothing held"))});for(let e of["approve","reject"])Qn.command(e).description(e==="approve"?"let a held fact be used in prompts":"keep a held fact out of prompts for good").requiredOption("--agent <id>","agent id").argument("<id>","fact id (from `agentx memory facts held`)").action((o,t)=>{if(!new St().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(ee.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ee.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});Qn.command("scrub").description("find stored facts that contain credentials; --apply deletes them").option("--agent <id>","one agent (default: all)").option("--apply","delete them (default: count only)").action(e=>{let o=new St,t=0;for(let n of wi(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${ee.bold(n)} ${s}`),t+=s}console.log(e.apply?ee.green(` \u2713 deleted ${t} fact(s) containing credentials`):ee.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});Qn.command("flag-unsourced").description("mark facts about billing, accounts, outages or deploys that name no source as unverified; --apply writes (with a backup)").option("--agent <id>","one agent (default: all)").option("--apply","flag them (default: list only)").action(async e=>{let{flagUnsourced:o}=await import("./memory-migrate-ED37IBEL.js"),t=new St,n=0;for(let s of wi(e.agent)){let i=o(t,s,{apply:!!e.apply});if(i.flagged.length!==0){n+=i.flagged.length,console.log(` ${ee.bold(s)} ${i.flagged.length}${i.backup?ee.dim(` (backup: ${i.backup})`):""}`);for(let r of i.flagged.slice(0,10))console.log(ee.dim(` ${r.id} [${r.volatility}] ${r.content.slice(0,100)}`))}}console.log(e.apply?ee.green(` \u2713 flagged ${n} fact(s) as unverified`):ee.dim(` ${n} fact(s) state billing, account, outage or deploy state with no source. Run with --apply to flag them.`))});async function x$(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Ep();import sa from"chalk";import{Command as S$}from"commander";import{resolve as E$}from"path";var Km=new S$().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{process.chdir(E$(e.cwd)),e.stdio!==!1?await mc():(So.error("Only stdio transport is currently supported."),So.info(`Usage: ${sa.green("agentx serve --stdio")} or configure in your MCP client.`),So.break(),So.info("Add to Claude Code:"),So.info(sa.dim(" claude mcp add agentx -- npx agentx serve --stdio")),So.break(),So.info("Add to Cursor/MCP config:"),So.info(sa.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){jl(o)}});import{Command as _$}from"commander";import de from"chalk";import{spawn as tp}from"child_process";import{mkdirSync as D$,writeFileSync as ki,readFileSync as P$,readdirSync as M$,rmSync as np,openSync as sp,existsSync as $i}from"fs";import{resolve as L$,join as We}from"path";import{randomBytes as q$}from"crypto";var Xm={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};oe();import{existsSync as A$,readFileSync as T$}from"fs";import{cpus as j$,loadavg as O$}from"os";import{resolve as C$}from"path";var Qm="AGENTX_DEMO_STARTUP_TIMEOUT",I$=60,N$=300;function R$(e,o){let t=Math.max(1,e/Math.max(1,o));return Math.min(N$,Math.ceil(I$*t))}function Zm(e,o){if(e===void 0||e.trim()==="")return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error(`${o} must be a positive number of seconds, got "${e}"`);return t}function ep(e){let o=C$(e,"agentx.json");if(!A$(o))return;let t;try{t=JSON.parse(T$(o,"utf8"))}catch{return}let n=Sa.shape.demo.safeParse(t?.demo);if(!n.success)throw new Error(`${o}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function op(e){let o=Zm(e.flag,"--startup-timeout");if(o!==void 0)return{seconds:o,source:"--startup-timeout"};let t=Zm(e.env,Qm);if(t!==void 0)return{seconds:t,source:Qm};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??O$()[0],s=e.cpuCount??j$().length;return{seconds:R$(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var ip="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",U$="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function F$(e,o){return[{dir:We(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(Xm,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:We(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:We(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function W$(e,o,t){let n=We(e.dir,"workspaces",e.agentId);D$(n,{recursive:!0}),ki(We(n,"CLAUDE.md"),`# ${e.agentName}
585
585
 
586
586
  ${e.persona}
587
587
  `),ki(We(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};ki(We(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function ia(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,250))}throw new Error(`Timed out waiting for ${e} (${t/1e3}s) \u2014 raise it with --startup-timeout <seconds>`)}function ra(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function aa(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function bi(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
588
588
  `).join(`
589
- `)}`)}var sp=new N$().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").option("--startup-timeout <seconds>","seconds each startup step may take (default: 60, longer when the machine is loaded)").action(async e=>{let o=parseInt(e.basePort,10),t=P$(process.cwd(),".agentx-demo"),n;try{n=Zm({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:Qm(process.cwd())})}catch(y){console.error(de.red(y.message)),process.exit(1)}let s=n.seconds*1e3,i=q$(t,o),r=We(t,"mesh-token"),a=!!e.reuse&&$i(r)&&$i(We(i[0].dir,"agentx.json")),c=a?_$(r,"utf8").trim():M$(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!$i(d))&&(console.error(de.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if($i(t))for(let y of D$(t))op(We(t,y),{recursive:!0,force:!0});for(let y of i)U$(y,i,c);ki(r,c+`
590
- `,{mode:384})}console.log(),console.log(de.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(de.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(de.dim(" Run `agentx setup` to wire real agents.\n")),console.log(de.dim(` Startup limit: ${n.seconds}s per step (${n.source})`));let u=!1,f=y=>{if(!u){u=!0;for(let w of g)try{w.kill("SIGTERM")}catch{}setTimeout(()=>{if(!l)try{op(t,{recursive:!0,force:!0})}catch{}process.exit(y)},800)}};process.on("SIGINT",()=>f(0)),process.on("SIGTERM",()=>f(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let $ of i){let E=tp(We($.dir,"daemon.log"),"a"),S=ep(process.execPath,[d,"daemon","start","-c",We($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:We($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(de.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${We($.dir,"daemon.log")})`))}let y=$=>ia(`${$.name} /health`,async()=>(await ra(`http://127.0.0.1:${$.port}/health`)).ok,s);await y(i[0]);let w=i[0].port+10;{let $=tp(We(i[0].dir,"board.log"),"a"),E=ep(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",$,$]});g.push(E)}for(let $ of i.slice(1))await y($);console.log(de.green(" \u2713 three daemons up")),await ia("dashboard /live",async()=>(await ra(`http://127.0.0.1:${w}/live`)).ok,s),console.log(de.green(" \u2713 dashboard up")),await ia("mesh discovery (laptop sees both peers)",async()=>((await(await ra(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(x=>x.healthy&&x.skills?.length).length>=2,s),console.log(de.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let k=`http://127.0.0.1:${w}/live`;console.log(),console.log(` Dashboard: ${de.cyan(k)} (all three nodes via the mesh)`),console.log(de.dim(` Daemon APIs: ${i.map($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1&&st(k);let b=async()=>{console.log(),console.log(de.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),bi("You \u2192 @cx (laptop-paris)",np,de.cyan);let $=await aa(i[0].port,"/task",{agent:"cx",message:np});bi("@cx (laptop-paris)",$.content||"(no content)",de.green),console.log(),console.log(de.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await aa(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:L$}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";bi("@builder (vps-nyc)",S,de.yellow);let x=await aa(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});bi("@cx (laptop-paris)",x.content||"(no content)",de.green),console.log(),console.log(de.dim(` Inspect the run: ${k} \xB7 ledger rows on each node record every dispatch`)),console.log(de.dim(` Worth your time? A star helps others find it: ${de.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(de.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await b(),e.once){console.log(),console.log(de.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(de.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{b().catch($=>console.error(de.red(` Replay failed: ${$.message}`)))}),process.stdin.resume()}catch(y){console.error(),console.error(de.red(` Demo failed: ${y.message}`)),console.error(de.dim(` Node logs: ${i.map(w=>We(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as F$}from"commander";import{randomUUID as W$}from"crypto";import{readFileSync as J$}from"fs";import{resolve as B$}from"path";oe();var rp=new F$().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??J$(0,"utf8")).trim();t||ip("no task given (pass it as an argument or on stdin)");let n=j(o.config?B$(o.config):void 0),s=n.agents[o.agent];s||ip(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Pa(o.agent,s,l,i)}let r=new ec(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${W$()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
589
+ `)}`)}var rp=new _$().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").option("--startup-timeout <seconds>","seconds each startup step may take (default: 60, longer when the machine is loaded)").action(async e=>{let o=parseInt(e.basePort,10),t=L$(process.cwd(),".agentx-demo"),n;try{n=op({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:ep(process.cwd())})}catch(y){console.error(de.red(y.message)),process.exit(1)}let s=n.seconds*1e3,i=F$(t,o),r=We(t,"mesh-token"),a=!!e.reuse&&$i(r)&&$i(We(i[0].dir,"agentx.json")),c=a?P$(r,"utf8").trim():q$(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!$i(d))&&(console.error(de.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if($i(t))for(let y of M$(t))np(We(t,y),{recursive:!0,force:!0});for(let y of i)W$(y,i,c);ki(r,c+`
590
+ `,{mode:384})}console.log(),console.log(de.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(de.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(de.dim(" Run `agentx setup` to wire real agents.\n")),console.log(de.dim(` Startup limit: ${n.seconds}s per step (${n.source})`));let u=!1,f=y=>{if(!u){u=!0;for(let w of g)try{w.kill("SIGTERM")}catch{}setTimeout(()=>{if(!l)try{np(t,{recursive:!0,force:!0})}catch{}process.exit(y)},800)}};process.on("SIGINT",()=>f(0)),process.on("SIGTERM",()=>f(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let $ of i){let E=sp(We($.dir,"daemon.log"),"a"),S=tp(process.execPath,[d,"daemon","start","-c",We($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:We($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(de.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${We($.dir,"daemon.log")})`))}let y=$=>ia(`${$.name} /health`,async()=>(await ra(`http://127.0.0.1:${$.port}/health`)).ok,s);await y(i[0]);let w=i[0].port+10;{let $=sp(We(i[0].dir,"board.log"),"a"),E=tp(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",$,$]});g.push(E)}for(let $ of i.slice(1))await y($);console.log(de.green(" \u2713 three daemons up")),await ia("dashboard /live",async()=>(await ra(`http://127.0.0.1:${w}/live`)).ok,s),console.log(de.green(" \u2713 dashboard up")),await ia("mesh discovery (laptop sees both peers)",async()=>((await(await ra(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(x=>x.healthy&&x.skills?.length).length>=2,s),console.log(de.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let k=`http://127.0.0.1:${w}/live`;console.log(),console.log(` Dashboard: ${de.cyan(k)} (all three nodes via the mesh)`),console.log(de.dim(` Daemon APIs: ${i.map($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1&&st(k);let b=async()=>{console.log(),console.log(de.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),bi("You \u2192 @cx (laptop-paris)",ip,de.cyan);let $=await aa(i[0].port,"/task",{agent:"cx",message:ip});bi("@cx (laptop-paris)",$.content||"(no content)",de.green),console.log(),console.log(de.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await aa(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:U$}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";bi("@builder (vps-nyc)",S,de.yellow);let x=await aa(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});bi("@cx (laptop-paris)",x.content||"(no content)",de.green),console.log(),console.log(de.dim(` Inspect the run: ${k} \xB7 ledger rows on each node record every dispatch`)),console.log(de.dim(` Worth your time? A star helps others find it: ${de.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(de.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await b(),e.once){console.log(),console.log(de.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(de.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{b().catch($=>console.error(de.red(` Replay failed: ${$.message}`)))}),process.stdin.resume()}catch(y){console.error(),console.error(de.red(` Demo failed: ${y.message}`)),console.error(de.dim(` Node logs: ${i.map(w=>We(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as J$}from"commander";import{randomUUID as B$}from"crypto";import{readFileSync as H$}from"fs";import{resolve as G$}from"path";oe();var cp=new J$().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??H$(0,"utf8")).trim();t||ap("no task given (pass it as an argument or on stdin)");let n=T(o.config?G$(o.config):void 0),s=n.agents[o.agent];s||ap(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Pa(o.agent,s,l,i)}let r=new oc(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${B$()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
591
591
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
592
- `),process.exit(c.error?1:0)});function ip(e){console.error(`agentx exec: ${e}`),process.exit(1)}oe();import{Command as G$}from"commander";import _e from"chalk";import{Command as H$}from"commander";import Re from"chalk";oe();rs();var bt=new H$("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function Zn(e){let o="",t=await ie(n=>{n.whatsappTriage=n.whatsappTriage&&typeof n.whatsappTriage=="object"?n.whatsappTriage:{},n.whatsappTriage.rules=Array.isArray(n.whatsappTriage.rules)?n.whatsappTriage.rules:[],o=e(n.whatsappTriage,n)});t.success||(console.error(Re.red(`\u2717 ${t.error}`)),process.exit(1)),console.log(Re.green(`\u2713 ${o}`)),t.reloaded&&console.log(Re.dim(" daemon hot-reloaded"))}function cp(e,o){let t=e.rules.find(n=>n.id===o);if(!t)throw new Error(`No watch rule "${o}". See \`agentx whatsapp triage status\`.`);return t}var ap=(e,o=[])=>[...o,e];bt.command("status").description("show triage settings and watch rules").action(()=>{let e=j().whatsappTriage,o=!!process.env[e.secretEnv];console.log(),console.log(` WhatsApp triage: ${e.enabled?Re.green("on"):Re.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${o?Re.green("set in this shell"):Re.yellow("not set in this shell; the daemon needs it too")}`),console.log(` Batch: ${e.batchSeconds} s \xB7 auto-acknowledge allowed: ${e.allowAutoAck?"yes":"no"}`),console.log(),e.rules.length===0&&console.log(Re.dim(" no watch rules yet: agentx whatsapp triage rule add <id> --agent <agent> --chat <number or JID>"));for(let t of e.rules){let n=t.quietHours?` \xB7 quiet ${t.quietHours.start}\u2013${t.quietHours.end}`:"";console.log(` ${t.enabled?Re.green("\u25CF"):Re.dim("\u25CB")} ${Re.bold(t.id)} \u2192 ${t.agent}${n}${t.autoAck?" \xB7 autoAck":""}`),t.chats.length&&console.log(Re.dim(` chats: ${t.chats.join(", ")}`)),t.senders.length&&console.log(Re.dim(` senders: ${t.senders.join(", ")}`))}console.log()});bt.command("on").description("turn triage on").action(()=>Zn(e=>(e.enabled=!0,"WhatsApp triage is on")));bt.command("off").description("turn triage off").action(()=>Zn(e=>(e.enabled=!1,"WhatsApp triage is off")));bt.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let o=Do();o||(console.error(Re.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let t=new ml(o).recent(Math.max(1,Number(e.limit)||20));if(t.length===0){console.log(Re.dim(" nothing triaged yet"));return}for(let n of t){let s=new Date(n.at).toISOString().slice(0,16).replace("T"," "),i=n.error?Re.red(n.error):`${Re.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${Re.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?Re.dim(` draft whatsapp:${n.draftId}`):""}`)}});var ca=bt.command("rule").description("add, remove, enable or disable a watch rule");ca.command("add <id>").description("watch a chat (or people) and send its messages to an agent").requiredOption("--agent <agent>","the agent that triages").option("--chat <jid>","a chat to watch: phone number, contact JID or group JID (repeatable)",ap).option("--sender <jid>","only messages from this person (repeatable)",ap).option("--prompt <text>","extra instructions for the agent").option("--quiet <range>","no notifications in this window, e.g. 22:00-07:00").option("--auto-ack","send short acknowledgements without asking (also needs allowAutoAck)").action((e,o)=>Zn((t,n)=>{if(!n.agents?.[o.agent])throw new Error(`No agent "${o.agent}" on this computer.`);if(t.rules.some(i=>i.id===e))throw new Error(`Watch rule "${e}" already exists.`);let s={id:e,agent:o.agent,chats:o.chat??[],senders:o.sender??[]};if(o.prompt&&(s.prompt=o.prompt),o.quiet){let i=String(o.quiet).match(/^(\d{2}:\d{2})-(\d{2}:\d{2})$/);if(!i)throw new Error("--quiet looks like 22:00-07:00");s.quietHours={start:i[1],end:i[2]}}return o.autoAck&&(s.autoAck=!0),t.rules.push(s),`added watch rule "${e}" \u2192 ${o.agent}`}));ca.command("remove <id>").description("delete a watch rule").action(e=>Zn(o=>(cp(o,e),o.rules=o.rules.filter(t=>t.id!==e),`removed watch rule "${e}"`)));for(let[e,o]of[["enable",!0],["disable",!1]])ca.command(`${e} <id>`).description(`${e} a watch rule`).action(t=>Zn(n=>(cp(n,t).enabled=o,`watch rule "${t}" ${o?"enabled":"disabled"}`)));var Ro=new G$().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Ro.addCommand(bt);Ro.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await es("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(_e.dim(" no chats cached yet"));return}console.log(),console.log(_e.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?_e.cyan("group"):_e.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${_e.dim(n.jid.padEnd(40))} ${_e.dim(i)}`)}console.log()}catch(o){mn(o)}});Ro.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await es("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(_e.dim(" no contacts cached yet"));return}console.log(),console.log(_e.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${_e.dim(i)} ${_e.dim(n.jid)}`)}console.log()}catch(o){mn(o)}});Ro.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await da("/whatsapp/ingest",o);la(t,!!e.dryRun)}catch(o){mn(o)}});Ro.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await da("/whatsapp/ingest",t);la(n,!!o.dryRun)}catch(t){mn(t)}});Ro.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await da("/whatsapp/ingest",t);la(n,!!o.dryRun)}catch(t){mn(t)}});Ro.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await es("/whatsapp/state"),o=await es("/whatsapp/chats"),t=await es("/whatsapp/contacts");console.log(),console.log(_e.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){mn(e)}});function la(e,o){if(console.log(),console.log(_e.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(_e.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(_e.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(_e.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(_e.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(_e.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function lp(){try{let e=j(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function es(e){let o=await fetch(`${lp()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function da(e,o){let t=await fetch(`${lp()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function mn(e){console.error(_e.red(` ${e.message||e}`)),process.exit(1)}oe();import{Command as z$}from"commander";import pe from"chalk";import{existsSync as Y$,mkdirSync as dp,writeFileSync as os}from"fs";import{join as pn,resolve as V$}from"path";var ts=new z$().name("plugin").description("manage agentx plugins (Move B)");ts.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=j().plugins??[];if(console.log(),o.length===0){console.log(pe.dim(" No plugins configured.")),console.log(pe.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(pe.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${pe.cyan(t)}`);console.log(),console.log(pe.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(pe.red(` ${e.message}`)),process.exitCode=1}});ts.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(pe.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=V$(o.cwd,t);Y$(n)&&!o.force&&(console.log(pe.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),dp(n,{recursive:!0}),dp(pn(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;os(pn(n,"package.json"),Z$(e,s)),os(pn(n,"tsconfig.json"),eb()),os(pn(n,"src/index.ts"),ob(e)),os(pn(n,"README.md"),tb(e,s)),os(pn(n,".gitignore"),nb()),console.log(),console.log(pe.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(pe.bold(" Next steps:")),console.log(pe.dim(` cd ${t}`)),console.log(pe.dim(" pnpm install")),console.log(pe.dim(" pnpm build")),console.log(pe.dim(" pnpm link --global # for local testing")),console.log(pe.dim(" # then in your agentx project:")),console.log(pe.dim(` pnpm link --global ${e}`)),console.log(pe.dim(` agentx config set plugins[0] "${e}"`)),console.log(pe.dim(" agentx plugin doctor")),console.log()});ts.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=j().plugins??[];if(console.log(),o.length===0){console.log(pe.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await K$(n);s.kind==="ok"?console.log(` ${pe.green("\u2713")} ${pe.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${pe.red("\u2717")} ${pe.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(pe.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(pe.red(` ${e.message}`)),process.exitCode=1}});async function K$(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=X$(o);if(!Q$(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Gc.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function X$(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function Q$(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Z$(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
593
- `}function eb(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
594
- `}function ob(e){return`// ${e} \u2014 AgentX plugin
592
+ `),process.exit(c.error?1:0)});function ap(e){console.error(`agentx exec: ${e}`),process.exit(1)}oe();import{Command as Y$}from"commander";import _e from"chalk";import{Command as z$}from"commander";import Re from"chalk";oe();rs();var bt=new z$("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function Zn(e){let o="",t=await ie(n=>{n.whatsappTriage=n.whatsappTriage&&typeof n.whatsappTriage=="object"?n.whatsappTriage:{},n.whatsappTriage.rules=Array.isArray(n.whatsappTriage.rules)?n.whatsappTriage.rules:[],o=e(n.whatsappTriage,n)});t.success||(console.error(Re.red(`\u2717 ${t.error}`)),process.exit(1)),console.log(Re.green(`\u2713 ${o}`)),t.reloaded&&console.log(Re.dim(" daemon hot-reloaded"))}function dp(e,o){let t=e.rules.find(n=>n.id===o);if(!t)throw new Error(`No watch rule "${o}". See \`agentx whatsapp triage status\`.`);return t}var lp=(e,o=[])=>[...o,e];bt.command("status").description("show triage settings and watch rules").action(()=>{let e=T().whatsappTriage,o=!!process.env[e.secretEnv];console.log(),console.log(` WhatsApp triage: ${e.enabled?Re.green("on"):Re.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${o?Re.green("set in this shell"):Re.yellow("not set in this shell; the daemon needs it too")}`),console.log(` Batch: ${e.batchSeconds} s \xB7 auto-acknowledge allowed: ${e.allowAutoAck?"yes":"no"}`),console.log(),e.rules.length===0&&console.log(Re.dim(" no watch rules yet: agentx whatsapp triage rule add <id> --agent <agent> --chat <number or JID>"));for(let t of e.rules){let n=t.quietHours?` \xB7 quiet ${t.quietHours.start}\u2013${t.quietHours.end}`:"";console.log(` ${t.enabled?Re.green("\u25CF"):Re.dim("\u25CB")} ${Re.bold(t.id)} \u2192 ${t.agent}${n}${t.autoAck?" \xB7 autoAck":""}`),t.chats.length&&console.log(Re.dim(` chats: ${t.chats.join(", ")}`)),t.senders.length&&console.log(Re.dim(` senders: ${t.senders.join(", ")}`))}console.log()});bt.command("on").description("turn triage on").action(()=>Zn(e=>(e.enabled=!0,"WhatsApp triage is on")));bt.command("off").description("turn triage off").action(()=>Zn(e=>(e.enabled=!1,"WhatsApp triage is off")));bt.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let o=Do();o||(console.error(Re.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let t=new pl(o).recent(Math.max(1,Number(e.limit)||20));if(t.length===0){console.log(Re.dim(" nothing triaged yet"));return}for(let n of t){let s=new Date(n.at).toISOString().slice(0,16).replace("T"," "),i=n.error?Re.red(n.error):`${Re.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${Re.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?Re.dim(` draft whatsapp:${n.draftId}`):""}`)}});var ca=bt.command("rule").description("add, remove, enable or disable a watch rule");ca.command("add <id>").description("watch a chat (or people) and send its messages to an agent").requiredOption("--agent <agent>","the agent that triages").option("--chat <jid>","a chat to watch: phone number, contact JID or group JID (repeatable)",lp).option("--sender <jid>","only messages from this person (repeatable)",lp).option("--prompt <text>","extra instructions for the agent").option("--quiet <range>","no notifications in this window, e.g. 22:00-07:00").option("--auto-ack","send short acknowledgements without asking (also needs allowAutoAck)").action((e,o)=>Zn((t,n)=>{if(!n.agents?.[o.agent])throw new Error(`No agent "${o.agent}" on this computer.`);if(t.rules.some(i=>i.id===e))throw new Error(`Watch rule "${e}" already exists.`);let s={id:e,agent:o.agent,chats:o.chat??[],senders:o.sender??[]};if(o.prompt&&(s.prompt=o.prompt),o.quiet){let i=String(o.quiet).match(/^(\d{2}:\d{2})-(\d{2}:\d{2})$/);if(!i)throw new Error("--quiet looks like 22:00-07:00");s.quietHours={start:i[1],end:i[2]}}return o.autoAck&&(s.autoAck=!0),t.rules.push(s),`added watch rule "${e}" \u2192 ${o.agent}`}));ca.command("remove <id>").description("delete a watch rule").action(e=>Zn(o=>(dp(o,e),o.rules=o.rules.filter(t=>t.id!==e),`removed watch rule "${e}"`)));for(let[e,o]of[["enable",!0],["disable",!1]])ca.command(`${e} <id>`).description(`${e} a watch rule`).action(t=>Zn(n=>(dp(n,t).enabled=o,`watch rule "${t}" ${o?"enabled":"disabled"}`)));var Ro=new Y$().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Ro.addCommand(bt);Ro.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await es("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(_e.dim(" no chats cached yet"));return}console.log(),console.log(_e.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?_e.cyan("group"):_e.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${_e.dim(n.jid.padEnd(40))} ${_e.dim(i)}`)}console.log()}catch(o){mn(o)}});Ro.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await es("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(_e.dim(" no contacts cached yet"));return}console.log(),console.log(_e.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${_e.dim(i)} ${_e.dim(n.jid)}`)}console.log()}catch(o){mn(o)}});Ro.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await da("/whatsapp/ingest",o);la(t,!!e.dryRun)}catch(o){mn(o)}});Ro.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await da("/whatsapp/ingest",t);la(n,!!o.dryRun)}catch(t){mn(t)}});Ro.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await da("/whatsapp/ingest",t);la(n,!!o.dryRun)}catch(t){mn(t)}});Ro.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await es("/whatsapp/state"),o=await es("/whatsapp/chats"),t=await es("/whatsapp/contacts");console.log(),console.log(_e.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){mn(e)}});function la(e,o){if(console.log(),console.log(_e.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(_e.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(_e.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(_e.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(_e.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(_e.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function gp(){try{let e=T(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function es(e){let o=await fetch(`${gp()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function da(e,o){let t=await fetch(`${gp()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function mn(e){console.error(_e.red(` ${e.message||e}`)),process.exit(1)}oe();import{Command as V$}from"commander";import pe from"chalk";import{existsSync as K$,mkdirSync as mp,writeFileSync as os}from"fs";import{join as pn,resolve as X$}from"path";var ts=new V$().name("plugin").description("manage agentx plugins (Move B)");ts.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=T().plugins??[];if(console.log(),o.length===0){console.log(pe.dim(" No plugins configured.")),console.log(pe.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(pe.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${pe.cyan(t)}`);console.log(),console.log(pe.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(pe.red(` ${e.message}`)),process.exitCode=1}});ts.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(pe.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=X$(o.cwd,t);K$(n)&&!o.force&&(console.log(pe.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),mp(n,{recursive:!0}),mp(pn(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;os(pn(n,"package.json"),ob(e,s)),os(pn(n,"tsconfig.json"),tb()),os(pn(n,"src/index.ts"),nb(e)),os(pn(n,"README.md"),sb(e,s)),os(pn(n,".gitignore"),ib()),console.log(),console.log(pe.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(pe.bold(" Next steps:")),console.log(pe.dim(` cd ${t}`)),console.log(pe.dim(" pnpm install")),console.log(pe.dim(" pnpm build")),console.log(pe.dim(" pnpm link --global # for local testing")),console.log(pe.dim(" # then in your agentx project:")),console.log(pe.dim(` pnpm link --global ${e}`)),console.log(pe.dim(` agentx config set plugins[0] "${e}"`)),console.log(pe.dim(" agentx plugin doctor")),console.log()});ts.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=T().plugins??[];if(console.log(),o.length===0){console.log(pe.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Q$(n);s.kind==="ok"?console.log(` ${pe.green("\u2713")} ${pe.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${pe.red("\u2717")} ${pe.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(pe.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(pe.red(` ${e.message}`)),process.exitCode=1}});async function Q$(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Z$(o);if(!eb(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=zc.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function Z$(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function eb(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function ob(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
593
+ `}function tb(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
594
+ `}function nb(e){return`// ${e} \u2014 AgentX plugin
595
595
  //
596
596
  // A plugin's default export is { manifest, setup }. The daemon calls
597
597
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -627,7 +627,7 @@ const plugin = {
627
627
  }
628
628
 
629
629
  export default plugin
630
- `}function tb(e,o){return`# ${e}
630
+ `}function sb(e,o){return`# ${e}
631
631
 
632
632
  ${o}
633
633
 
@@ -654,24 +654,24 @@ agentx plugin doctor
654
654
  \`\`\`
655
655
 
656
656
  Restart the daemon to activate.
657
- `}function nb(){return`node_modules/
657
+ `}function ib(){return`node_modules/
658
658
  dist/
659
659
  *.log
660
660
  .env
661
- `}import{Command as sb}from"commander";import De from"chalk";import{writeFileSync as ib,mkdirSync as rb,existsSync as vi,readFileSync as gp,appendFileSync as mp}from"fs";import{resolve as un,dirname as fp}from"path";import{homedir as ma}from"os";var hp=new sb().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-Y5BSOGQQ.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=lb(t);break;case"bash":s=ub(t);break;case"fish":s=fb(t);break;default:console.error(De.red(`unsupported shell: ${n}`)),console.error(De.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?un(String(e.output)):ab(n);rb(fp(i),{recursive:!0}),ib(i,s),console.log(De.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),cb(n,i,!!e.yes)});function ab(e){let o=ma();switch(e){case"zsh":return un(o,".zsh","completions","_agentx");case"bash":return un(o,".bash_completion.d","agentx.bash");case"fish":return un(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function cb(e,o,t){if(e==="zsh"){let n=un(ma(),".zshrc"),s=fp(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=vi(n)?gp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(De.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&vi(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),mp(n,g.join(`
661
+ `}import{Command as rb}from"commander";import De from"chalk";import{writeFileSync as ab,mkdirSync as cb,existsSync as vi,readFileSync as pp,appendFileSync as up}from"fs";import{resolve as un,dirname as yp}from"path";import{homedir as ma}from"os";var wp=new rb().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-QKNNDRP6.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=gb(t);break;case"bash":s=hb(t);break;case"fish":s=yb(t);break;default:console.error(De.red(`unsupported shell: ${n}`)),console.error(De.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?un(String(e.output)):lb(n);cb(yp(i),{recursive:!0}),ab(i,s),console.log(De.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),db(n,i,!!e.yes)});function lb(e){let o=ma();switch(e){case"zsh":return un(o,".zsh","completions","_agentx");case"bash":return un(o,".bash_completion.d","agentx.bash");case"fish":return un(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function db(e,o,t){if(e==="zsh"){let n=un(ma(),".zshrc"),s=yp(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=vi(n)?pp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(De.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&vi(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),up(n,g.join(`
662
662
  `)+`
663
- `),console.log(De.green("\u2713 Patched ~/.zshrc")),console.log(De.dim("Reload your shell: exec zsh"));return}console.log(De.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(De.cyan(` ${i}`)),l&&console.log(De.cyan(` ${r}`)),console.log(),console.log(De.dim("Then reload: exec zsh")),console.log(De.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=un(ma(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((vi(n)?gp(n,"utf-8"):"").includes(o)){console.log(De.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&vi(n)){mp(n,`
663
+ `),console.log(De.green("\u2713 Patched ~/.zshrc")),console.log(De.dim("Reload your shell: exec zsh"));return}console.log(De.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(De.cyan(` ${i}`)),l&&console.log(De.cyan(` ${r}`)),console.log(),console.log(De.dim("Then reload: exec zsh")),console.log(De.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=un(ma(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((vi(n)?pp(n,"utf-8"):"").includes(o)){console.log(De.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&vi(n)){up(n,`
664
664
  # agentx completion
665
665
  ${s}
666
- `),console.log(De.green("\u2713 Patched ~/.bashrc")),console.log(De.dim("Reload your shell: exec bash"));return}console.log(De.dim("Add this to ~/.bashrc:")),console.log(De.cyan(` ${s}`)),console.log(),console.log(De.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(De.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Xe(e){return e._name||e.name()||""}function et(e){return e.commands.filter(o=>{let t=Xe(o);return!(!t||t==="help")})}function ns(e){return e.options.filter(o=>!o.hidden)}function lb(e){let o=[];return o.push("#compdef agentx"),o.push(""),yp(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
667
- `)}function pp(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function yp(e,o,t){let n=et(e),i=ns(e).map(mb).filter(c=>!!c),r=pp(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(pb).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let l=pp([...o,Xe(c)]);t.push(` (${Xe(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)yp(c,[...o,Xe(c)],t)}function db(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function gb(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function mb(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=db(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function pb(e){let o=gb(e.description()||"");return`'${Xe(e)}[${o}]'`}function ub(e){let o=et(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Xe).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=et(n).map(Xe),i=up(n);if(t.push(` ${Xe(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of et(n)){let a=up(r);t.push(` ${Xe(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
668
- `)}function up(e){let o=[];for(let t of ns(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function fb(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of et(e)){let n=pa(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Xe(t)}" -d "${n}"`)}o.push("");for(let t of ns(e)){let n=ga(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of et(e)){let n=Xe(t);o.push(`# ${n}`);for(let s of ns(t)){let i=ga(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of et(t)){let i=pa(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${et(t).map(Xe).join(" ")}" -a "${Xe(s)}" -d "${i}"`);for(let r of ns(s)){let a=ga(r,[`__fish_seen_subcommand_from ${Xe(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
669
- `)}function pa(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ga(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=pa(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}import{Command as yb}from"commander";import hn from"chalk";import{readFile as wb}from"node:fs/promises";var fn="anis-marrouchi/agentx",ua=`https://raw.githubusercontent.com/${fn}/main/contrib/models.json`,Si=`https://github.com/${fn}/issues/new/choose`,$p=`https://github.com/${fn}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,wp=8e3,xi={bug:{template:"bug_report.yml",titlePrefix:"Bug: ",fields:[{id:"what-happened",required:!0},{id:"environment",required:!0},{id:"config",required:!1},{id:"logs",required:!1}],footerField:"environment"},enhancement:{template:"enhancement.yml",titlePrefix:"Enh: ",fields:[{id:"area",required:!0},{id:"today",required:!0},{id:"better",required:!0}],footerField:"better"},feature:{template:"feature_request.yml",titlePrefix:"Feat: ",fields:[{id:"problem",required:!0},{id:"proposal",required:!0},{id:"alternatives",required:!1}],footerField:"proposal"},integration:{template:"integration.yml",titlePrefix:"Integration: ",fields:[{id:"kind",required:!0},{id:"name",required:!0},{id:"use-case",required:!0},{id:"notes",required:!1}],footerField:"use-case"},idea:{template:"idea.yml",titlePrefix:"Idea: ",fields:[{id:"idea",required:!0},{id:"why",required:!0}],footerField:"why"},docs:{template:"docs.yml",titlePrefix:"Docs: ",fields:[{id:"page",required:!0},{id:"problem",required:!0},{id:"suggestion",required:!1}],footerField:"problem"}};function fa(e,o){let t=e.trim().toLowerCase();return t?o.models.some(n=>{let s=n.id.toLowerCase();return t===s||t.startsWith(`${s}-`)||(n.aliases??[]).some(i=>i.toLowerCase()===t)}):!1}function ha(e,o){return[`The model "${e}" is not on the recommended list for drafting AgentX issues.`,`The list (${o.models.map(t=>t.id).join(", ")}) keeps drafts clear and consistent; it says nothing about you or your idea.`,`Please write the issue yourself with the web form, which is always available: ${Si}`].join(`
670
- `)}function hb(e){return`---
671
- _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function bp(e,o){let t=xi[e.category];if(!t)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(xi).join(", ")}`);let n=new Set(t.fields.map(l=>l.id)),s=Object.keys(e.fields).filter(l=>!n.has(l));if(s.length)throw new Error(`Unknown field(s) for ${e.category}: ${s.join(", ")}. Expected: ${[...n].join(", ")}`);let i=t.fields.filter(l=>l.required&&!e.fields[l.id]?.trim()).map(l=>l.id);if(i.length)throw new Error(`Missing required field(s) for ${e.category}: ${i.join(", ")}`);let r=e.title.trim();if(!r)throw new Error("The issue needs a title");r.toLowerCase().startsWith(t.titlePrefix.toLowerCase())||(r=t.titlePrefix+r);let a=new URLSearchParams({template:t.template,title:r});for(let l of t.fields){let g=e.fields[l.id]?.trim()??"";l.id===t.footerField&&(g=`${g}
672
-
673
- ${hb({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${fn}/issues/new?${a.toString()}`;if(c.length>wp)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${wp}). Shorten it, or paste it into the web form.`);return c}async function kp(e,o=fetch){let t=`repo:${fn} is:issue is:open ${e}`,n=await o(`https://api.github.com/search/issues?per_page=10&q=${encodeURIComponent(t)}`,{headers:{accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`GitHub search failed (HTTP ${n.status}). Search by hand: https://github.com/${fn}/issues`);return((await n.json()).items??[]).map(i=>({number:i.number,title:i.title,url:i.html_url,votes:i.reactions?.["+1"]??0})).sort((i,r)=>r.votes-i.votes)}async function ya(e,o=fetch){let t;if(/^https?:\/\//.test(e)){let s=await o(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Could not read the model list (HTTP ${s.status}) from ${e}`);t=await s.text()}else{let{readFile:s}=await import("node:fs/promises");t=await s(e,"utf8")}let n=JSON.parse(t);if(!Array.isArray(n.models))throw new Error(`The model list at ${e} has no "models" array`);return n}var ss=new yb().name("contribute").description("help you file a clear AgentX issue \u2014 check the model, find duplicates, build a pre-filled form link").action(()=>{console.log(),console.log(hn.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${Si}`),console.log(" 2. Let your agent help: install the skill with"),console.log(hn.cyan(" agentx skill install anis-marrouchi/agentx/agentx-contribute")),console.log(" then ask your agent to help you file an AgentX issue."),console.log(),console.log(` Before posting, please \u{1F44D} the open requests you care about: ${$p}`),console.log(` Categories: ${Object.keys(xi).join(", ")}`),console.log()});ss.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",ua).action(async(e,o)=>{try{let t=await ya(o.models);if(fa(e,t)){console.log(hn.green(` "${e}" is on the recommended list.`));return}console.log(ha(e,t)),process.exitCode=1}catch(t){console.error(hn.red(` ${t.message}`)),console.error(` You can always write the issue yourself: ${Si}`),process.exitCode=1}});ss.command("search <words...>").description("list open issues that match, most-voted first \u2014 check for duplicates before drafting").action(async e=>{try{let o=await kp(e.join(" "));if(!o.length){console.log(" No open issue matches. It looks new.");return}for(let t of o)console.log(` #${t.number} \u{1F44D} ${t.votes} ${t.title}
674
- ${t.url}`)}catch(o){console.error(hn.red(` ${o.message}`)),process.exitCode=1}});ss.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",ua).action(async(e,o)=>{try{let t=await ya(o.models);if(!fa(o.model,t)){console.log(ha(o.model,t)),process.exitCode=1;return}let n=e==="-"?await $b():await wb(e,"utf8"),s=JSON.parse(n),{version:i}=await gs(),r=bp({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(hn.red(` ${t.message}`)),process.exitCode=1}});async function $b(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function qC(){let e=await gs(),o=new bb().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=Wl(n);Jl(s)&&Fl("cli",s)});for(let t of[fd,ud,en,Dt,Lt,ro,Cl,it,Ds,jo,Co,Xt,im,Vo,_s,Jm,Go,Pd,Hd,qn,tg,rg,lg,mg,pg,Cg,_g,Dg,Yt,Gn,Ym,In,Fo,hp,ss])o.addCommand(t);for(let t of vp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=vp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,kb(t,74," "),""].join(`
675
- `)}),o}var vp=[te,nn,Zo,ho,_n,Vt,Ke,No,Ko,ft,cn,ln,Bo,Ge,Wt,ei,Um,Fm,Ao,to,Yl,at,ts,mr,Qo,no,Ut,pr,fi,xo,Ro,sp,rp,zm];function kb(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(`
676
- `)}export{qC as buildProgram};
677
- //# sourceMappingURL=program-Y5BSOGQQ.js.map
666
+ `),console.log(De.green("\u2713 Patched ~/.bashrc")),console.log(De.dim("Reload your shell: exec bash"));return}console.log(De.dim("Add this to ~/.bashrc:")),console.log(De.cyan(` ${s}`)),console.log(),console.log(De.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(De.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Xe(e){return e._name||e.name()||""}function et(e){return e.commands.filter(o=>{let t=Xe(o);return!(!t||t==="help")})}function ns(e){return e.options.filter(o=>!o.hidden)}function gb(e){let o=[];return o.push("#compdef agentx"),o.push(""),$p(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
667
+ `)}function fp(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function $p(e,o,t){let n=et(e),i=ns(e).map(ub).filter(c=>!!c),r=fp(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(fb).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let l=fp([...o,Xe(c)]);t.push(` (${Xe(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)$p(c,[...o,Xe(c)],t)}function mb(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function pb(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function ub(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=mb(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function fb(e){let o=pb(e.description()||"");return`'${Xe(e)}[${o}]'`}function hb(e){let o=et(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Xe).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=et(n).map(Xe),i=hp(n);if(t.push(` ${Xe(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of et(n)){let a=hp(r);t.push(` ${Xe(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
668
+ `)}function hp(e){let o=[];for(let t of ns(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function yb(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of et(e)){let n=pa(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Xe(t)}" -d "${n}"`)}o.push("");for(let t of ns(e)){let n=ga(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of et(e)){let n=Xe(t);o.push(`# ${n}`);for(let s of ns(t)){let i=ga(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of et(t)){let i=pa(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${et(t).map(Xe).join(" ")}" -a "${Xe(s)}" -d "${i}"`);for(let r of ns(s)){let a=ga(r,[`__fish_seen_subcommand_from ${Xe(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
669
+ `)}function pa(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ga(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=pa(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}import{Command as $b}from"commander";import hn from"chalk";import{readFile as bb}from"node:fs/promises";var fn="anis-marrouchi/agentx",ua=`https://raw.githubusercontent.com/${fn}/main/contrib/models.json`,Si=`https://github.com/${fn}/issues/new/choose`,kp=`https://github.com/${fn}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,bp=8e3,xi={bug:{template:"bug_report.yml",titlePrefix:"Bug: ",fields:[{id:"what-happened",required:!0},{id:"environment",required:!0},{id:"config",required:!1},{id:"logs",required:!1}],footerField:"environment"},enhancement:{template:"enhancement.yml",titlePrefix:"Enh: ",fields:[{id:"area",required:!0},{id:"today",required:!0},{id:"better",required:!0}],footerField:"better"},feature:{template:"feature_request.yml",titlePrefix:"Feat: ",fields:[{id:"problem",required:!0},{id:"proposal",required:!0},{id:"alternatives",required:!1}],footerField:"proposal"},integration:{template:"integration.yml",titlePrefix:"Integration: ",fields:[{id:"kind",required:!0},{id:"name",required:!0},{id:"use-case",required:!0},{id:"notes",required:!1}],footerField:"use-case"},idea:{template:"idea.yml",titlePrefix:"Idea: ",fields:[{id:"idea",required:!0},{id:"why",required:!0}],footerField:"why"},docs:{template:"docs.yml",titlePrefix:"Docs: ",fields:[{id:"page",required:!0},{id:"problem",required:!0},{id:"suggestion",required:!1}],footerField:"problem"}};function fa(e,o){let t=e.trim().toLowerCase();return t?o.models.some(n=>{let s=n.id.toLowerCase();return t===s||t.startsWith(`${s}-`)||(n.aliases??[]).some(i=>i.toLowerCase()===t)}):!1}function ha(e,o){return[`The model "${e}" is not on the recommended list for drafting AgentX issues.`,`The list (${o.models.map(t=>t.id).join(", ")}) keeps drafts clear and consistent; it says nothing about you or your idea.`,`Please write the issue yourself with the web form, which is always available: ${Si}`].join(`
670
+ `)}function wb(e){return`---
671
+ _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function vp(e,o){let t=xi[e.category];if(!t)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(xi).join(", ")}`);let n=new Set(t.fields.map(l=>l.id)),s=Object.keys(e.fields).filter(l=>!n.has(l));if(s.length)throw new Error(`Unknown field(s) for ${e.category}: ${s.join(", ")}. Expected: ${[...n].join(", ")}`);let i=t.fields.filter(l=>l.required&&!e.fields[l.id]?.trim()).map(l=>l.id);if(i.length)throw new Error(`Missing required field(s) for ${e.category}: ${i.join(", ")}`);let r=e.title.trim();if(!r)throw new Error("The issue needs a title");r.toLowerCase().startsWith(t.titlePrefix.toLowerCase())||(r=t.titlePrefix+r);let a=new URLSearchParams({template:t.template,title:r});for(let l of t.fields){let g=e.fields[l.id]?.trim()??"";l.id===t.footerField&&(g=`${g}
672
+
673
+ ${wb({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${fn}/issues/new?${a.toString()}`;if(c.length>bp)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${bp}). Shorten it, or paste it into the web form.`);return c}async function xp(e,o=fetch){let t=`repo:${fn} is:issue is:open ${e}`,n=await o(`https://api.github.com/search/issues?per_page=10&q=${encodeURIComponent(t)}`,{headers:{accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`GitHub search failed (HTTP ${n.status}). Search by hand: https://github.com/${fn}/issues`);return((await n.json()).items??[]).map(i=>({number:i.number,title:i.title,url:i.html_url,votes:i.reactions?.["+1"]??0})).sort((i,r)=>r.votes-i.votes)}async function ya(e,o=fetch){let t;if(/^https?:\/\//.test(e)){let s=await o(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Could not read the model list (HTTP ${s.status}) from ${e}`);t=await s.text()}else{let{readFile:s}=await import("node:fs/promises");t=await s(e,"utf8")}let n=JSON.parse(t);if(!Array.isArray(n.models))throw new Error(`The model list at ${e} has no "models" array`);return n}var ss=new $b().name("contribute").description("help you file a clear AgentX issue \u2014 check the model, find duplicates, build a pre-filled form link").action(()=>{console.log(),console.log(hn.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${Si}`),console.log(" 2. Let your agent help: install the skill with"),console.log(hn.cyan(" agentx skill install anis-marrouchi/agentx/agentx-contribute")),console.log(" then ask your agent to help you file an AgentX issue."),console.log(),console.log(` Before posting, please \u{1F44D} the open requests you care about: ${kp}`),console.log(` Categories: ${Object.keys(xi).join(", ")}`),console.log()});ss.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",ua).action(async(e,o)=>{try{let t=await ya(o.models);if(fa(e,t)){console.log(hn.green(` "${e}" is on the recommended list.`));return}console.log(ha(e,t)),process.exitCode=1}catch(t){console.error(hn.red(` ${t.message}`)),console.error(` You can always write the issue yourself: ${Si}`),process.exitCode=1}});ss.command("search <words...>").description("list open issues that match, most-voted first \u2014 check for duplicates before drafting").action(async e=>{try{let o=await xp(e.join(" "));if(!o.length){console.log(" No open issue matches. It looks new.");return}for(let t of o)console.log(` #${t.number} \u{1F44D} ${t.votes} ${t.title}
674
+ ${t.url}`)}catch(o){console.error(hn.red(` ${o.message}`)),process.exitCode=1}});ss.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",ua).action(async(e,o)=>{try{let t=await ya(o.models);if(!fa(o.model,t)){console.log(ha(o.model,t)),process.exitCode=1;return}let n=e==="-"?await kb():await bb(e,"utf8"),s=JSON.parse(n),{version:i}=await gs(),r=vp({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(hn.red(` ${t.message}`)),process.exitCode=1}});async function kb(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function FC(){let e=await gs(),o=new vb().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=Wl(n);Jl(s)&&Fl("cli",s)});for(let t of[fd,ud,en,Dt,Lt,ro,Il,it,Ds,jo,Co,Xt,am,Vo,_s,Hm,Go,Pd,Hd,qn,tg,rg,lg,mg,pg,Cg,_g,Dg,Yt,Gn,Km,In,Fo,wp,ss])o.addCommand(t);for(let t of Sp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Sp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,xb(t,74," "),""].join(`
675
+ `)}),o}var Sp=[te,nn,Zo,ho,_n,Vt,Ke,No,Ko,ft,cn,ln,Bo,Ge,Wt,ei,Wm,Jm,Ao,to,Yl,at,ts,mr,Qo,no,Ut,pr,fi,xo,Ro,rp,cp,Vm];function xb(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(`
676
+ `)}export{FC as buildProgram};
677
+ //# sourceMappingURL=program-QKNNDRP6.js.map