agentix-cli 0.110.0 → 0.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +77 -30
  2. package/apps/mac-voice/Sources/AgentXVoice/PanelAnswer.swift +3 -2
  3. package/apps/mac-voice/Sources/AgentXVoice/PillForm.swift +55 -0
  4. package/apps/mac-voice/Sources/AgentXVoice/PillMenu.swift +8 -7
  5. package/apps/mac-voice/Sources/AgentXVoice/SettingsLook.swift +2 -2
  6. package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +5 -6
  7. package/apps/mac-voice/Sources/AgentXVoice/main.swift +7 -6
  8. package/dist/{App-4VWAQOVA.js → App-T4Q7SW6M.js} +2 -2
  9. package/dist/{ChatApp-KOTGUDZH.js → ChatApp-BKUJUIDL.js} +2 -2
  10. package/dist/{agent-CGRHC2IS.js → agent-YZVEXFE7.js} +2 -2
  11. package/dist/{board-dashboard-SAYBNLZW.js → board-dashboard-3TVUCOSI.js} +411 -257
  12. package/dist/board-dashboard-3TVUCOSI.js.map +1 -0
  13. package/dist/{chunk-UVMCAZL7.js → chunk-4FU4BFCH.js} +2 -2
  14. package/dist/{chunk-NIW75USA.js → chunk-4NFDDTGA.js} +2 -2
  15. package/dist/{chunk-2VGYRETU.js → chunk-53OS4TDU.js} +2 -2
  16. package/dist/{chunk-J32LSOBJ.js → chunk-7UNS34CN.js} +2 -2
  17. package/dist/chunk-AV7T3SYT.js +111 -0
  18. package/dist/chunk-AV7T3SYT.js.map +1 -0
  19. package/dist/chunk-DTQQ4DAY.js +154 -0
  20. package/dist/chunk-DTQQ4DAY.js.map +1 -0
  21. package/dist/{chunk-SFPMS55Z.js → chunk-DUBCOGQB.js} +49 -48
  22. package/dist/chunk-DUBCOGQB.js.map +1 -0
  23. package/dist/{chunk-BFOB6ERR.js → chunk-DXWDVKMX.js} +2 -2
  24. package/dist/{chunk-BZKGQMU2.js → chunk-FBODSJU6.js} +2 -2
  25. package/dist/{chunk-UTV4DRAW.js → chunk-GQMUFSKB.js} +14 -14
  26. package/dist/{chunk-UTV4DRAW.js.map → chunk-GQMUFSKB.js.map} +1 -1
  27. package/dist/{chunk-4UCDWEC4.js → chunk-HCTWKWS3.js} +2 -2
  28. package/dist/{chunk-EC6DKMR5.js → chunk-KDD6FPQ6.js} +238 -238
  29. package/dist/chunk-KDD6FPQ6.js.map +1 -0
  30. package/dist/{chunk-5O6PIO7F.js → chunk-LWYKS5JU.js} +2 -2
  31. package/dist/{chunk-QQAZ6EJP.js → chunk-M2L6S3Z5.js} +2 -2
  32. package/dist/{chunk-6F2E5NQA.js → chunk-QJP37VVA.js} +2 -2
  33. package/dist/{chunk-QFP4YZII.js → chunk-RS2T53EC.js} +2 -2
  34. package/dist/{chunk-E5OV6RTG.js → chunk-RXLU6HJ6.js} +3 -3
  35. package/dist/chunk-RXLU6HJ6.js.map +1 -0
  36. package/dist/{chunk-D7M4WQFU.js → chunk-SIOWVLZG.js} +4 -4
  37. package/dist/chunk-SIOWVLZG.js.map +1 -0
  38. package/dist/{chunk-BG6SOGKT.js → chunk-U52IS3AF.js} +2 -2
  39. package/dist/{chunk-RJ7DASOU.js → chunk-UIBUZ2N3.js} +25 -10
  40. package/dist/chunk-UIBUZ2N3.js.map +1 -0
  41. package/dist/{chunk-MJWJ3JVA.js → chunk-WSKQUKCF.js} +2 -2
  42. package/dist/{chunk-S4NZUPIN.js → chunk-WXQQO2PD.js} +2 -2
  43. package/dist/{chunk-FHI5WPFO.js → chunk-WYSNRZV4.js} +4 -4
  44. package/dist/chunk-WYSNRZV4.js.map +1 -0
  45. package/dist/{chunk-CJR26JUI.js → chunk-XEOT2F4C.js} +2 -2
  46. package/dist/{chunk-3Z5P2CWS.js → chunk-XF26QNAW.js} +2 -2
  47. package/dist/{chunk-CJL5OPNQ.js → chunk-Z7L74GGT.js} +2 -2
  48. package/dist/cli.js +1 -1
  49. package/dist/{client-VYMTUZKN.js → client-O7SPKO5X.js} +2 -2
  50. package/dist/config-ZHQYXFOJ.js +2 -0
  51. package/dist/config-mutator-RS2NTDNO.js +2 -0
  52. package/dist/{doctor-GHUPUBET.js → doctor-XP7O45RC.js} +2 -2
  53. package/dist/{grants-Y667GZAU.js → grants-M4K6WXOO.js} +2 -2
  54. package/dist/index.d.ts +68 -15
  55. package/dist/index.js +1 -1
  56. package/dist/{program-V2JEVJAD.js → program-EZLJIVQX.js} +187 -182
  57. package/dist/program-EZLJIVQX.js.map +1 -0
  58. package/dist/{promote-KY3Y2PVU.js → promote-UGWANGI2.js} +2 -2
  59. package/dist/{query-BYCRYDM3.js → query-ZET7Z5FT.js} +2 -2
  60. package/dist/registry-UXWOY52B.js +2 -0
  61. package/dist/request-planner-W5YLKCGG.js +6 -0
  62. package/dist/request-planner-W5YLKCGG.js.map +1 -0
  63. package/dist/{review-candidates-56ZPJNXW.js → review-candidates-GU4S5VQH.js} +2 -2
  64. package/dist/{routing-WKS2CZYF.js → routing-GJ4VXKIC.js} +2 -2
  65. package/dist/schedule-tool-HD4LWKVC.js +2 -0
  66. package/dist/scheduler-3LEHZHWJ.js +2 -0
  67. package/dist/seat-L6XJ2BFA.js +2 -0
  68. package/dist/select-T7CKKLC2.js +2 -0
  69. package/dist/{select-73JC2YBN.js.map → select-T7CKKLC2.js.map} +1 -1
  70. package/dist/{set-enabled-WQAO4BFF.js → set-enabled-U2HGNY2O.js} +2 -2
  71. package/dist/{surface-usage-CH3SHO77.js → surface-usage-HCJTUS6Z.js} +2 -2
  72. package/dist/{tool-QDU6MY6B.js → tool-2FMWZB4N.js} +2 -2
  73. package/dist/{tool-GCPMPPUE.js → tool-TX622HEB.js} +2 -2
  74. package/dist/wiki-MYJBOJSM.js +2 -0
  75. package/dist/workspace-setup-HAV4CQV7.js +2 -0
  76. package/package.json +2 -1
  77. package/dist/board-dashboard-SAYBNLZW.js.map +0 -1
  78. package/dist/chunk-3TY6YJHO.js +0 -153
  79. package/dist/chunk-3TY6YJHO.js.map +0 -1
  80. package/dist/chunk-D7M4WQFU.js.map +0 -1
  81. package/dist/chunk-E5OV6RTG.js.map +0 -1
  82. package/dist/chunk-EC6DKMR5.js.map +0 -1
  83. package/dist/chunk-FHI5WPFO.js.map +0 -1
  84. package/dist/chunk-RJ7DASOU.js.map +0 -1
  85. package/dist/chunk-SFPMS55Z.js.map +0 -1
  86. package/dist/chunk-UDJAODAB.js +0 -100
  87. package/dist/chunk-UDJAODAB.js.map +0 -1
  88. package/dist/config-J6CNV23P.js +0 -2
  89. package/dist/config-mutator-RGC72OEU.js +0 -2
  90. package/dist/program-V2JEVJAD.js.map +0 -1
  91. package/dist/registry-NDFYNQG4.js +0 -2
  92. package/dist/request-planner-YOUVO3BR.js +0 -2
  93. package/dist/request-planner-YOUVO3BR.js.map +0 -1
  94. package/dist/schedule-tool-4L6QAILN.js +0 -2
  95. package/dist/scheduler-65SE3WJJ.js +0 -2
  96. package/dist/seat-EO3EVBH3.js +0 -2
  97. package/dist/select-73JC2YBN.js +0 -2
  98. package/dist/wiki-CQZE5Z5C.js +0 -2
  99. package/dist/workspace-setup-EA3G42NY.js +0 -2
  100. /package/dist/{App-4VWAQOVA.js.map → App-T4Q7SW6M.js.map} +0 -0
  101. /package/dist/{ChatApp-KOTGUDZH.js.map → ChatApp-BKUJUIDL.js.map} +0 -0
  102. /package/dist/{agent-CGRHC2IS.js.map → agent-YZVEXFE7.js.map} +0 -0
  103. /package/dist/{chunk-UVMCAZL7.js.map → chunk-4FU4BFCH.js.map} +0 -0
  104. /package/dist/{chunk-NIW75USA.js.map → chunk-4NFDDTGA.js.map} +0 -0
  105. /package/dist/{chunk-2VGYRETU.js.map → chunk-53OS4TDU.js.map} +0 -0
  106. /package/dist/{chunk-J32LSOBJ.js.map → chunk-7UNS34CN.js.map} +0 -0
  107. /package/dist/{chunk-BFOB6ERR.js.map → chunk-DXWDVKMX.js.map} +0 -0
  108. /package/dist/{chunk-BZKGQMU2.js.map → chunk-FBODSJU6.js.map} +0 -0
  109. /package/dist/{chunk-4UCDWEC4.js.map → chunk-HCTWKWS3.js.map} +0 -0
  110. /package/dist/{chunk-5O6PIO7F.js.map → chunk-LWYKS5JU.js.map} +0 -0
  111. /package/dist/{chunk-QQAZ6EJP.js.map → chunk-M2L6S3Z5.js.map} +0 -0
  112. /package/dist/{chunk-6F2E5NQA.js.map → chunk-QJP37VVA.js.map} +0 -0
  113. /package/dist/{chunk-QFP4YZII.js.map → chunk-RS2T53EC.js.map} +0 -0
  114. /package/dist/{chunk-BG6SOGKT.js.map → chunk-U52IS3AF.js.map} +0 -0
  115. /package/dist/{chunk-MJWJ3JVA.js.map → chunk-WSKQUKCF.js.map} +0 -0
  116. /package/dist/{chunk-S4NZUPIN.js.map → chunk-WXQQO2PD.js.map} +0 -0
  117. /package/dist/{chunk-CJR26JUI.js.map → chunk-XEOT2F4C.js.map} +0 -0
  118. /package/dist/{chunk-3Z5P2CWS.js.map → chunk-XF26QNAW.js.map} +0 -0
  119. /package/dist/{chunk-CJL5OPNQ.js.map → chunk-Z7L74GGT.js.map} +0 -0
  120. /package/dist/{client-VYMTUZKN.js.map → client-O7SPKO5X.js.map} +0 -0
  121. /package/dist/{config-J6CNV23P.js.map → config-ZHQYXFOJ.js.map} +0 -0
  122. /package/dist/{config-mutator-RGC72OEU.js.map → config-mutator-RS2NTDNO.js.map} +0 -0
  123. /package/dist/{doctor-GHUPUBET.js.map → doctor-XP7O45RC.js.map} +0 -0
  124. /package/dist/{grants-Y667GZAU.js.map → grants-M4K6WXOO.js.map} +0 -0
  125. /package/dist/{promote-KY3Y2PVU.js.map → promote-UGWANGI2.js.map} +0 -0
  126. /package/dist/{query-BYCRYDM3.js.map → query-ZET7Z5FT.js.map} +0 -0
  127. /package/dist/{registry-NDFYNQG4.js.map → registry-UXWOY52B.js.map} +0 -0
  128. /package/dist/{review-candidates-56ZPJNXW.js.map → review-candidates-GU4S5VQH.js.map} +0 -0
  129. /package/dist/{routing-WKS2CZYF.js.map → routing-GJ4VXKIC.js.map} +0 -0
  130. /package/dist/{schedule-tool-4L6QAILN.js.map → schedule-tool-HD4LWKVC.js.map} +0 -0
  131. /package/dist/{scheduler-65SE3WJJ.js.map → scheduler-3LEHZHWJ.js.map} +0 -0
  132. /package/dist/{seat-EO3EVBH3.js.map → seat-L6XJ2BFA.js.map} +0 -0
  133. /package/dist/{set-enabled-WQAO4BFF.js.map → set-enabled-U2HGNY2O.js.map} +0 -0
  134. /package/dist/{surface-usage-CH3SHO77.js.map → surface-usage-HCJTUS6Z.js.map} +0 -0
  135. /package/dist/{tool-QDU6MY6B.js.map → tool-2FMWZB4N.js.map} +0 -0
  136. /package/dist/{tool-GCPMPPUE.js.map → tool-TX622HEB.js.map} +0 -0
  137. /package/dist/{wiki-CQZE5Z5C.js.map → wiki-MYJBOJSM.js.map} +0 -0
  138. /package/dist/{workspace-setup-EA3G42NY.js.map → workspace-setup-HAV4CQV7.js.map} +0 -0
@@ -1,53 +1,53 @@
1
- import{a as rd,b as Ds,g as ad}from"./chunk-CJR26JUI.js";import{a as Jl,c as Hl}from"./chunk-NIW75USA.js";import{A as id,a as so,b as Bl,f as Ut,g as Gl,h as zl,i as Yl,j as Vl,l as Xl,m as Kl,r as Ql,s as Zl,t as sr,u as ed,x as ir,y as sd}from"./chunk-SFPMS55Z.js";import{a as od,c as td,d as nd}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as Bi,b as hc}from"./chunk-RKPAVWXF.js";import{$ as Rn,A as ul,B as fl,C as hl,D as yl,E as wl,F as $l,G as bl,H as Tl,I as Os,J as Co,K as Bo,L as Pt,M as Cs,N as Is,O as Qi,P as jl,Q as Ol,R as Cl,S as Il,T as Nl,U as Rl,V as Mt,W as Lt,X as _l,Y as Dl,Z as Le,_ as Ns,a as Sc,aa as Zi,b as Ec,ba as Pl,ca as ql,da as tr,ea as Fl,fa as Rs,ga as qt,h as ws,ha as _s,i as Oc,ia as nr,j as Cn,ja as Wl,k as $s,l as Nc,m as Rc,n as Hc,o as Gc,p as Es,q as Hi,r as Qc,s as il,t as rl,u as ll,v as dl,w as gl,x as ml,y as pl,z as zi}from"./chunk-EC6DKMR5.js";import{$a as Ul,A as As,C as sl,Ia as Ml,Ja as er,Ka as Ll,La as or,R as In,U as Yi,V as Ts,W as kl,Za as ko,ba as Wo,ca as vl,da as Vi,fa as Xi,ha as xl,ia as Sl,ja as Nn,na as js,qa as El,ra as Al,sa as Ki,w as Gi,x as tl,z as nl}from"./chunk-FHI5WPFO.js";import{a as Ac,d as Tc,e as jc}from"./chunk-BG6SOGKT.js";import{a as bs,b as ks,c as _c,d as Dc,e as Pc,g as Mc,h as Lc,j as qc,k as Uc,l as Fc,m as Wc,p as vs,s as Bc,t as Jc}from"./chunk-S2GAEH2F.js";import"./chunk-GTJIKXDB.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as al,b as cl}from"./chunk-EKJG63EJ.js";import{a as Cc,p as Ic}from"./chunk-5O6PIO7F.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as zc,e as xs,g as Ss}from"./chunk-LQE73AZR.js";import{a as Yc,b as Vc,c as Xc,d as Kc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Zc,e as el,g as ol}from"./chunk-E5OV6RTG.js";import{L as Fo,R as gc,aa as pc,g as Va,r as Xa,y as Ui,z as ec}from"./chunk-3TY6YJHO.js";import{b as Ct,g as Nt,h as hs,i as ys,j as Rt,k as oc,l as at,m as jn,u as mc}from"./chunk-2VGYRETU.js";import{e as ac,f as Wi,k as cc}from"./chunk-GLQLCBJS.js";import{b as It}from"./chunk-6W74CHNW.js";import"./chunk-4UCDWEC4.js";import"./chunk-SFQUP3BP.js";import{b as On}from"./chunk-LLNPKE7H.js";import{a as uc,b as fc}from"./chunk-SHEUCITK.js";import"./chunk-Y4CYQV7G.js";import{a as Ji,e as yc,f as wc,h as $c,i as bc,k as kc,l as vc,m as xc}from"./chunk-S4NZUPIN.js";import{a as _t}from"./chunk-GV7S5BAX.js";import{c as nc}from"./chunk-SZDACK6O.js";import{f as sc,g as ic,h as Fi}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Qa,k as rc}from"./chunk-QQAZ6EJP.js";import{a as lc,b as re,c as Ie,d as Dt,e as dc}from"./chunk-6F2E5NQA.js";import"./chunk-VWTBHLMX.js";import{a as Li}from"./chunk-BFOB6ERR.js";import"./chunk-CJL5OPNQ.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as qi,b as Ka}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Za}from"./chunk-X5C5W3E4.js";import{e as tc}from"./chunk-GSX4NK2N.js";import"./chunk-J32LSOBJ.js";import"./chunk-MYVHVJWZ.js";import{n as Ya}from"./chunk-UDJAODAB.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-BZKGQMU2.js";import{g as Uo,i as fs}from"./chunk-QFP4YZII.js";import"./chunk-WPNRDEHW.js";import{b as Ot,d as za}from"./chunk-2GIDVZ4H.js";import{a as Di,b as ja,c as Bp,d as ms,e as Oa,f as Fa,g as Yp,h as Wa,i as Vp,m as jt,n as Ja,o as Ha,s as Ga,v as bo,w as Tn}from"./chunk-UTV4DRAW.js";import{a as Oo,b as Tt,e as La,f as An}from"./chunk-72SZI2UW.js";import{a as Ba,b as Xp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as jo,b as Wp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as Hp,N as Pi,P as Mi,W as Gp,fa as Pa,ga as Ma,h as Ca,ha as T,i as Ia,ia as us,j as Na,k as Ra,ka as te,l as _a,m as Jp,z as Da}from"./chunk-D7M4WQFU.js";import{a as qo,i as ps}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as qa,k as Ua,l as zp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Kp}from"commander";var cd=new Kp().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 Ec({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()});te();import{Command as Qp}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as ld,existsSync as cr,mkdirSync as rr,mkdtempSync as Zp,readdirSync as eu,rmSync as dd,writeFileSync as gd}from"node:fs";import{dirname as md,join as qe}from"node:path";import{homedir as Ps,release as ou,tmpdir as tu}from"node:os";import{setTimeout as nu}from"node:timers/promises";function Ms(){let e=_c(process.platform,process.arch,ou());if(e)throw new Error(e)}function Ls(){let e=qe(Ps(),"Library/LaunchAgents"),o=[];try{o=eu(e).filter(Mc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:ao("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Lc(e,t)}function _n(e){return`gui/${process.getuid()}/${e.label}`}async function ar(e){try{ao("launchctl",["bootout",_n(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{ao("launchctl",["print",_n(e)],{stdio:"pipe"})}catch{return}await nu(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function pd(e){if(!cr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{ao("launchctl",["print",_n(e)],{stdio:"pipe"})}catch{o=!1}o||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ao("launchctl",["kickstart",_n(e)],{stdio:"pipe"})}function su(){let e=Wc();if(e&&cr(qe(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 Ft=new Qp("desktop").description("install and control the macOS desktop assistant");Ft.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=>{Ms();let o=T(),t=Dc(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=su(),r=qe(Ps(),"Applications"),{keep:a,remove:c}=Ls();if(console.log(`Desktop assistant \u2192 ${qe(r,bs)}
2
- Computer-use helper \u2192 ${qe(r,ks)}
1
+ import{a as fd,b as Ps,g as hd}from"./chunk-XEOT2F4C.js";import{a as Kl,c as Ql}from"./chunk-4NFDDTGA.js";import{A as ar,B as pd,D as ud,a as so,b as Xl,f as Ut,g as Zl,h as ed,i as od,j as td,l as nd,m as sd,n as id,o as ir,p as rd,u as ad,v as cd,w as rr,x as ld}from"./chunk-DUBCOGQB.js";import{a as dd,c as gd,d as md}from"./chunk-4FU4BFCH.js";import"./chunk-N7HKIMMR.js";import{a as Ji,b as xc}from"./chunk-RKPAVWXF.js";import{$ as _n,A as kl,B as vl,C as xl,D as Sl,E as El,F as Al,G as Tl,H as _l,I as Cs,J as Co,K as Bo,L as Mt,M as Is,N as Ns,O as Zi,P as Dl,Q as Pl,R as Ml,S as Ll,T as ql,U as Fl,V as Lt,W as qt,X as Ul,Y as Wl,Z as Le,_ as Rs,a as Ic,aa as er,b as Nc,ba as Bl,ca as Gl,da as nr,ea as Yl,fa as _s,ga as Ft,h as $s,ha as Ds,i as Pc,ia as sr,j as In,ja as Vl,k as bs,l as qc,m as Fc,n as Qc,o as Zc,p as As,q as Gi,r as il,s as ml,t as pl,u as hl,v as yl,w as wl,x as $l,y as bl,z as Yi}from"./chunk-KDD6FPQ6.js";import{$a as zl,A as Ts,C as gl,Ia as Jl,Ja as or,Ka as Hl,La as tr,R as Nn,U as Vi,V as js,W as jl,Za as vo,ba as Wo,ca as Ol,da as Xi,fa as Ki,ha as Cl,ia as Il,ja as Rn,na as Os,qa as Nl,ra as Rl,sa as Qi,w as zi,x as ll,z as dl}from"./chunk-WYSNRZV4.js";import{a as Rc,d as _c,e as Dc}from"./chunk-U52IS3AF.js";import{a as ks,b as vs,c as Uc,d as Wc,e as Bc,g as Jc,h as Hc,j as Gc,k as zc,l as Yc,m as Vc,p as xs,s as Xc,t as Kc}from"./chunk-S2GAEH2F.js";import"./chunk-GTJIKXDB.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ul,b as fl}from"./chunk-EKJG63EJ.js";import{a as Mc,p as Lc}from"./chunk-LWYKS5JU.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as el,e as Ss,g as Es}from"./chunk-LQE73AZR.js";import{a as ol,b as tl,c as nl,d as sl}from"./chunk-2D3RYIDU.js";import"./chunk-XF26QNAW.js";import{a as rl,e as al,g as cl}from"./chunk-RXLU6HJ6.js";import{L as Uo,R as wc,ca as bc,g as tc,r as nc,y as Ui,z as ac}from"./chunk-DTQQ4DAY.js";import{b as It,g as Rt,h as ys,i as ws,j as _t,k as cc,l as at,m as On,u as $c}from"./chunk-53OS4TDU.js";import{e as uc,f as Bi,k as fc}from"./chunk-GLQLCBJS.js";import{b as Nt}from"./chunk-6W74CHNW.js";import"./chunk-HCTWKWS3.js";import"./chunk-SFQUP3BP.js";import{b as Cn}from"./chunk-LLNPKE7H.js";import{a as kc,b as vc}from"./chunk-SHEUCITK.js";import"./chunk-Y4CYQV7G.js";import{a as Hi,e as Sc,f as Ec,h as Ac,i as Tc,k as jc,l as Oc,m as Cc}from"./chunk-WXQQO2PD.js";import{a as Dt}from"./chunk-GV7S5BAX.js";import{c as dc}from"./chunk-SZDACK6O.js";import{f as gc,g as mc,h as Wi}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as ic,k as pc}from"./chunk-M2L6S3Z5.js";import{a as hc,b as re,c as Ie,d as Pt,e as yc}from"./chunk-QJP37VVA.js";import"./chunk-VWTBHLMX.js";import{a as qi}from"./chunk-DXWDVKMX.js";import"./chunk-Z7L74GGT.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as Fi,b as sc}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as rc}from"./chunk-X5C5W3E4.js";import{e as lc}from"./chunk-GSX4NK2N.js";import"./chunk-7UNS34CN.js";import"./chunk-MYVHVJWZ.js";import{n as oc}from"./chunk-AV7T3SYT.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-FBODSJU6.js";import{g as Fo,i as hs}from"./chunk-RS2T53EC.js";import"./chunk-WPNRDEHW.js";import{b as Ct,d as ec}from"./chunk-2GIDVZ4H.js";import{a as Pi,b as _a,c as tu,d as ps,e as Da,f as Ya,g as au,h as Va,i as cu,m as Ot,n as Ka,q as Qa,u as Za,y as ko,z as jn}from"./chunk-GQMUFSKB.js";import{a as Oo,b as jt,e as Ha,f as Tn}from"./chunk-72SZI2UW.js";import{a as Xa,b as lu}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as jo,b as ou}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as su,N as Wa,O as Mi,Q as Li,X as iu,ga as Ba,h as Pa,ha as Ja,i as Ma,ia as T,j as La,ja as fs,k as qa,l as Fa,la as te,m as nu,z as Ua}from"./chunk-SIOWVLZG.js";import{f as qo,n as us}from"./chunk-UIBUZ2N3.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Ga,k as za,l as ru}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as du}from"commander";var yd=new du().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 Nc({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()});te();import{Command as gu}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as wd,existsSync as dr,mkdirSync as cr,mkdtempSync as mu,readdirSync as pu,rmSync as $d,writeFileSync as bd}from"node:fs";import{dirname as kd,join as qe}from"node:path";import{homedir as Ms,release as uu,tmpdir as fu}from"node:os";import{setTimeout as hu}from"node:timers/promises";function Ls(){let e=Uc(process.platform,process.arch,uu());if(e)throw new Error(e)}function qs(){let e=qe(Ms(),"Library/LaunchAgents"),o=[];try{o=pu(e).filter(Jc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:ao("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Hc(e,t)}function Dn(e){return`gui/${process.getuid()}/${e.label}`}async function lr(e){try{ao("launchctl",["bootout",Dn(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{ao("launchctl",["print",Dn(e)],{stdio:"pipe"})}catch{return}await hu(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function vd(e){if(!dr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{ao("launchctl",["print",Dn(e)],{stdio:"pipe"})}catch{o=!1}o||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ao("launchctl",["kickstart",Dn(e)],{stdio:"pipe"})}function yu(){let e=Vc();if(e&&dr(qe(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Wt=new gu("desktop").description("install and control the macOS desktop assistant");Wt.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Ls();let o=T(),t=Wc(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=yu(),r=qe(Ms(),"Applications"),{keep:a,remove:c}=qs();if(console.log(`Desktop assistant \u2192 ${qe(r,ks)}
2
+ Computer-use helper \u2192 ${qe(r,vs)}
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{ao("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=ao("/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=Zp(qe(tu(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){ld(qe(i,"apps",p),qe(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let y=p==="mac-helper"?Uc(o.notifications.local.icon):[];ao("/bin/bash",[qe(g,p,"build.sh"),...y],{stdio:"inherit"})}let d=qe(Ps(),"Library/Logs/agentx-desktop.err.log"),u=qc({label:a.label,executable:qe(r,bs,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:Fc(Ps()),cli:qe(i,"dist/cli.js"),node:process.execPath,log:d,path:Pc(l,process.env.AGENTX_VOICE_PATH)}),f=qe(g,"desktop.plist");gd(f,u,{mode:384}),ao("plutil",["-lint",f],{stdio:"pipe"}),await ar(a);for(let p of c)p.label!==a.label&&await ar(p),dd(p.file,{force:!0});rr(r,{recursive:!0});for(let[p,y,w]of[["mac-voice","AgentX Voice.app",bs],["mac-helper",ks,ks]])ld(qe(g,p,"build",y),qe(r,w),{recursive:!0});rr(md(a.file),{recursive:!0}),rr(md(d),{recursive:!0}),gd(a.file,u,{mode:384}),pd(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{ao("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=ao("/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=mu(qe(fu(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){wd(qe(i,"apps",p),qe(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let y=p==="mac-helper"?zc(o.notifications.local.icon):[];ao("/bin/bash",[qe(g,p,"build.sh"),...y],{stdio:"inherit"})}let d=qe(Ms(),"Library/Logs/agentx-desktop.err.log"),u=Gc({label:a.label,executable:qe(r,ks,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:Yc(Ms()),cli:qe(i,"dist/cli.js"),node:process.execPath,log:d,path:Bc(l,process.env.AGENTX_VOICE_PATH)}),f=qe(g,"desktop.plist");bd(f,u,{mode:384}),ao("plutil",["-lint",f],{stdio:"pipe"}),await lr(a);for(let p of c)p.label!==a.label&&await lr(p),$d(p.file,{force:!0});cr(r,{recursive:!0});for(let[p,y,w]of[["mac-voice","AgentX Voice.app",ks],["mac-helper",vs,vs]])wd(qe(g,p,"build",y),qe(r,w),{recursive:!0});cr(kd(a.file),{recursive:!0}),cr(kd(d),{recursive:!0}),bd(a.file,u,{mode:384}),vd(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{dd(g,{recursive:!0,force:!0})}});Ft.command("start").description("start the installed desktop assistant").action(()=>{Ms(),pd(Ls().keep),console.log("Desktop assistant started.")});Ft.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{Ms(),await ar(Ls().keep),console.log("Desktop assistant stopped.")});Ft.command("status").description("show the desktop login service status").action(()=>{Ms();let{keep:e}=Ls();try{console.log(ao("launchctl",["print",_n(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(cr(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as du}from"commander";import{open as gu}from"fs/promises";import{existsSync as Fs,mkdirSync as iu,readFileSync as Ws,writeFileSync as ud}from"fs";import{homedir as ru}from"os";import{dirname as au,resolve as lr}from"path";var dr="/attach/",fd="/guard/check";function hd(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 qs(e,o,t){let n={hooks:[{type:"command",command:hd(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function cu(e){return{SessionStart:[qs("/attach/session-start",e,"")],UserPromptSubmit:[qs("/attach/prompt",e)],Stop:[qs("/attach/stop",e)],SessionEnd:[qs("/attach/session-end",e)]}}function lu(e){let o=hd("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Us(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Dn(){return lr(ru(),".claude/settings.json")}function ct(e=process.cwd()){for(let o of[e,lr(e,"..")]){let t=lr(o,"agentx.json");if(Fs(t))try{let n=JSON.parse(Ws(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function yd(e,o={}){let t=o.path??Dn(),n=o.withGuard!==!1,s={};if(Fs(t))try{s=JSON.parse(Ws(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(cu(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!Us(f,dr)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Us(d,fd)):[];r.PreToolUse=[...g,...lu(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(iu(au(t),{recursive:!0}),ud(t,`${JSON.stringify(s,null,2)}
9
- `)),{path:t,changed:l,events:a,guardInstalled:c}}function wd(e={}){let o=e.path??Dn();if(!Fs(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Ws(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"?fd:dr;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!Us(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&&ud(o,`${JSON.stringify(t,null,2)}
10
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function Pn(e=Dn()){if(!Fs(e))return!1;try{return!!JSON.parse(Ws(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Us(t,dr))}catch{return!1}}var Bs=new du("monitor").description("Register external CLI sessions and report ended runs to the briefing"),$d=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${ct()}`;async function bd(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)}`)}Bs.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",$d).action(async e=>{try{await bd(e.url,"register",Tc.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}});Bs.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",$d).action(async e=>{try{let o=await gu(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 bd(e.url,"ended",jc.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 Hb}from"commander";import{Command as ku}from"commander";te();import j from"chalk";import{existsSync as vu,readFileSync as xu}from"fs";te();import{Command as mu}from"commander";import ae from"chalk";import{spawn as vd}from"child_process";import{existsSync as pu,readFileSync as uu,unlinkSync as fu}from"fs";import{resolve as gr}from"path";var mr=e=>new Promise(o=>setTimeout(o,e));function pr(e){try{return process.kill(e,0),!0}catch{return!1}}async function Wt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function hu(e){let o=await Wt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await Wt(`${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 yu(e){for(let o of[gr(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(uu(o,"utf-8").trim(),10);if(Number.isFinite(t)&&pr(t))return t}catch{}return null}function wu(e){return new Promise(o=>{let t=vd(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var xd=new mu("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 Wt(`${i}/health`);r||(console.log(ae.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(ae.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await Wt(`${i}/daemon/restart`),c=a?.pid??ul(s)??yu(process.cwd()),l=a?.service??(c?ml(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=dl(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?pl(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${ae.bold(r.node?.name||r.node?.id||i)}${c?ae.dim(` (PID ${c})`):""}`),console.log(` Run by: ${gl(l)}`),f.ok||(console.log(ae.red(` ${f.reason}`)),console.log(ae.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(ae.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(ae.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(ae.dim(" Would run:"));for(let $ of f.steps)console.log(ae.dim(` ${kd($,c)}`));console.log();return}if(e.whenIdle){let $=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite($)||$<0)&&(console.log(ae.red(" --timeout must be a number of minutes")),process.exit(1));let S,v=await ll({read:()=>hu(i),intervalMs:E*1e3,timeoutMs:$*6e4,onCheck:x=>{x!==S&&x!==null&&x>0&&console.log(ae.dim(` Waiting: ${x} task(s) running...`)),S=x}});if(v.outcome==="unreachable"&&(console.log(ae.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(ae.dim(" Check with: agentx daemon status")),process.exit(1)),v.outcome==="timeout"){let x=v.inflight??"some";e.abortOnTimeout&&(console.log(ae.yellow(` Still ${x} task(s) running after ${$} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(ae.yellow(` Still ${x} task(s) running after ${$} min. Restarting anyway:`)),console.log(ae.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(ae.green(` No tasks running${v.waitedMs>=1e3?` (waited ${Math.round(v.waitedMs/1e3)}s)`:""}.`))}let p=gr(g,".agentx");try{cl(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(ae.dim(" Restarting..."));for(let $ of f.steps){if(await $u($,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||$.kind==="exec"&&$.mayFail)continue;let S=$===f.steps[0];try{S&&fu(gr(p,al))}catch{}console.log(ae.red(` Step failed: ${kd($,c)}`)),console.log(S?ae.dim(` The daemon is still running. Restart it with: ${f.manual}`):ae.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let b=12e4,k=Date.now();for(;Date.now()-k<b;){let $=await Wt(`${i}/health`);if($&&typeof $.uptime=="number"&&$.uptime*1e3<=Date.now()-y+2e3){let E=await Wt(`${i}/daemon/restart`);console.log(ae.green(` Daemon is back${E?.pid?` (PID ${E.pid})`:""} after ${Math.round((Date.now()-y)/1e3)}s.`)),console.log();return}await mr(1e3)}console.log(ae.red(` The daemon did not come back within ${b/6e4} min.`)),console.log(ae.dim(` Start it with: ${f.manual}`)),console.log(ae.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function kd(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 $u(e,o){switch(e.kind){case"exec":return await wu(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(;pr(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(ae.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await mr(500);return pr(o.pid)?(console.log(ae.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(;zi(o.service)&&Date.now()-t<3e4;)await mr(500);return!zi(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!pu(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=vd(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}function lt(e,o){return new Intl.DateTimeFormat("sv-SE",{timeZone:o,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(e))}function Sd(e){let o=Math.max(0,Math.floor(e/1e3));return o<60?`${o}s`:o<3600?`${Math.floor(o/60)}m`:o<86400?`${Math.floor(o/3600)}h ${String(Math.floor(o%3600/60)).padStart(2,"0")}m`:`${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h`}function bu(e){if(!e.service)return null;if(e.service.kind==="none")return"none (started from a terminal, nothing starts it again)";let o=e.service.kind==="launchd"?`launchd ${e.service.label}`:`systemd ${e.service.unit}`;if(!e.selfRestart)return o;let t=e.selfRestart.ok?e.selfRestart.how.match(/\(([^)]+)\)$/)?.[1]:null;return e.selfRestart.ok?`${o}${t?` (${t})`:""}`:`${o} (does not start it again by itself)`}function Ed(e,o,t,n){let s=(a,c)=>`${a.padEnd(16)}${c}`,i=[`AgentX ${e.version??"unknown version"}${e.commit?` (${e.commit})`:""} node ${e.node?.id??"unknown"}`];if(e.startedAt&&i.push(s("Running since",`${lt(e.startedAt,n)} (${n}), ${Sd(t-Date.parse(e.startedAt))} ago${e.pid?`, pid ${e.pid}`:""}`)),e.lastRestart){let a=e.lastRestart,c=a.by?`by ${a.by}${a.reason?` (${a.reason})`:""}`:a.reason?`on ${a.reason}, sender unknown`:"no clean stop on record before it";i.push(s("Last restart",a.previousBootAt?`${lt(a.at,n)} ${c}, previous boot ${lt(a.previousBootAt,n)}`:`${lt(a.at,n)}, first start on record`))}if(e.restarts){let a=e.restarts.since&&Date.parse(e.restarts.since)>t-6048e5?` (on record since ${lt(e.restarts.since,n)})`:"";i.push(s("Restarts",`${e.restarts.today} today, ${e.restarts.last7d} in the last 7 days${a}`))}if(e.build){let a=e.build,c=[a.version&&a.version!==e.version?a.version:null,a.changedAt?`written ${lt(a.changedAt,n)}`:null].filter(Boolean).join(", ");i.push(s("Build on disk",a.newer?`dist newer than process: yes${c?` (${c})`:""}, restart to load it`:"dist newer than process: no"))}let r=bu(o);return r&&i.push(s("Service",r)),i}function Ad(e){let o=il(e).at(-1);return o?{at:new Date(o.at).toISOString(),by:o.by,reason:o.reason}:null}function Td(e,o,t,n,s="refused"){return[`${s==="timeout"?"AgentX did not answer within 3 seconds":"AgentX is stopped"} node ${e}`,o?`${"Last boot".padEnd(16)}${lt(o.at,n)} (${n}), ${Sd(t-Date.parse(o.at))} ago`:`${"Last boot".padEnd(16)}none on record in this folder`]}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 co=new ku().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");co.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(k){console.error(j.red(` Failed to open ${y} for writing: ${k.message}`)),process.exit(1)}let b=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});b.unref(),d("/tmp/agentx-daemon.pid",String(b.pid)),console.log(j.green(`Daemon started in background (PID: ${b.pid})`)),console.log(j.dim(` Logs: tail -f ${y}`)),console.log(j.dim(" Stop: agentx daemon stop")),await new Promise(k=>setTimeout(k,1e3));try{process.kill(b.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 Su(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Eu(i(process.cwd(),".env"))}catch{}await new nr(e.config).start()});function Eu(e){if(!vu(e))return;let o=xu(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}}co.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(;jd(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(jd(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"))}});co.addCommand(xd);co.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(),a={};try{let l=await fetch(`http://${t||"127.0.0.1"}:${n}/daemon/restart`,{signal:AbortSignal.timeout(3e3)});if(l.ok){let g=await l.json();a={service:g.service,selfRestart:g.selfRestart}}}catch{}if(e.json){console.log(JSON.stringify({...r,...a},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 ${Au(r.uptime)}`));for(let l of Ed(r,a,Date.now(),Intl.DateTimeFormat().resolvedOptions().timeZone))console.log(` ${l}`);console.log(),console.log(j.bold(" Agents:"));for(let l of r.agents){let g=l.active>0?j.yellow(` [${l.active} active]`):"",d=l.errors>0?j.red(` (${l.errors} errors)`):"";console.log(` ${j.cyan(l.name)} ${j.dim(`(${l.tier})`)}${g}${d}`),console.log(j.dim(` ${l.workspace}`))}let c=r.crons.filter(l=>l.enabled);if(r.crons.length){console.log(),console.log(j.bold(` Crons: ${c.length} enabled / ${r.crons.length} total`));for(let l of r.crons){let g=l.enabled?j.green("\u25CF"):j.dim("\u25CB"),d=l.nextRun?j.dim(` next: ${new Date(l.nextRun).toLocaleTimeString()}`):"";console.log(` ${g} ${l.id}${d}`)}}if(r.mesh?.length){console.log(),console.log(j.bold(" Mesh:"));for(let l of r.mesh){let g=l.healthy?j.green("\u25CF"):j.red("\u25CF"),d=l.skills?.length?j.dim(` (${l.skills.length} agents)`):"";console.log(` ${g} ${l.peer} ${j.dim(l.peerUrl)}${d}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError"){let{resolve:t}=await import("path"),n=Ad(t(process.cwd(),".agentx")),s="unknown";try{s=T(e.config).node.id}catch{}let i=o.name==="TimeoutError"?"timeout":"refused";if(e.json){console.log(JSON.stringify({status:i==="timeout"?"not answering":"stopped",node:{id:s},lastBoot:n},null,2));return}let[r,...a]=Td(s,n,Date.now(),Intl.DateTimeFormat().resolvedOptions().timeZone,i);console.log(j.red(` ${r}`));for(let c of a)console.log(` ${c}`);i==="refused"&&console.log(j.dim(" Start with: agentx daemon start"))}else try{let t=T(e.config),n=us(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}`))}}});co.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"})});co.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
8
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{$d(g,{recursive:!0,force:!0})}});Wt.command("start").description("start the installed desktop assistant").action(()=>{Ls(),vd(qs().keep),console.log("Desktop assistant started.")});Wt.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{Ls(),await lr(qs().keep),console.log("Desktop assistant stopped.")});Wt.command("status").description("show the desktop login service status").action(()=>{Ls();let{keep:e}=qs();try{console.log(ao("launchctl",["print",Dn(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(dr(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as xu}from"commander";import{open as Su}from"fs/promises";import{existsSync as Ws,mkdirSync as wu,readFileSync as Bs,writeFileSync as xd}from"fs";import{homedir as $u}from"os";import{dirname as bu,resolve as gr}from"path";var mr="/attach/",Sd="/guard/check";function Ed(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 Fs(e,o,t){let n={hooks:[{type:"command",command:Ed(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function ku(e){return{SessionStart:[Fs("/attach/session-start",e,"")],UserPromptSubmit:[Fs("/attach/prompt",e)],Stop:[Fs("/attach/stop",e)],SessionEnd:[Fs("/attach/session-end",e)]}}function vu(e){let o=Ed("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Us(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function Pn(){return gr($u(),".claude/settings.json")}function ct(e=process.cwd()){for(let o of[e,gr(e,"..")]){let t=gr(o,"agentx.json");if(Ws(t))try{let n=JSON.parse(Bs(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Ad(e,o={}){let t=o.path??Pn(),n=o.withGuard!==!1,s={};if(Ws(t))try{s=JSON.parse(Bs(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(ku(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!Us(f,mr)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Us(d,Sd)):[];r.PreToolUse=[...g,...vu(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(wu(bu(t),{recursive:!0}),xd(t,`${JSON.stringify(s,null,2)}
9
+ `)),{path:t,changed:l,events:a,guardInstalled:c}}function Td(e={}){let o=e.path??Pn();if(!Ws(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Bs(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"?Sd:mr;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!Us(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&&xd(o,`${JSON.stringify(t,null,2)}
10
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function Mn(e=Pn()){if(!Ws(e))return!1;try{return!!JSON.parse(Bs(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Us(t,mr))}catch{return!1}}var Js=new xu("monitor").description("Register external CLI sessions and report ended runs to the briefing"),jd=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${ct()}`;async function Od(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)}`)}Js.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",jd).action(async e=>{try{await Od(e.url,"register",_c.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}});Js.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",jd).action(async e=>{try{let o=await Su(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 Od(e.url,"ended",Dc.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 pk}from"commander";import{Command as _u}from"commander";te();import j from"chalk";import{existsSync as Du,readFileSync as Pu}from"fs";te();import{Command as Eu}from"commander";import ae from"chalk";import{spawn as Id}from"child_process";import{existsSync as Au,readFileSync as Tu,unlinkSync as ju}from"fs";import{resolve as pr}from"path";var ur=e=>new Promise(o=>setTimeout(o,e));function fr(e){try{return process.kill(e,0),!0}catch{return!1}}async function Bt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function Ou(e){let o=await Bt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await Bt(`${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 Cu(e){for(let o of[pr(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(Tu(o,"utf-8").trim(),10);if(Number.isFinite(t)&&fr(t))return t}catch{}return null}function Iu(e){return new Promise(o=>{let t=Id(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var Nd=new Eu("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 Bt(`${i}/health`);r||(console.log(ae.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(ae.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await Bt(`${i}/daemon/restart`),c=a?.pid??kl(s)??Cu(process.cwd()),l=a?.service??(c?$l(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=yl(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?bl(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${ae.bold(r.node?.name||r.node?.id||i)}${c?ae.dim(` (PID ${c})`):""}`),console.log(` Run by: ${wl(l)}`),f.ok||(console.log(ae.red(` ${f.reason}`)),console.log(ae.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(ae.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(ae.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(ae.dim(" Would run:"));for(let $ of f.steps)console.log(ae.dim(` ${Cd($,c)}`));console.log();return}if(e.whenIdle){let $=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite($)||$<0)&&(console.log(ae.red(" --timeout must be a number of minutes")),process.exit(1));let S,v=await hl({read:()=>Ou(i),intervalMs:E*1e3,timeoutMs:$*6e4,onCheck:x=>{x!==S&&x!==null&&x>0&&console.log(ae.dim(` Waiting: ${x} task(s) running...`)),S=x}});if(v.outcome==="unreachable"&&(console.log(ae.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(ae.dim(" Check with: agentx daemon status")),process.exit(1)),v.outcome==="timeout"){let x=v.inflight??"some";e.abortOnTimeout&&(console.log(ae.yellow(` Still ${x} task(s) running after ${$} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(ae.yellow(` Still ${x} task(s) running after ${$} min. Restarting anyway:`)),console.log(ae.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(ae.green(` No tasks running${v.waitedMs>=1e3?` (waited ${Math.round(v.waitedMs/1e3)}s)`:""}.`))}let p=pr(g,".agentx");try{fl(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(ae.dim(" Restarting..."));for(let $ of f.steps){if(await Nu($,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||$.kind==="exec"&&$.mayFail)continue;let S=$===f.steps[0];try{S&&ju(pr(p,ul))}catch{}console.log(ae.red(` Step failed: ${Cd($,c)}`)),console.log(S?ae.dim(` The daemon is still running. Restart it with: ${f.manual}`):ae.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let b=12e4,k=Date.now();for(;Date.now()-k<b;){let $=await Bt(`${i}/health`);if($&&typeof $.uptime=="number"&&$.uptime*1e3<=Date.now()-y+2e3){let E=await Bt(`${i}/daemon/restart`);console.log(ae.green(` Daemon is back${E?.pid?` (PID ${E.pid})`:""} after ${Math.round((Date.now()-y)/1e3)}s.`)),console.log();return}await ur(1e3)}console.log(ae.red(` The daemon did not come back within ${b/6e4} min.`)),console.log(ae.dim(` Start it with: ${f.manual}`)),console.log(ae.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function Cd(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 Nu(e,o){switch(e.kind){case"exec":return await Iu(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(;fr(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(ae.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await ur(500);return fr(o.pid)?(console.log(ae.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(;Yi(o.service)&&Date.now()-t<3e4;)await ur(500);return!Yi(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!Au(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=Id(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}function lt(e,o){return new Intl.DateTimeFormat("sv-SE",{timeZone:o,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(e))}function Rd(e){let o=Math.max(0,Math.floor(e/1e3));return o<60?`${o}s`:o<3600?`${Math.floor(o/60)}m`:o<86400?`${Math.floor(o/3600)}h ${String(Math.floor(o%3600/60)).padStart(2,"0")}m`:`${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h`}function Ru(e){if(!e.service)return null;if(e.service.kind==="none")return"none (started from a terminal, nothing starts it again)";let o=e.service.kind==="launchd"?`launchd ${e.service.label}`:`systemd ${e.service.unit}`;if(!e.selfRestart)return o;let t=e.selfRestart.ok?e.selfRestart.how.match(/\(([^)]+)\)$/)?.[1]:null;return e.selfRestart.ok?`${o}${t?` (${t})`:""}`:`${o} (does not start it again by itself)`}function _d(e,o,t,n){let s=(a,c)=>`${a.padEnd(16)}${c}`,i=[`AgentX ${e.version??"unknown version"}${e.commit?` (${e.commit})`:""} node ${e.node?.id??"unknown"}`];if(e.startedAt&&i.push(s("Running since",`${lt(e.startedAt,n)} (${n}), ${Rd(t-Date.parse(e.startedAt))} ago${e.pid?`, pid ${e.pid}`:""}`)),e.lastRestart){let a=e.lastRestart,c=a.by?`by ${a.by}${a.reason?` (${a.reason})`:""}`:a.reason?`on ${a.reason}, sender unknown`:"no clean stop on record before it";i.push(s("Last restart",a.previousBootAt?`${lt(a.at,n)} ${c}, previous boot ${lt(a.previousBootAt,n)}`:`${lt(a.at,n)}, first start on record`))}if(e.restarts){let a=e.restarts.since&&Date.parse(e.restarts.since)>t-6048e5?` (on record since ${lt(e.restarts.since,n)})`:"";i.push(s("Restarts",`${e.restarts.today} today, ${e.restarts.last7d} in the last 7 days${a}`))}if(e.build){let a=e.build,c=[a.version&&a.version!==e.version?a.version:null,a.changedAt?`written ${lt(a.changedAt,n)}`:null].filter(Boolean).join(", ");i.push(s("Build on disk",a.newer?`dist newer than process: yes${c?` (${c})`:""}, restart to load it`:"dist newer than process: no"))}let r=Ru(o);return r&&i.push(s("Service",r)),i}function Dd(e){let o=ml(e).at(-1);return o?{at:new Date(o.at).toISOString(),by:o.by,reason:o.reason}:null}function Pd(e,o,t,n,s="refused"){return[`${s==="timeout"?"AgentX did not answer within 3 seconds":"AgentX is stopped"} node ${e}`,o?`${"Last boot".padEnd(16)}${lt(o.at,n)} (${n}), ${Rd(t-Date.parse(o.at))} ago`:`${"Last boot".padEnd(16)}none on record in this folder`]}async function Mu(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 co=new _u().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");co.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(k){console.error(j.red(` Failed to open ${y} for writing: ${k.message}`)),process.exit(1)}let b=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});b.unref(),d("/tmp/agentx-daemon.pid",String(b.pid)),console.log(j.green(`Daemon started in background (PID: ${b.pid})`)),console.log(j.dim(` Logs: tail -f ${y}`)),console.log(j.dim(" Stop: agentx daemon stop")),await new Promise(k=>setTimeout(k,1e3));try{process.kill(b.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 Mu(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Lu(i(process.cwd(),".env"))}catch{}await new sr(e.config).start()});function Lu(e){if(!Du(e))return;let o=Pu(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}}co.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(;Md(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(Md(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"))}});co.addCommand(Nd);co.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(),a={};try{let l=await fetch(`http://${t||"127.0.0.1"}:${n}/daemon/restart`,{signal:AbortSignal.timeout(3e3)});if(l.ok){let g=await l.json();a={service:g.service,selfRestart:g.selfRestart}}}catch{}if(e.json){console.log(JSON.stringify({...r,...a},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 ${qu(r.uptime)}`));for(let l of _d(r,a,Date.now(),Intl.DateTimeFormat().resolvedOptions().timeZone))console.log(` ${l}`);console.log(),console.log(j.bold(" Agents:"));for(let l of r.agents){let g=l.active>0?j.yellow(` [${l.active} active]`):"",d=l.errors>0?j.red(` (${l.errors} errors)`):"";console.log(` ${j.cyan(l.name)} ${j.dim(`(${l.tier})`)}${g}${d}`),console.log(j.dim(` ${l.workspace}`))}let c=r.crons.filter(l=>l.enabled);if(r.crons.length){console.log(),console.log(j.bold(` Crons: ${c.length} enabled / ${r.crons.length} total`));for(let l of r.crons){let g=l.enabled?j.green("\u25CF"):j.dim("\u25CB"),d=l.nextRun?j.dim(` next: ${new Date(l.nextRun).toLocaleTimeString()}`):"";console.log(` ${g} ${l.id}${d}`)}}if(r.mesh?.length){console.log(),console.log(j.bold(" Mesh:"));for(let l of r.mesh){let g=l.healthy?j.green("\u25CF"):j.red("\u25CF"),d=l.skills?.length?j.dim(` (${l.skills.length} agents)`):"";console.log(` ${g} ${l.peer} ${j.dim(l.peerUrl)}${d}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError"){let{resolve:t}=await import("path"),n=Dd(t(process.cwd(),".agentx")),s="unknown";try{s=T(e.config).node.id}catch{}let i=o.name==="TimeoutError"?"timeout":"refused";if(e.json){console.log(JSON.stringify({status:i==="timeout"?"not answering":"stopped",node:{id:s},lastBoot:n},null,2));return}let[r,...a]=Pd(s,n,Date.now(),Intl.DateTimeFormat().resolvedOptions().timeZone,i);console.log(j.red(` ${r}`));for(let c of a)console.log(` ${c}`);i==="refused"&&console.log(j.dim(" Start with: agentx daemon start"))}else try{let t=T(e.config),n=fs(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}`))}}});co.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"})});co.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
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
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."))}});co.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"))}});co.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}`))}});co.action(async e=>{await new nr(e.config).start()});function Au(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 jd(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as Tu}from"commander";import lo from"chalk";import{existsSync as Mn,readFileSync as ju,writeFileSync as Od,mkdirSync as Cd}from"fs";import{hostname as Id}from"os";import{resolve as Bt}from"path";var Nd=new Tu().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Bt(o,"agentx.json"),n=Bt(o,".env"),s=Bt(o,".agentx/sessions");if(console.log(),console.log(lo.bold(" agentx init")),console.log(),Mn(t)&&!e.force){console.log(lo.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Bt(o,"agentx.example.json"),Bt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Mn(c)){r=ju(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Id().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Id(),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)),Od(t,r),console.log(lo.green(" \u2713 Created agentx.json")),Mn(n)||(Od(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
- `)),console.log(lo.green(" \u2713 Created .env template"))),Mn(s)||(Cd(s,{recursive:!0}),console.log(lo.green(" \u2713 Created .agentx/sessions/")));let a=Bt(o,".claude");Mn(a)||(Cd(a,{recursive:!0}),console.log(lo.green(" \u2713 Created .claude/"))),console.log(),console.log(lo.bold(" Next steps:")),console.log(` 1. Edit ${lo.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${lo.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${lo.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${lo.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Nu}from"commander";import Ln from"chalk";import{spawn as Ru}from"child_process";import{existsSync as _u}from"fs";import{dirname as Du,resolve as Pu}from"path";import{fileURLToPath as Mu}from"url";te();import{spawn as Ou}from"child_process";import Cu from"chalk";function Iu(e=process.platform){return e==="darwin"?"open":e==="win32"?"start":"xdg-open"}function dt(e,o=Iu()){let t=()=>console.log(Cu.dim(` Couldn't open a browser. Visit ${e}`));try{let n=Ou(o,[e],{stdio:"ignore",detached:!0});n.once("error",t),n.unref()}catch{t()}}var Rd=new Nu().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=Bl(),t=e.port?parseInt(e.port,10):Lu(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Ln.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Ln.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Ln.bold(` Opening ${n}`)),console.log(),await Uu(n).catch(()=>!1))console.log(Ln.dim(" Dashboard is already running.")),e.open!==!1&&dt(n);else{console.log(Ln.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=qu(),r=Ru(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&dt(n),await new Promise(a=>r.on("exit",()=>a()))}});function Lu(){try{return T().dashboard.port||4202}catch{return 4202}}function qu(){let e=Pu(Du(Mu(import.meta.url)),"cli.js");return _u(e)?e:process.argv[1]||e}async function Uu(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}import{Command as Fu}from"commander";import Ne from"chalk";var qn=new Fu().name("token").description("scoped API tokens for external access (mesh peers, integrations)");qn.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 no,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)}});qn.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new no().list();if(e.length===0){console.log(Ne.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"))}});co.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}`))}});co.action(async e=>{await new sr(e.config).start()});function qu(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 Md(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as Fu}from"commander";import lo from"chalk";import{existsSync as Ln,readFileSync as Uu,writeFileSync as Ld,mkdirSync as qd}from"fs";import{hostname as Fd}from"os";import{resolve as Jt}from"path";var Ud=new Fu().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Jt(o,"agentx.json"),n=Jt(o,".env"),s=Jt(o,".agentx/sessions");if(console.log(),console.log(lo.bold(" agentx init")),console.log(),Ln(t)&&!e.force){console.log(lo.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Jt(o,"agentx.example.json"),Jt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Ln(c)){r=Uu(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Fd().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Fd(),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)),Ld(t,r),console.log(lo.green(" \u2713 Created agentx.json")),Ln(n)||(Ld(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
+ `)),console.log(lo.green(" \u2713 Created .env template"))),Ln(s)||(qd(s,{recursive:!0}),console.log(lo.green(" \u2713 Created .agentx/sessions/")));let a=Jt(o,".claude");Ln(a)||(qd(a,{recursive:!0}),console.log(lo.green(" \u2713 Created .claude/"))),console.log(),console.log(lo.bold(" Next steps:")),console.log(` 1. Edit ${lo.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${lo.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${lo.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${lo.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Hu}from"commander";import qn from"chalk";import{spawn as Gu}from"child_process";import{existsSync as zu}from"fs";import{dirname as Yu,resolve as Vu}from"path";import{fileURLToPath as Xu}from"url";te();import{spawn as Wu}from"child_process";import Bu from"chalk";function Ju(e=process.platform){return e==="darwin"?"open":e==="win32"?"start":"xdg-open"}function dt(e,o=Ju()){let t=()=>console.log(Bu.dim(` Couldn't open a browser. Visit ${e}`));try{let n=Wu(o,[e],{stdio:"ignore",detached:!0});n.once("error",t),n.unref()}catch{t()}}var Wd=new Hu().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=Xl(),t=e.port?parseInt(e.port,10):Ku(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(qn.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(qn.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(qn.bold(` Opening ${n}`)),console.log(),await Zu(n).catch(()=>!1))console.log(qn.dim(" Dashboard is already running.")),e.open!==!1&&dt(n);else{console.log(qn.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Qu(),r=Gu(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&dt(n),await new Promise(a=>r.on("exit",()=>a()))}});function Ku(){try{return T().dashboard.port||4202}catch{return 4202}}function Qu(){let e=Vu(Yu(Xu(import.meta.url)),"cli.js");return zu(e)?e:process.argv[1]||e}async function Zu(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}import{Command as ef}from"commander";import Ne from"chalk";var Fn=new ef().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Fn.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 no,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)}});Fn.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new no().list();if(e.length===0){console.log(Ne.dim(`
17
17
  No tokens issued.
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)}});qn.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new no().revoke(e);o||(console.log(Ne.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ne.green(`
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)}});Fn.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new no().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 Wu}from"commander";import Te from"chalk";import{execFileSync as Dd}from"child_process";import{existsSync as _d}from"fs";te();var Jt=new Wu().name("app").description("pair phones with the AgentX phone app and manage paired devices");Jt.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=fr(hr(),Un());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:${Un()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${Un()}/api/app`].join(`
21
- `));let t=(e.url?String(e.url):ur()).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 no().create({name:String(e.name),scopes:["app"]}),{code:i}=new Ss().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 Bu({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!_d("agentx.json")&&!_d(".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)}});Jt.command("devices").description("list paired phones").action(()=>{let e=new no().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()});Jt.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new no,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 of}from"commander";import Te from"chalk";import{execFileSync as Jd}from"child_process";import{existsSync as Bd}from"fs";te();var Ht=new of().name("app").description("pair phones with the AgentX phone app and manage paired devices");Ht.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=yr(wr(),Un());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:${Un()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${Un()}/api/app`].join(`
21
+ `));let t=(e.url?String(e.url):hr()).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 no().create({name:String(e.name),scopes:["app"]}),{code:i}=new Es().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 tf({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!Bd("agentx.json")&&!Bd(".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)}});Ht.command("devices").description("list paired phones").action(()=>{let e=new no().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()});Ht.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new no,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
- `))});Jt.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=Yc;try{o=T().channels.push.keysFile}catch{}let t=Vc(o),n=Xc(t);if(n&&!e.force){console.log(Te.green(`
23
+ `))});Ht.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=ol;try{o=T().channels.push.keysFile}catch{}let t=tl(o),n=nl(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");Kc(t,s.generateVAPIDKeys()),console.log(Te.green(`
25
+ `));return}let{default:s}=await import("web-push");sl(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 Bu(e){let o=Math.round(zc/6e4),t=[` Pairing code: ${Te.bold.cyan(xs(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 ur(){let e;try{e=JSON.parse(Dd("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 Ju=new Set(["/app","/api/app","/member","/api/member"]);function fr(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&&!Ju.has(g)&&n.push(`${i}${a}`)}return n}function hr(){try{return JSON.parse(Dd("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Un(){try{return T().dashboard.port||4202}catch{return 4202}}te();import{Command as xo}from"commander";import h from"chalk";import Me from"prompts";import{readFileSync as Ho,writeFileSync as Ht,existsSync as we,mkdirSync as vo,cpSync as yr,readdirSync as $r}from"fs";import{resolve as G,join as Jo,dirname as Hu}from"path";import{fileURLToPath as Gu}from"url";function me(){let e=G(process.cwd(),"agentx.json");if(!we(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ho(e,"utf-8"))}function Je(e){return re(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 gt=new xo().name("agent").description("manage agents \u2014 add, list, remove");gt.command("list").alias("ls").description("list configured agents").action(()=>{let e=me();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()});gt.command("add").description("add a new agent interactively").action(async()=>{let e=me(),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:G(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Jo(o.workspace,o.id);vo(G(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-EA3G42NY.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=G(process.cwd(),"src/wiki/SKILL.md"),a=G(Hu(Gu(import.meta.url)),"../wiki/SKILL.md"),c=we(r)?r:a;we(c)&&(vo(G(t,".claude/skills/wiki"),{recursive:!0}),yr(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Je(e),console.log(h.green(`
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()});gt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=me();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)`))});gt.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=me(),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 Fn=new xo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Fn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=me().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(`
27
+ `))});function tf(e){let o=Math.round(el/6e4),t=[` Pairing code: ${Te.bold.cyan(Ss(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 hr(){let e;try{e=JSON.parse(Jd("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 nf=new Set(["/app","/api/app","/member","/api/member"]);function yr(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&&!nf.has(g)&&n.push(`${i}${a}`)}return n}function wr(){try{return JSON.parse(Jd("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Un(){try{return T().dashboard.port||4202}catch{return 4202}}te();import{Command as So}from"commander";import h from"chalk";import Me from"prompts";import{readFileSync as Ho,writeFileSync as Gt,existsSync as we,mkdirSync as xo,cpSync as $r,readdirSync as kr}from"fs";import{resolve as z,join as Jo,dirname as sf}from"path";import{fileURLToPath as rf}from"url";function me(){let e=z(process.cwd(),"agentx.json");if(!we(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ho(e,"utf-8"))}function Je(e){return re(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 gt=new So().name("agent").description("manage agents \u2014 add, list, remove");gt.command("list").alias("ls").description("list configured agents").action(()=>{let e=me();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()});gt.command("add").description("add a new agent interactively").action(async()=>{let e=me(),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:z(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:Jo(o.workspace,o.id);xo(z(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-HAV4CQV7.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=z(process.cwd(),"src/wiki/SKILL.md"),a=z(sf(rf(import.meta.url)),"../wiki/SKILL.md"),c=we(r)?r:a;we(c)&&(xo(z(t,".claude/skills/wiki"),{recursive:!0}),$r(c,z(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Je(e),console.log(h.green(`
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()});gt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=me();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)`))});gt.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=me(),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 Wn=new So().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Wn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=me().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()});Fn.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=me();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-J6CNV23P.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`))});Fn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=me(),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}`))});Fn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=me().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)});gt.addCommand(Fn);var Js=new xo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Js.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=me();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()});Js.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=me(),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),vo(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await 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 Gt=new xo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Gt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=me();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()});Gt.command("add").description("add a cron job").action(async()=>{let e=me(),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())});Gt.command("enable <id>").description("enable a cron job").action(async e=>{let o=me();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`))});Gt.command("disable <id>").description("disable a cron job").action(async e=>{let o=me();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 io=new xo().name("mesh").description("manage mesh peers \u2014 add, list, remove");io.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=me();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()});io.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=me(),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()}});io.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=me();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`)))});io.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=me();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."))});io.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 Pd=e=>{let o=e||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Hs(e,o,t={}){let n=Pd(),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 mt=io.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");mt.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-Y667GZAU.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||Pd()).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()});mt.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()});Wn.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=me();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-ZHQYXFOJ.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`))});Wn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=me(),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}`))});Wn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=me().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)});gt.addCommand(Wn);var Hs=new So().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Hs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=me();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()});Hs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=me(),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),xo(z(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 zt=new So().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");zt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=me();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()});zt.command("add").description("add a cron job").action(async()=>{let e=me(),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())});zt.command("enable <id>").description("enable a cron job").action(async e=>{let o=me();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`))});zt.command("disable <id>").description("disable a cron job").action(async e=>{let o=me();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 io=new So().name("mesh").description("manage mesh peers \u2014 add, list, remove");io.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=me();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()});io.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=me(),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()}});io.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=me();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`)))});io.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=me();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."))});io.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 Hd=e=>{let o=e||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Gs(e,o,t={}){let n=Hd(),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 mt=io.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");mt.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-M4K6WXOO.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||Hd()).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()});mt.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()});mt.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()});mt.command("pause <id>").description("stop the guest at once; running turns are cancelled. Resume later").action(e=>Hs(e,"pause"));mt.command("resume <id>").description("let a paused guest work again").action(e=>Hs(e,"resume"));mt.command("end <id>").description("end the grant for good; its key stops at once").action(e=>Hs(e,"end"));mt.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)),Hs(e,"update",n)});io.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(`
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()});mt.command("pause <id>").description("stop the guest at once; running turns are cancelled. Resume later").action(e=>Gs(e,"pause"));mt.command("resume <id>").description("let a paused guest work again").action(e=>Gs(e,"resume"));mt.command("end <id>").description("end the grant for good; its key stops at once").action(e=>Gs(e,"end"));mt.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)),Gs(e,"update",n)});io.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)}});io.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()});io.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
- `)});io.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 pt=new xo().name("skill").description("manage skills \u2014 add to agent(s), list");pt.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=me(),n=G(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(Jo(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=G(a.workspace,".claude/skills",s);vo(c,{recursive:!0}),we(Jo(n,"SKILL.md"))?yr(n,c,{recursive:!0}):n.endsWith(".md")&&yr(n,Jo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});pt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=we(n)?$r(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});pt.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(b=>we(b));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(h.dim(` ${b}`));return}let r=Ho(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(b){console.log(h.red(` Can't load agentx.json: ${b.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([b])=>b===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[b,k]of d){let $=k.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${b.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=G($,".claude/skills",e),S=G(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${b.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(vo(E,{recursive:!0}),Ht(S,r)),console.log(` ${h.green("+")} ${b.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=Ho(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${b.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Ht(S,r),console.log(` ${h.yellow("\u21BB")} ${b.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()});pt.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=me().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let u=me();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(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)});pt.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=me(),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-73JC2YBN.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
+ `)});io.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 pt=new So().name("skill").description("manage skills \u2014 add to agent(s), list");pt.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=me(),n=z(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(Jo(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=z(a.workspace,".claude/skills",s);xo(c,{recursive:!0}),we(Jo(n,"SKILL.md"))?$r(n,c,{recursive:!0}):n.endsWith(".md")&&$r(n,Jo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});pt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=z(t.workspace,".claude/skills"),s=we(n)?kr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});pt.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]:[z(n,"src",e,"SKILL.md"),z(n,"skills",e,"SKILL.md")],i=s.find(b=>we(b));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(h.dim(` ${b}`));return}let r=Ho(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(b){console.log(h.red(` Can't load agentx.json: ${b.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([b])=>b===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[b,k]of d){let $=k.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${b.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=z($,".claude/skills",e),S=z(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${b.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(xo(E,{recursive:!0}),Gt(S,r)),console.log(` ${h.green("+")} ${b.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=Ho(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${b.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Gt(S,r),console.log(` ${h.yellow("\u21BB")} ${b.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()});pt.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=me().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(z(f.workspace))}else if(e.allWorkspaces){let u=me();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(z(f.workspace))}else i.push(z(e.cwd));let r=z(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)});pt.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=me(),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-T7CKKLC2.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
- (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Wn=new xo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Wn.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");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=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");vo(i,{recursive:!0}),vo(r,{recursive:!0});let a=$r(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Jo(i,d);if(we(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Ho(Jo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Ht(u,p),console.log(h.green(` + ${u}`)),c++}let g=Jo(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=Ho(s,"utf-8").replaceAll("example.",`${e}.`);Ht(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()});Wn.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=G(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=G(o.referencesCwd||o.cwd),u=G(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(`
43
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Bn=new So().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Bn.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=z(o.cwd),n=z(t,"references/example"),s=z(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=z(t,".agentx/references",e),r=z(t,".agentx/references/recipes");xo(i,{recursive:!0}),xo(r,{recursive:!0});let a=kr(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Jo(i,d);if(we(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Ho(Jo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Gt(u,p),console.log(h.green(` + ${u}`)),c++}let g=Jo(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=Ho(s,"utf-8").replaceAll("example.",`${e}.`);Gt(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()});Bn.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=z(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=z(o.referencesCwd||o.cwd),u=z(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(`
45
45
  `).slice(0,30).map(b=>` ${b}`).join(`
46
46
  `)),w.split(`
47
47
  `).length>30&&console.log(h.dim(` \u2026 (${w.split(`
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}vo(u,{recursive:!0});let f=0,p=0;for(let[y,w]of Object.entries(g)){let b=Jo(u,y);if(we(b)&&!o.force){console.log(h.dim(` skip ${b} (exists; --force to overwrite)`)),p++;continue}Ht(b,w),console.log(h.green(` + ${b}`)),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()});Wn.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(G(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var br=new xo().name("hook").description("manage hooks \u2014 add to agent workspace");br.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=me().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=G(t.workspace,".claude/settings.json"),s=we(n)?JSON.parse(Ho(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),vo(G(t.workspace,".claude"),{recursive:!0}),Ht(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var kr=new xo().name("migrate").description("import configuration from OpenClaw or other tools");kr.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,G(process.env.HOME||"",".openclaw/openclaw.json"),G(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&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(Ho(n,"utf-8")),i=we(G(process.cwd(),"agentx.json"))?me():{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){vo(G(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-EA3G42NY.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=G(n,"../cron/jobs.json");if(we(u)){let f=JSON.parse(Ho(u,"utf-8")),p=0;for(let y of f.jobs||[]){let w=y.name||y.id,b=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:b,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(`
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}xo(u,{recursive:!0});let f=0,p=0;for(let[y,w]of Object.entries(g)){let b=Jo(u,y);if(we(b)&&!o.force){console.log(h.dim(` skip ${b} (exists; --force to overwrite)`)),p++;continue}Gt(b,w),console.log(h.green(` + ${b}`)),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()});Bn.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(z(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 vr=new So().name("hook").description("manage hooks \u2014 add to agent workspace");vr.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=me().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=z(t.workspace,".claude/settings.json"),s=we(n)?JSON.parse(Ho(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),xo(z(t.workspace,".claude"),{recursive:!0}),Gt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var xr=new So().name("migrate").description("import configuration from OpenClaw or other tools");xr.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,z(process.env.HOME||"",".openclaw/openclaw.json"),z(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(Ho(n,"utf-8")),i=we(z(process.cwd(),"agentx.json"))?me():{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){xo(z(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-HAV4CQV7.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=z(n,"../cron/jobs.json");if(we(u)){let f=JSON.parse(Ho(u,"utf-8")),p=0;for(let y of f.jobs||[]){let w=y.name||y.id,b=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:b,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 Go=new xo().name("config").description("validate and inspect configuration");Go.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=us(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(G(r,".claude")),c=we(G(r,"CLAUDE.md")),l=we(G(r,".claude/settings.json")),g=we(G(r,".claude/skills"))?$r(G(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()});Go.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 zu(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 wr(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Go.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-RGC72OEU.js"),{expandEnvVars:r}=await import("./config-J6CNV23P.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(wr(g))});Go.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-RGC72OEU.js"),r=zu(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: ${wr(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${wr(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})`)))});Go.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-RGC72OEU.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.")))});Go.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()});ps();import{Command as Yu}from"commander";import zo from"chalk";import{resolve as Yo}from"path";import{existsSync as Vu}from"fs";var Io=new Yu().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function ut(e){let o=Yo(e,".agentx/db.sqlite");Vu(o)||(console.log(zo.red(` No SQLite at ${o}`)),console.log(zo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=qo({path:o});return t||(console.log(zo.red(` Could not open ${o}`)),console.log(zo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function ft(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(zo.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])))}Io.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=ut(Yo(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 Go=new So().name("config").description("validate and inspect configuration");Go.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=fs(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(z(r,".claude")),c=we(z(r,"CLAUDE.md")),l=we(z(r,".claude/settings.json")),g=we(z(r,".claude/skills"))?kr(z(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()});Go.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 af(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 br(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Go.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-RS2NTDNO.js"),{expandEnvVars:r}=await import("./config-ZHQYXFOJ.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(br(g))});Go.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-RS2NTDNO.js"),r=af(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: ${br(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${br(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})`)))});Go.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-RS2NTDNO.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.")))});Go.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()});us();import{Command as cf}from"commander";import zo from"chalk";import{resolve as Yo}from"path";import{existsSync as lf}from"fs";var Io=new cf().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function ut(e){let o=Yo(e,".agentx/db.sqlite");lf(o)||(console.log(zo.red(` No SQLite at ${o}`)),console.log(zo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=qo({path:o});return t||(console.log(zo.red(` Could not open ${o}`)),console.log(zo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function ft(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(zo.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])))}Io.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=ut(Yo(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,12 +98,12 @@ ${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)});ft(i,!!e.json)});Io.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=ut(Yo(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}));ft(n,!!e.json)});Io.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=ut(Yo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(zo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(zo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();ft(n,!!o.json)}catch(n){console.log(zo.red(` ${n.message}`)),process.exit(1)}});import{Command as Qu}from"commander";import V from"chalk";import{mkdtempSync as Zu}from"fs";import{tmpdir as ef}from"os";import{resolve as Ld,join as qd}from"path";import{existsSync as of}from"fs";import tf from"better-sqlite3";function Md(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=Xu(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=rc(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:Ku(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Xu(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Ku(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 Vo=new Qu().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function zt(e){let o=Ld(e.cwd??process.cwd()),t=Ld(o,e.path??".agentx/intent/ledger.sqlite");of(t)||(console.log(V.red(` No ledger at ${t}`)),console.log(V.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 tf(t,{readonly:!0})}catch(n){console.log(V.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(V.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function ht(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(V.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 nf(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 Gs(e){if(!e)return;let o=nf(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(V.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Vo.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=zt(e),t=Gs(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)});ft(i,!!e.json)});Io.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=ut(Yo(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}));ft(n,!!e.json)});Io.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=ut(Yo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(zo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(zo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();ft(n,!!o.json)}catch(n){console.log(zo.red(` ${n.message}`)),process.exit(1)}});import{Command as mf}from"commander";import V from"chalk";import{mkdtempSync as pf}from"fs";import{tmpdir as uf}from"os";import{resolve as zd,join as Yd}from"path";import{existsSync as ff}from"fs";import hf from"better-sqlite3";function Gd(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=df(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=pc(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:gf(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function df(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function gf(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 Vo=new mf().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Yt(e){let o=zd(e.cwd??process.cwd()),t=zd(o,e.path??".agentx/intent/ledger.sqlite");ff(t)||(console.log(V.red(` No ledger at ${t}`)),console.log(V.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 hf(t,{readonly:!0})}catch(n){console.log(V.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(V.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function ht(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(V.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 yf(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 zs(e){if(!e)return;let o=yf(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(V.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Vo.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=Yt(e),t=zs(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
105
105
  WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
106
- `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(V.bold("Events by source")),ht(r,!1),console.log(),console.log(V.bold(`Decisions: ${a}`)),ht(c,!1),console.log(),console.log(V.bold(`Divergences: ${l}`)),ht(g,!1),console.log(),console.log(V.bold(`In-flight (dispatched, no resolution): ${d}`))});Vo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=zt(e),t=Gs(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
106
+ `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(V.bold("Events by source")),ht(r,!1),console.log(),console.log(V.bold(`Decisions: ${a}`)),ht(c,!1),console.log(),console.log(V.bold(`Divergences: ${l}`)),ht(g,!1),console.log(),console.log(V.bold(`In-flight (dispatched, no resolution): ${d}`))});Vo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Yt(e),t=zs(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
107
107
  SELECT
108
108
  datetime(ts/1000, 'unixepoch') AS at,
109
109
  source,
@@ -117,7 +117,7 @@ ${i.content}
117
117
  ${i}
118
118
  ORDER BY ts DESC
119
119
  LIMIT @limit
120
- `).all(s);ht(r,!!e.json)});Vo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=zt(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
120
+ `).all(s);ht(r,!!e.json)});Vo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Yt(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
121
121
  SELECT
122
122
  datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
123
123
  e.source,
@@ -133,7 +133,7 @@ ${i.content}
133
133
  WHERE ${t.join(" AND ")}
134
134
  ORDER BY d.decided_at DESC
135
135
  LIMIT @limit
136
- `).all(n);ht(s,!!e.json)});Vo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=zt(e),t=Gs(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
136
+ `).all(n);ht(s,!!e.json)});Vo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Yt(e),t=zs(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
137
137
  SELECT
138
138
  datetime(ts/1000, 'unixepoch') AS at,
139
139
  source,
@@ -144,7 +144,7 @@ ${i.content}
144
144
  ${i}
145
145
  ORDER BY ts DESC
146
146
  LIMIT @limit
147
- `).all(s);ht(r,!!e.json)});Vo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=zt(o),n=null,s=null;if(o.bySubject){let d=e.indexOf(":");d<0&&(console.log(V.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(V.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(V.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(V.dim(` project: ${n}`)),s&&console.log(V.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
147
+ `).all(s);ht(r,!!e.json)});Vo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=Yt(o),n=null,s=null;if(o.bySubject){let d=e.indexOf(":");d<0&&(console.log(V.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(V.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(V.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(V.dim(` project: ${n}`)),s&&console.log(V.dim(` subject: ${s}`)),process.exit(1))}let i=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
148
148
  FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(V.dim(` (no events for ${n}:${s})`));return}let r=i.map(d=>d.id),a=r.map((d,u)=>`@id${u}`).join(", "),c=Object.fromEntries(r.map((d,u)=>[`id${u}`,d])),l=t.prepare(`
149
149
  SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
150
150
  r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
@@ -153,7 +153,7 @@ ${i.content}
153
153
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
154
154
  WHERE d.event_id IN (${a})
155
155
  ORDER BY d.decided_at ASC
156
- `).all(c);if(o.json){let d=i.map(u=>({event:u,decisions:l.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(V.bold(` Lineage for ${V.cyan(n+":"+s)}`)),console.log(V.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let u=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${V.dim(u)} ${V.bold(d.id)} ${V.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(V.dim(" (no decisions yet)"));continue}for(let p of f){let y=p.outcome==="dispatched"?V.green(p.outcome):p.outcome==="dropped"?V.dim(p.outcome):V.yellow(p.outcome),w=p.agent_id?V.cyan(p.agent_id):V.dim("-"),b=p.reason?V.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${V.dim(p.decided_by)} \u2192 ${y} ${w}${b}`),p.resolution_status){let k=p.resolution_status==="ok"?V.green(p.resolution_status):V.red(p.resolution_status),$=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${V.dim("resolved")} ${k} ${V.dim($)}`)}else p.outcome==="dispatched"&&console.log(` ${V.yellow("(in-flight, no resolution)")}`)}}console.log()});Vo.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").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("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=zt(e),t=Gs(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
156
+ `).all(c);if(o.json){let d=i.map(u=>({event:u,decisions:l.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(V.bold(` Lineage for ${V.cyan(n+":"+s)}`)),console.log(V.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let u=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${V.dim(u)} ${V.bold(d.id)} ${V.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(V.dim(" (no decisions yet)"));continue}for(let p of f){let y=p.outcome==="dispatched"?V.green(p.outcome):p.outcome==="dropped"?V.dim(p.outcome):V.yellow(p.outcome),w=p.agent_id?V.cyan(p.agent_id):V.dim("-"),b=p.reason?V.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${V.dim(p.decided_by)} \u2192 ${y} ${w}${b}`),p.resolution_status){let k=p.resolution_status==="ok"?V.green(p.resolution_status):V.red(p.resolution_status),$=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${V.dim("resolved")} ${k} ${V.dim($)}`)}else p.outcome==="dispatched"&&console.log(` ${V.yellow("(in-flight, no resolution)")}`)}}console.log()});Vo.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").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("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=Yt(e),t=zs(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
157
157
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
158
158
  FROM intent_events
159
159
  ${n.length?"WHERE "+n.join(" AND "):""}
@@ -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=Zu(qd(ef(),"agentx-ledger-replay-")),f=new Qa({path:qd(u,"target.sqlite")});try{let p=Md(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(V.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(V.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(V.red(` \u2717 ${p.divergences.length} divergences`)),ht(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()}});Oa();zp();Yp();Vp();Bp();Ja();An();import{Command as sf}from"commander";import F from"chalk";import{existsSync as Ud}from"fs";import{resolve as vr}from"path";import rf from"better-sqlite3";var ze=new sf().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),go=".agentx/decisions/decisions.sqlite";function af(e){return vr(vr(e.cwd??process.cwd()),e.path??go)}function Eo(e,o=!1){let t=af(e);Ud(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 ms({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 So(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 xr(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 Sr(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:xr(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}ze.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",go).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=Eo(e),t=xr(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=pf(Yd(uf(),"agentx-ledger-replay-")),f=new ic({path:Yd(u,"target.sqlite")});try{let p=Gd(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(V.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(V.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(V.red(` \u2717 ${p.divergences.length} divergences`)),ht(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()}});Da();ru();au();cu();tu();Ka();Tn();import{Command as wf}from"commander";import W from"chalk";import{existsSync as Vd}from"fs";import{resolve as Sr}from"path";import $f from"better-sqlite3";var ze=new wf().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),go=".agentx/decisions/decisions.sqlite";function bf(e){return Sr(Sr(e.cwd??process.cwd()),e.path??go)}function Ao(e,o=!1){let t=bf(e);Vd(t)||(console.log(W.red(` No decision store at ${t}`)),console.log(W.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 ps({path:t,readonly:!o})}catch(n){console.log(W.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(W.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Eo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(W.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(W.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function Er(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 Ar(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Er(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}ze.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",go).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=Ao(e),t=Er(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,
@@ -177,38 +177,38 @@ ${i.content}
177
177
  FROM decision_calls
178
178
  WHERE ts >= ?
179
179
  GROUP BY seat, mode, backend, model, structure_mode
180
- ORDER BY calls DESC`).all(t);So(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
180
+ ORDER BY calls DESC`).all(t);Eo(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
181
181
  FROM decision_calls WHERE ts >= ? GROUP BY seat, mode, action, explored
182
- ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(F.bold(`
183
- policy`)),So(s,!1),console.log(F.dim(`
182
+ ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(W.bold(`
183
+ policy`)),Eo(s,!1),console.log(W.dim(`
184
184
  explored=1 means the policy wanted to skip and the expensive path ran anyway.
185
- Those are the only rows in the skip region that can ever be graded.`))),o.close()});ze.command("calls").description("recent calls").option("--path <file>","store path",go).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Eo(e),t=["ts >= ?"],n=[xr(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,
185
+ Those are the only rows in the skip region that can ever be graded.`))),o.close()});ze.command("calls").description("recent calls").option("--path <file>","store path",go).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Ao(e),t=["ts >= ?"],n=[Er(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));So(s,e.json),o.close()});ze.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",go).option("--json").action((e,o)=>{let t=Eo(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}So(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()});ze.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",go).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=Eo(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()});ze.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",go).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Eo(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));So(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});ze.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",go).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=Eo(e,!0),t=vr(process.cwd(),e.db);Ud(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new rf(t,{readonly:!0});try{let s=Ac(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
- label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});ze.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",go).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=Eo(e),t=o.gradedRows(Sr(e)),n=Ua(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
- ${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
- 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(`
192
- accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+F.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${F.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${F.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${F.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
193
- fitted temperature ${s.temperature} `+F.dim(`(NLL ${s.nllBefore.toFixed(4)} \u2192 ${s.nll.toFixed(4)})`)),s.temperature>1.15&&console.log(F.dim(` T > 1 means the backend is overconfident. Set decisions.seats.${e.seat}.temperature = ${s.temperature}.`));let i=t.filter(a=>a.action==="skip"),r=i.filter(a=>a.explored&&a.truth!==void 0);i.length>0&&(console.log(`
194
- skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(F.yellow(` Nothing in the skip region has been graded. Everything below describes
188
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));Eo(s,e.json),o.close()});ze.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",go).option("--json").action((e,o)=>{let t=Ao(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(W.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}Eo(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()});ze.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",go).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=Ao(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(W.green(` labeled ${e}.${o} = ${t}`)),s.close()});ze.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",go).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Ao(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));Eo(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});ze.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",go).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=Ao(e,!0),t=Sr(process.cwd(),e.db);Vd(t)||(console.log(W.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new $f(t,{readonly:!0});try{let s=Rc(n,o);console.log(W.green(` wrote ${s} label(s)`)),s===0&&console.log(W.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
189
+ label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});ze.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",go).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=Ao(e),t=o.gradedRows(Ar(e)),n=za(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(W.bold(`
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(W.yellow(`
191
+ Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(W.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(W.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
192
+ accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+W.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${W.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${W.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${W.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
193
+ fitted temperature ${s.temperature} `+W.dim(`(NLL ${s.nllBefore.toFixed(4)} \u2192 ${s.nll.toFixed(4)})`)),s.temperature>1.15&&console.log(W.dim(` T > 1 means the backend is overconfident. Set decisions.seats.${e.seat}.temperature = ${s.temperature}.`));let i=t.filter(a=>a.action==="skip"),r=i.filter(a=>a.explored&&a.truth!==void 0);i.length>0&&(console.log(`
194
+ skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(W.yellow(` Nothing in the skip region has been graded. Everything below describes
195
195
  only the decisions this policy chose NOT to skip \u2014 it cannot tell you
196
- what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(F.bold(`
197
- reliability (equal-width bins)`)),So(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});ze.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",go).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=Eo(e),t=o.gradedRows(Sr(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Fa(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(F.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(F.bold(`
198
- ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(F.dim(` Cross-validated, because more parameters always fit training data better.
199
- `)),So(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(F.green(`
200
- Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(F.dim(" that need different corrections."))):s.best==="temperature"?console.log(F.dim(`
201
- One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(F.dim(`
202
- Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});ze.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",go).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=Eo(e),t=o.gradedRows({...Sr(e),labeledOnly:!0}),n=qa(t,Number(e.steps));if(n.length===0){console.log(F.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}So(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});ze.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",go).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{jt();let o=Eo(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
196
+ what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(W.bold(`
197
+ reliability (equal-width bins)`)),Eo(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});ze.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",go).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=Ao(e),t=o.gradedRows(Ar(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Ya(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(W.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(W.bold(`
198
+ ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(W.dim(` Cross-validated, because more parameters always fit training data better.
199
+ `)),Eo(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(W.green(`
200
+ Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(W.dim(" that need different corrections."))):s.best==="temperature"?console.log(W.dim(`
201
+ One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(W.dim(`
202
+ Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});ze.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",go).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=Ao(e),t=o.gradedRows({...Ar(e),labeledOnly:!0}),n=Ga(t,Number(e.steps));if(n.length===0){console.log(W.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}Eo(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});ze.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",go).requiredOption("--seat <seat>").option("--backend <name>","default: the backend that recorded the row").option("--model <id>").option("--call <id>","a specific call id; default is the newest with stored state").option("-n, --samples <n>","default 15","15").option("--json").action(async e=>{Ot();let o=Ao(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
203
203
  WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
204
204
  ${e.call?"AND id = ?":""}
205
- ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(F.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(F.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Wa(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(F.bold(`
206
- ${e.seat} on ${i.backend} (${i.model})`)),console.log(F.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
207
- `)),So(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?F.red("NO"):"yes"})),!1),console.log(`
208
- mean stdev ${i.meanStdev.toFixed(4)}`),console.log(F.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(F.red(`
209
- Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(F.dim(` not merely by how much. Usually a compound question: one name, several questions.
210
- Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(F.green(`
211
- Every question held its decision across all samples.`)),console.log(F.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});ze.command("backends").description("registered decision backends and what they claim").action(()=>{jt();let e=ja().map(o=>{let t=Di(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});So(e,!1),console.log(F.dim(`
205
+ ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(W.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(W.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Va(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(W.bold(`
206
+ ${e.seat} on ${i.backend} (${i.model})`)),console.log(W.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
207
+ `)),Eo(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?W.red("NO"):"yes"})),!1),console.log(`
208
+ mean stdev ${i.meanStdev.toFixed(4)}`),console.log(W.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(W.red(`
209
+ Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(W.dim(` not merely by how much. Usually a compound question: one name, several questions.
210
+ Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(W.green(`
211
+ Every question held its decision across all samples.`)),console.log(W.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});ze.command("backends").description("registered decision backends and what they claim").action(()=>{Ot();let e=_a().map(o=>{let t=Pi(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});Eo(e,!1),console.log(W.dim(`
212
212
  source where the numbers come from. "verbalized" means the model wrote them
213
213
  into its answer; "logits" means they were read off its next-token
214
214
  distribution. Logits are the model's actual posterior \u2014 verbalized
@@ -216,22 +216,22 @@ ${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\`.`))});ze.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=>{jt();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=Tt(s,"Which option fits this state?")}e.noul&&(o.verdict=Oo(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 Di(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as mf}from"commander";import O from"chalk";import{resolve as zd}from"path";import{existsSync as pf}from"fs";import uf from"better-sqlite3";var Fd=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],cf=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function Bd(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...cf,...Fd,"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\`.`))});ze.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=>{Ot();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=jt(s,"Which option fits this state?")}e.noul&&(o.verdict=Oo(String(e.noul))),Object.keys(o).length===0&&(console.log(W.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await Pi(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Ef}from"commander";import O from"chalk";import{resolve as tg}from"path";import{existsSync as Af}from"fs";import Tf 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"],kf=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function Qd(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...kf,...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=Oc({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=Fd.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,b)=>w+b,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:ac(d.injected_context)}})}function Er(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function Ar(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 Wd(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:Ar(e.map(o=>o.tokens)),medianTurns:Ar(e.map(o=>o.turns)),medianDurationMs:Ar(e.map(o=>o.durationMs))}}function Jd(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 Er(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(Er));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=>Er(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Wd(u),after:Wd(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Xo from"chalk";function lf(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function df(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function gf(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function Tr(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 Hd(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 ${lf(o.medianTokens)}${t?Tr(t.medianTokens,o.medianTokens):""}`,`turns ${gf(o.medianTurns)}${t?Tr(t.medianTurns,o.medianTurns):""}`,`time ${df(o.medianDurationMs)}${t?Tr(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function Gd(e,o){if(e.length===0)return[Xo.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Xo.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(`${Xo.bold(s.agentId)} ${Xo.cyan(s.cluster)}`),n=i),t.push(` ${Xo.yellow(s.lesson)} ${Xo.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Xo.dim(Hd("before",s.before))),t.push(Hd("after",s.after,s.before))}return t.push(""),t.push(Xo.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var Yt=new mf().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Ys(e){let o=zd(e.cwd??process.cwd()),t=zd(o,e.path??".agentx/db.sqlite");pf(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 uf(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 ff(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 Yd(e){if(!e)return;let o=ff(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 hf(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 jr(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}Yt.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=Ys(e),t=cc(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Yd(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=jr(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(hf(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});Yt.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=Ys(o),n=Wi(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}yf(n.task,n.steps)});function yf(e,o){let t=jr(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?jr(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=Pc({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,b)=>w+b,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:uc(d.injected_context)}})}function Tr(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function jr(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 Kd(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:jr(e.map(o=>o.tokens)),medianTurns:jr(e.map(o=>o.turns)),medianDurationMs:jr(e.map(o=>o.durationMs))}}function Zd(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 Tr(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(Tr));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=>Tr(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Kd(u),after:Kd(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Xo from"chalk";function vf(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function xf(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function Sf(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function Or(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 eg(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 ${vf(o.medianTokens)}${t?Or(t.medianTokens,o.medianTokens):""}`,`turns ${Sf(o.medianTurns)}${t?Or(t.medianTurns,o.medianTurns):""}`,`time ${xf(o.medianDurationMs)}${t?Or(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function og(e,o){if(e.length===0)return[Xo.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Xo.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(`${Xo.bold(s.agentId)} ${Xo.cyan(s.cluster)}`),n=i),t.push(` ${Xo.yellow(s.lesson)} ${Xo.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Xo.dim(eg("before",s.before))),t.push(eg("after",s.after,s.before))}return t.push(""),t.push(Xo.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var Vt=new Ef().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Vs(e){let o=tg(e.cwd??process.cwd()),t=tg(o,e.path??".agentx/db.sqlite");Af(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 Tf(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 jf(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 ng(e){if(!e)return;let o=jf(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 Of(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 Cr(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}Vt.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=Vs(e),t=fc(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:ng(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=Cr(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(Of(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});Vt.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=Vs(o),n=Bi(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}Cf(n.task,n.steps)});function Cf(e,o){let t=Cr(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?Cr(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(`
230
230
  `).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2190")} ${a}`).join(`
231
231
  `)),n.outputSummary.split(`
232
- `).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}Yt.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=Ys(e),t=Math.max(1,parseInt(e.min,10)||2),n=Bd(o,{since:Yd(e.since),agentId:e.agent}),s=Jd(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of Gd(s,{minSamples:t}))console.log(i)});Yt.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=Ys(o),n=Wi(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(),zs(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?zs(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(),zs(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(),zs(d.content??"(empty reply)"),d.error&&console.log(O.red(`
233
- error: ${d.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function zs(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 kf}from"commander";import he from"chalk";import{existsSync as vf,mkdirSync as xf,writeFileSync as Sf}from"fs";import{resolve as Kd,join as Xd,dirname as Ef}from"path";var wf=`# AgentX destructive-action guardrails \u2014 global policy
232
+ `).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}Vt.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=Vs(e),t=Math.max(1,parseInt(e.min,10)||2),n=Qd(o,{since:ng(e.since),agentId:e.agent}),s=Zd(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of og(s,{minSamples:t}))console.log(i)});Vt.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=Vs(o),n=Bi(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(),Ys(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Ys(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(),Ys(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(),Ys(d.content??"(empty reply)"),d.error&&console.log(O.red(`
233
+ error: ${d.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Ys(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 _f}from"commander";import he from"chalk";import{existsSync as Df,mkdirSync as Pf,writeFileSync as Mf}from"fs";import{resolve as rg,join as ig,dirname as Lf}from"path";var If=`# 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
- `,$f=`# Production protected resources.
260
+ `,Nf=`# 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
- `,bf=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
282
+ `,Rf=`# 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,9 +288,9 @@ rules:
288
288
  action: deny
289
289
  severity: critical
290
290
  message: "coder-agent is not permitted to run commands against production."
291
- `,Vd=[{relPath:"policy.yaml",content:wf},{relPath:"environments/production.yaml",content:$f},{relPath:"agents/coder-agent.yaml",content:bf}];var Ko=new kf().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Or(e){return e==="deny"?he.red:e==="escalate"||e==="ask"?he.yellow:e==="warn"?he.magenta:he.green}function Vs(e){return e.root?Kd(e.root):bl()}Ko.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 $l({root:Vs(e),agentId:e.agent,env:e.env}),process.exit(0)});Ko.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=Vs(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=wl({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}Af(s,i,r)});function Af(e,o,t){let n=Or(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":he.dim(" (no rule matched)")}`),console.log(` enforced as ${Or(e.effectiveAction)(e.effectiveAction)} ${he.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${he.cyan(e.ruleId)}${e.severity?he.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${he.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${he.dim(`evaluated in ${t}ms`)}`),console.log()}Ko.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=Va({root:Vs(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(he.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=Or(t.verdict),i=t.effective_action!==t.verdict?he.dim(`->${t.effective_action}`):"";console.log(` ${he.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${he.cyan((t.agent_id??"?").padEnd(16))} ${he.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(he.dim(` target: ${t.resolved_target}`))}});Ko.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=Xd(Kd(e.root),hl),t=0;for(let n of Vd){let s=Xd(o,n.relPath);if(vf(s)&&!e.force){console.log(he.dim(` skip (exists) ${n.relPath}`));continue}xf(Ef(s),{recursive:!0}),Sf(s,n.content),console.log(he.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${he.cyan(o)}`),console.log(he.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(he.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Ko.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(he.green(` daemon reloaded (${e.url})`)):console.log(he.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(he.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Ko.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=yl(Vs(e),e.agent);console.log(JSON.stringify(o,null,2))});Tn();import{Command as If}from"commander";import{execFile as Nf}from"child_process";import{promisify as Rf}from"util";import{existsSync as _f}from"fs";import Ye from"chalk";An();var Jn="ui-element";function Xs(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:Bn(t.tried,80),screenChanged:t.changed,note:t.note?Bn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Qd(t.role),label:Bn(t.label,120),value:t.value?Bn(t.value,80):null,enabled:t.enabled}))}}function Ks(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Qd(t.role)}: ${Bn(n,80)}`}return{target:Tt(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:Oo("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 Qs(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 Qd(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Bn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{Command as Vt}from"commander";import mo from"chalk";var Zd=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function He(e,o,t,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${Zd}${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 ${Zd}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function Tf(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 Ir(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}
291
+ `,sg=[{relPath:"policy.yaml",content:If},{relPath:"environments/production.yaml",content:Nf},{relPath:"agents/coder-agent.yaml",content:Rf}];var Ko=new _f().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Ir(e){return e==="deny"?he.red:e==="escalate"||e==="ask"?he.yellow:e==="warn"?he.magenta:he.green}function Xs(e){return e.root?rg(e.root):Tl()}Ko.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 Al({root:Xs(e),agentId:e.agent,env:e.env}),process.exit(0)});Ko.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=Xs(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=El({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}qf(s,i,r)});function qf(e,o,t){let n=Ir(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":he.dim(" (no rule matched)")}`),console.log(` enforced as ${Ir(e.effectiveAction)(e.effectiveAction)} ${he.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${he.cyan(e.ruleId)}${e.severity?he.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${he.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${he.dim(`evaluated in ${t}ms`)}`),console.log()}Ko.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=tc({root:Xs(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(he.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=Ir(t.verdict),i=t.effective_action!==t.verdict?he.dim(`->${t.effective_action}`):"";console.log(` ${he.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${he.cyan((t.agent_id??"?").padEnd(16))} ${he.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(he.dim(` target: ${t.resolved_target}`))}});Ko.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=ig(rg(e.root),xl),t=0;for(let n of sg){let s=ig(o,n.relPath);if(Df(s)&&!e.force){console.log(he.dim(` skip (exists) ${n.relPath}`));continue}Pf(Lf(s),{recursive:!0}),Mf(s,n.content),console.log(he.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${he.cyan(o)}`),console.log(he.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(he.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Ko.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(he.green(` daemon reloaded (${e.url})`)):console.log(he.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(he.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Ko.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=Sl(Xs(e),e.agent);console.log(JSON.stringify(o,null,2))});jn();import{Command as Jf}from"commander";import{execFile as Hf}from"child_process";import{promisify as Gf}from"util";import{existsSync as zf}from"fs";import Ye from"chalk";Tn();var Hn="ui-element";function Ks(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:Jn(t.tried,80),screenChanged:t.changed,note:t.note?Jn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:ag(t.role),label:Jn(t.label,120),value:t.value?Jn(t.value,80):null,enabled:t.enabled}))}}function Qs(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${ag(t.role)}: ${Jn(n,80)}`}return{target:jt(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:Oo("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 Zs(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 ag(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Jn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{Command as Xt}from"commander";import mo from"chalk";var cg=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function He(e,o,t,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${cg}${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 ${cg}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function Ff(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 Rr(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}
292
292
  ${e.reason}${e.summary?mo.dim(`
293
- summary: ${e.summary}`):""}`}async function Hn(e){try{await e()}catch(o){console.log(mo.red(` ${o?.message??o}`)),process.exit(1)}}var jf=new Vt("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=>Hn(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 He("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},On());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}`)})),Of=new Vt("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=>Hn(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await He("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(Ir(n))}));function Cr(e,o){return new Vt(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>Hn(async()=>{let{call:n}=await He("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(Ir(n))}))}var Cf=new Vt("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>Hn(async()=>{let{call:t}=await He("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(Ir(t))}));function eg(e,o){return new Vt(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)=>Hn(()=>{let{summary:s}=so(i=>Tf(i,t,o),{configPath:n.config});console.log(mo.green(` ${s}`))}))}var og=new Vt("call").description("agents ring you for a live voice call").addCommand(jf).addCommand(Of).addCommand(Cr("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(Cr("decline","decline a ringing call")).addCommand(Cf).addCommand(Cr("hangup","end an answered call")).addCommand(eg("allow",!0)).addCommand(eg("disallow",!1));var Df=Rf(Nf);async function tg(e,o,t){await He("POST","/voice/guide",{rect:e,mark:t.mark,...t.hold?{hold:Number(t.hold)}:{},...t.text?{text:t.text}:{},...t.expression?{expression:t.expression}:{}}).then(s=>s?.shown===!0,()=>!1)||await Df(Le,["point","--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height),"--label",o])}var ng=new If().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").option("--mark <kind>",`how the character marks it: ${Os.join(", ")}`,"box").option("--hold <seconds>","how long the character stays there (8 by default)").option("--text <words>","what the character's bubble says there (no bubble without it)").option("--expression <name>",`the state the character shows there: ${Co.join(", ")}`).action(async(e,o)=>{Os.includes(o.mark)||(console.log(Ye.red(` --mark is one of: ${Os.join(", ")}`)),process.exit(1)),o.expression!==void 0&&!Co.includes(o.expression)&&(console.log(Ye.red(` --expression is one of: ${Co.join(", ")}`)),process.exit(1)),o.hold!==void 0&&!(Number(o.hold)>0&&Number(o.hold)<=Bo.max)&&(console.log(Ye.red(` --hold is a number of seconds, up to ${Bo.max}`)),process.exit(1)),_f(Le)||(console.log(Ye.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await Ns({max:Number(o.max)||40})}catch(d){console.log(Ye.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ye.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=Rn(t,n[0].id);d&&(console.log(Ye.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ye.bold(n[0].label)),await tg(d,n[0].label,o));return}let s=await bo(Jn,Xs({request:e,app:t.app,window:t.window,candidates:n}),Ks(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ye.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Jn}.mode`)),process.exit(1));let i=Qs(s.answers,n),r=Rn(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(Ye.yellow(` nothing on screen matches "${e}"`)+Ye.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(` ${Ye.green("\u2192")} ${Ye.bold(g)} `+Ye.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await tg(r,g,o)});import{Command as Pf}from"commander";import Xt from"chalk";var sg=new Pf().name("express").description(`have the character show one of its states for a few seconds: ${Co.join(", ")}`).argument("<name>",`the state: ${Co.join(", ")}`).option("--hold <seconds>",`how long it shows it (${Bo.default} by default)`).action(async(e,o)=>{Co.includes(e)||(console.log(Xt.red(` the state is one of: ${Co.join(", ")}`)),process.exit(1)),o.hold!==void 0&&!(Number(o.hold)>0&&Number(o.hold)<=Bo.max)&&(console.log(Xt.red(` --hold is a number of seconds, up to ${Bo.max}`)),process.exit(1));try{await He("POST","/voice/guide",{expression:e,...o.hold?{hold:Number(o.hold)}:{}}),console.log(` ${Xt.green("\u2192")} ${Xt.bold(e)} ${Xt.dim(`for ${o.hold??Bo.default} seconds`)}`)}catch(t){console.log(Xt.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as sh}from"commander";import Ve from"chalk";import{readFileSync as ig}from"fs";import{homedir as Mf}from"os";import{join as Lf}from"path";var rg=12e5,qf="https://openrouter.ai/api/v1/chat/completions",Uf=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Ff(e={kind:"window"},o=rg,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return qt(e,{},n);try{return await qt(e,{untilStable:!0},n)}catch(s){if(s instanceof Fl)return qt(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.
293
+ summary: ${e.summary}`):""}`}async function Gn(e){try{await e()}catch(o){console.log(mo.red(` ${o?.message??o}`)),process.exit(1)}}var Uf=new Xt("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=>Gn(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 He("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},Cn());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}`)})),Wf=new Xt("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=>Gn(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await He("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(Rr(n))}));function Nr(e,o){return new Xt(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>Gn(async()=>{let{call:n}=await He("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(Rr(n))}))}var Bf=new Xt("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>Gn(async()=>{let{call:t}=await He("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(Rr(t))}));function lg(e,o){return new Xt(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)=>Gn(()=>{let{summary:s}=so(i=>Ff(i,t,o),{configPath:n.config});console.log(mo.green(` ${s}`))}))}var dg=new Xt("call").description("agents ring you for a live voice call").addCommand(Uf).addCommand(Wf).addCommand(Nr("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(Nr("decline","decline a ringing call")).addCommand(Bf).addCommand(Nr("hangup","end an answered call")).addCommand(lg("allow",!0)).addCommand(lg("disallow",!1));var Yf=Gf(Hf);async function gg(e,o,t){await He("POST","/voice/guide",{rect:e,mark:t.mark,...t.hold?{hold:Number(t.hold)}:{},...t.text?{text:t.text}:{},...t.expression?{expression:t.expression}:{}}).then(s=>s?.shown===!0,()=>!1)||await Yf(Le,["point","--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height),"--label",o])}var mg=new Jf().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").option("--mark <kind>",`how the character marks it: ${Cs.join(", ")}`,"box").option("--hold <seconds>","how long the character stays there (8 by default)").option("--text <words>","what the character's bubble says there (no bubble without it)").option("--expression <name>",`the state the character shows there: ${Co.join(", ")}`).action(async(e,o)=>{Cs.includes(o.mark)||(console.log(Ye.red(` --mark is one of: ${Cs.join(", ")}`)),process.exit(1)),o.expression!==void 0&&!Co.includes(o.expression)&&(console.log(Ye.red(` --expression is one of: ${Co.join(", ")}`)),process.exit(1)),o.hold!==void 0&&!(Number(o.hold)>0&&Number(o.hold)<=Bo.max)&&(console.log(Ye.red(` --hold is a number of seconds, up to ${Bo.max}`)),process.exit(1)),zf(Le)||(console.log(Ye.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await Rs({max:Number(o.max)||40})}catch(d){console.log(Ye.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Ye.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=_n(t,n[0].id);d&&(console.log(Ye.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Ye.bold(n[0].label)),await gg(d,n[0].label,o));return}let s=await ko(Hn,Ks({request:e,app:t.app,window:t.window,candidates:n}),Qs(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Ye.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Hn}.mode`)),process.exit(1));let i=Zs(s.answers,n),r=_n(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(Ye.yellow(` nothing on screen matches "${e}"`)+Ye.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(` ${Ye.green("\u2192")} ${Ye.bold(g)} `+Ye.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await gg(r,g,o)});import{Command as Vf}from"commander";import Kt from"chalk";var pg=new Vf().name("express").description(`have the character show one of its states for a few seconds: ${Co.join(", ")}`).argument("<name>",`the state: ${Co.join(", ")}`).option("--hold <seconds>",`how long it shows it (${Bo.default} by default)`).action(async(e,o)=>{Co.includes(e)||(console.log(Kt.red(` the state is one of: ${Co.join(", ")}`)),process.exit(1)),o.hold!==void 0&&!(Number(o.hold)>0&&Number(o.hold)<=Bo.max)&&(console.log(Kt.red(` --hold is a number of seconds, up to ${Bo.max}`)),process.exit(1));try{await He("POST","/voice/guide",{expression:e,...o.hold?{hold:Number(o.hold)}:{}}),console.log(` ${Kt.green("\u2192")} ${Kt.bold(e)} ${Kt.dim(`for ${o.hold??Bo.default} seconds`)}`)}catch(t){console.log(Kt.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as yh}from"commander";import Ve from"chalk";import{readFileSync as ug}from"fs";import{homedir as Xf}from"os";import{join as Kf}from"path";var fg=12e5,Qf="https://openrouter.ai/api/v1/chat/completions",Zf=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function eh(e={kind:"window"},o=fg,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return Ft(e,{},n);try{return await Ft(e,{untilStable:!0},n)}catch(s){if(s instanceof Yl)return Ft(e,{},n);throw s}}var oh=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
294
294
 
295
295
  Report only what is visible in this image.
296
296
 
@@ -298,13 +298,13 @@ The failure that matters: an application that performs an action is on screen, a
298
298
 
299
299
  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.
300
300
 
301
- 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 Bf(e,o,t,n){let s=Hf();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=ig(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
301
+ 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 th(e,o,t,n){let s=sh();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=ug(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
302
302
 
303
- The image is the region ${Jf(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(qf,{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 Zs(e,o={}){let t=Date.now(),n=await Ff(o.region??{kind:"window"},o.maxPixels??rg,{settle:o.settle,screen:o.screen}),s=await Bf(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 Jf(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 Gn;function Hf(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Gn!==void 0)return Gn??void 0;try{let e=ig(Lf(Mf(),".agentx","openrouter-key.txt"),"utf-8").trim();Gn=e.length>0?e:null}catch{Gn=null}return Gn??void 0}import{execFile as Gf}from"child_process";import{promisify as zf}from"util";var Yf=zf(Gf),Vf=["screencapture"],Xf=["Screen Studio","OBS","QuickTime Player","Zoom"];async function cg(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Kf()),t}async function Kf(){let e=await ag(Vf);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 ag(Xf);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 ag(e){let o=[];for(let t of e)try{let{stdout:n}=await Yf("pgrep",["-x",t]),s=n.trim().split(`
304
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Tn();An();var lg="screen-state",dg={observable:Oo("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:Oo("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 gg(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 mg(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Qf=.6,Zf=.7,eh=.3;async function zn(e,o={}){let[t,n]=await Promise.all([Zs(e,o),cg(e).catch(()=>[])]),s=o.observableFloor??Qf,i=await bo(lg,gg({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:nh(t),treeNote:o.treeNote,probes:n}),dg,{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:th(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=mg(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 (${ei(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Zf?"confirmed":a<=eh?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:oh(c,a,t),sighting:t,probes:n}}function oh(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${ei(o)}). ${n}`:e==="refuted"?`Not true (${ei(1-o)} it is false). ${n}`:`Inconclusive (${ei(o)}, between the thresholds). ${n}`}function th(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 nh(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 ei=e=>`${Math.round(e*100)}%`;var pg=new sh().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(Ve.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 zn(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?ko():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"?Ve.green("\u2713"):s.outcome==="refuted"?Ve.red("\u2717"):Ve.yellow("?");console.log(` ${i} ${Ve.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Ve.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Ve.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 Zs(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?ko():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Ve.bold(n.observation)}`),n.evidence&&console.log(Ve.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${ih(n.reading)}`),console.log(Ve.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Ve.red(` ${n?.message??n}`)),process.exit(1)}});function ih(e){return e==="yes"?Ve.green(e):e==="no"?Ve.red(e):Ve.yellow(e)}import{Command as rh}from"commander";import po from"chalk";import{spawn as ah}from"child_process";function Qo(e){console.log(po.red(` ${e}`)),process.exit(1)}function ug(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?po.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(po.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function ch(e){return new Promise(o=>{let t=ah(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var Yn=new rh("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");Yn.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=ko(o.config),n;try{n=Rs(o.region,t)}catch(r){Qo(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Qo("--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 _s(()=>ch(e),n,{out:o.out,untilStable:r},i);c||(console.log(po.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),ug(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}ug(await qt(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){Qo(r?.message??String(r))}});Yn.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:${ct()}`).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||Qo(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(po.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${po.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Qo(`could not reach the daemon: ${n?.message??n}`)}});Yn.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&&Qo(`--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)||Qo("--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=ko(e.config);console.log(`
303
+ The image is the region ${nh(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:oh,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(Qf,{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 ei(e,o={}){let t=Date.now(),n=await eh(o.region??{kind:"window"},o.maxPixels??fg,{settle:o.settle,screen:o.screen}),s=await th(e,n,o.model??Zf,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 nh(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 zn;function sh(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(zn!==void 0)return zn??void 0;try{let e=ug(Kf(Xf(),".agentx","openrouter-key.txt"),"utf-8").trim();zn=e.length>0?e:null}catch{zn=null}return zn??void 0}import{execFile as ih}from"child_process";import{promisify as rh}from"util";var ah=rh(ih),ch=["screencapture"],lh=["Screen Studio","OBS","QuickTime Player","Zoom"];async function yg(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await dh()),t}async function dh(){let e=await hg(ch);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 hg(lh);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 hg(e){let o=[];for(let t of e)try{let{stdout:n}=await ah("pgrep",["-x",t]),s=n.trim().split(`
304
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}jn();Tn();var wg="screen-state",$g={observable:Oo("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:Oo("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 bg(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 kg(e){return{observable:e.observable.noul,holds:e.holds.noul}}var gh=.6,mh=.7,ph=.3;async function Yn(e,o={}){let[t,n]=await Promise.all([ei(e,o),yg(e).catch(()=>[])]),s=o.observableFloor??gh,i=await ko(wg,bg({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:hh(t),treeNote:o.treeNote,probes:n}),$g,{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:fh(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=kg(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 (${oi(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=mh?"confirmed":a<=ph?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:uh(c,a,t),sighting:t,probes:n}}function uh(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${oi(o)}). ${n}`:e==="refuted"?`Not true (${oi(1-o)} it is false). ${n}`:`Inconclusive (${oi(o)}, between the thresholds). ${n}`}function fh(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 hh(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 oi=e=>`${Math.round(e*100)}%`;var vg=new yh().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(Ve.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 Yn(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?vo():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"?Ve.green("\u2713"):s.outcome==="refuted"?Ve.red("\u2717"):Ve.yellow("?");console.log(` ${i} ${Ve.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Ve.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Ve.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 ei(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?vo():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Ve.bold(n.observation)}`),n.evidence&&console.log(Ve.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${wh(n.reading)}`),console.log(Ve.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Ve.red(` ${n?.message??n}`)),process.exit(1)}});function wh(e){return e==="yes"?Ve.green(e):e==="no"?Ve.red(e):Ve.yellow(e)}import{Command as $h}from"commander";import po from"chalk";import{spawn as bh}from"child_process";function Qo(e){console.log(po.red(` ${e}`)),process.exit(1)}function xg(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?po.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(po.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function kh(e){return new Promise(o=>{let t=bh(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var Vn=new $h("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");Vn.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=vo(o.config),n;try{n=_s(o.region,t)}catch(r){Qo(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Qo("--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 Ds(()=>kh(e),n,{out:o.out,untilStable:r},i);c||(console.log(po.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),xg(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}xg(await Ft(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){Qo(r?.message??String(r))}});Vn.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:${ct()}`).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||Qo(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(po.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${po.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Qo(`could not reach the daemon: ${n?.message??n}`)}});Vn.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&&Qo(`--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)||Qo("--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=vo(e.config);console.log(`
305
305
  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(" "):po.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":po.dim("off")} ${po.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
306
- `);return}try{let{summary:s,backupPath:i}=so(r=>{let a=Ul(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(po.green(`
307
- \u2713 ${s}`)),i&&console.log(po.dim(` Backup: ${i}`)),console.log()}catch(s){Qo(s?.message??String(s))}});Tn();import{Command as gh}from"commander";import{execFile as vg}from"child_process";import{promisify as mh}from"util";import{existsSync as ph,readFileSync as uh,writeFileSync as xg,mkdirSync as fh}from"fs";import{homedir as hh}from"os";import{join as yh,dirname as wh}from"path";import Ue from"chalk";An();var Nr="paste-transform";function fg(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function hg(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:Oo("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:Tt(o,"What shape should this paste arrive in?")}}function yg(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 lh=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"]),dh=e=>/^https?:\/\/\S+$/i.test(e.trim()),Rr=[{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
+ `);return}try{let{summary:s,backupPath:i}=so(r=>{let a=zl(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(po.green(`
307
+ \u2713 ${s}`)),i&&console.log(po.dim(` Backup: ${i}`)),console.log()}catch(s){Qo(s?.message??String(s))}});jn();import{Command as Sh}from"commander";import{execFile as Ig}from"child_process";import{promisify as Eh}from"util";import{existsSync as Ah,readFileSync as Th,writeFileSync as Ng,mkdirSync as jh}from"fs";import{homedir as Oh}from"os";import{join as Ch,dirname as Ih}from"path";import Fe from"chalk";Tn();var _r="paste-transform";function Sg(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Eg(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:Oo("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:jt(o,"What shape should this paste arrive in?")}}function Ag(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 vh=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"]),xh=e=>/^https?:\/\/\S+$/i.test(e.trim()),Dr=[{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(`
308
308
  `);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(`
309
309
  `).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
310
310
 
@@ -312,27 +312,27 @@ The image is the region ${Jf(o)}.`},{type:"image_url",image_url:{url:`data:image
312
312
  `).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
313
313
  `)}},{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(`
314
314
  `);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
315
- `)}},{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(!dh(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])lh.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(`
315
+ `)}},{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(!xh(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])vh.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(`
316
316
  `)||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,`
317
- `).trim();return o===e?null:o}}];function wg(e){let o=[];for(let t of Rr){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function $g(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
317
+ `).trim();return o===e?null:o}}];function Tg(e){let o=[];for(let t of Dr){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function jg(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
318
318
  \u2026[${e.length-o} more characters]\u2026
319
- ${e.slice(-n)}`}function bg(e){let o=e.trim();return o.includes(`
320
- `)||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 _r=mh(vg),Sg=new gh().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 (${Rr.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=bh();c===null&&(console.log(Ue.yellow(" nothing to undo")),process.exit(2)),await Ag(c),console.log(` ${Ue.green("\u2192")} clipboard restored`);return}let o=await kh();if(o||(console.log(Ue.yellow(" clipboard is empty")),process.exit(2)),bg(o)){Eg(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=wg(o),n=await vh();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Ue.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ue.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Kt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Kt(e,"asIs",o,o,"nothing else applies",0);return}let s=await bo(Nr,fg({preview:$g(o),length:o.length,lineCount:o.split(`
321
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),hg(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Kt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${Nr}.mode`,0);return}let i=yg(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Kt(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 Kt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Kt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Kt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&($h(n),await Ag(t)),Eg(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await _r(Le,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ue.red(` could not paste: ${a?.message??a}`))})}function Eg(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Ue.dim("\u2192")} ${Ue.bold("unchanged")} ${Ue.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Ue.green("\u2192")} ${Ue.bold(o.applied)} ${Ue.dim(`\xB7 ${o.reason}`)}`),console.log(Ue.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Ue.dim(kg(o.original))),console.log(Ue.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(kg(o.result)),!e.apply&&!e.paste&&console.log(Ue.dim(`
322
- (dry run \u2014 pass --apply to write it back)`))}var kg=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
319
+ ${e.slice(-n)}`}function Og(e){let o=e.trim();return o.includes(`
320
+ `)||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 Pr=Eh(Ig),Rg=new Sh().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 (${Dr.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=Rh();c===null&&(console.log(Fe.yellow(" nothing to undo")),process.exit(2)),await Dg(c),console.log(` ${Fe.green("\u2192")} clipboard restored`);return}let o=await _h();if(o||(console.log(Fe.yellow(" clipboard is empty")),process.exit(2)),Og(o)){_g(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Tg(o),n=await Dh();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Fe.red(` "${e.as}" does not apply to this clipboard`)),console.log(Fe.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Qt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Qt(e,"asIs",o,o,"nothing else applies",0);return}let s=await ko(_r,Sg({preview:jg(o),length:o.length,lineCount:o.split(`
321
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Eg(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Qt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${_r}.mode`,0);return}let i=Ag(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Qt(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 Qt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Qt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Qt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(Nh(n),await Dg(t)),_g(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Pr(Le,["key","--name","v","--mod","command"]).catch(a=>{console.log(Fe.red(` could not paste: ${a?.message??a}`))})}function _g(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Fe.dim("\u2192")} ${Fe.bold("unchanged")} ${Fe.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Fe.green("\u2192")} ${Fe.bold(o.applied)} ${Fe.dim(`\xB7 ${o.reason}`)}`),console.log(Fe.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Fe.dim(Cg(o.original))),console.log(Fe.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Cg(o.result)),!e.apply&&!e.paste&&console.log(Fe.dim(`
322
+ (dry run \u2014 pass --apply to write it back)`))}var Cg=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
323
323
  `).map(t=>` ${t}`).join(`
324
- `),oi=yh(hh(),".agentx","paste-undo.txt");function $h(e){try{fh(wh(oi),{recursive:!0}),xg(oi,e,{mode:384})}catch{}}function bh(){try{let e=uh(oi,"utf-8");return xg(oi,"",{mode:384}),e.length?e:null}catch{return null}}async function kh(){let{stdout:e}=await _r("pbpaste",[],{maxBuffer:16777216});return e}async function Ag(e){await new Promise((o,t)=>{vg("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function vh(){if(!ph(Le))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await _r(Le,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:xh(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function xh(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 Sh}from"commander";import Ge from"chalk";te();function Tg(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 _s(()=>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 Eh=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Ah(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
325
- ${n}`:n,a=await fetch(`${Eh}/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 Th(e){let o;try{o=T(e.config)}catch{o=void 0}let t=vs(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??Es(o);return{alert:Bc(t),banner:t.banner,channel:n}}var jg=new Sh().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 Rc,n=uc(),{alert:s,banner:i,channel:r}=Th(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=ko(o.config),d=Tg(s,Rs("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?Ge.yellow("\u25D0"):Ge.green("\u25CB")} ${fc(n)} ${Ge.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(Ge.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=Ah(r,o.chatId);if(o.flush){let g=await Gc(l,{queue:t,alert:s});console.log(g?Ge.green(` delivered ${g} held notification(s)`):Ge.dim(" nothing was held"));return}e?.trim()||(console.log(Ge.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await Hc({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?Ge.green("\u2192"):Ge.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Ge.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Ge.yellow("?"):Ge.green("\u2713")} banner: ${d.shot.path}${Ge.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Ge.yellow(` ${d.error}`))}catch(g){console.log(Ge.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});import{Command as yt}from"commander";import Xe from"chalk";function Og(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?Xe.yellow("missed"):e.status==="ringing"?Xe.green("asking"):e.status==="answered"?Xe.green("showing"):Xe.dim(e.status),n=e.note?Xe.dim(` (${e.note})`):"";return` ${Xe.dim(e.id)} ${o} ${e.agentId} ${t}${n}
326
- ${e.reason}`}async function Qt(e){try{await e()}catch(o){console.log(Xe.red(` ${o?.message??o}`)),process.exit(1)}}function Cg(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 jh=new yt("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=>Qt(async()=>{let o=Cg("a camera ask"),t=await He("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal",kind:"camera"},On());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?Xe.green("\u{1F4F7}"):Xe.yellow("\u23F8")} ${t.call.id} ${n}`)})),Oh=new yt("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=>Qt(async()=>{let o=Cg("a look"),t=await He("POST","/webrtc/camera/look",{agentId:o},On());if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(` ${t.frame.path}`),console.log(Xe.dim(` ${t.frame.width}x${t.frame.height}, taken ${new Date(t.frame.takenAt).toLocaleTimeString()} (share ${t.callId})`))})),Ch=new yt("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=>Qt(async()=>{let o=new URLSearchParams({limit:String(e.limit),kind:"camera"});e.status&&o.set("status",e.status);let{calls:t}=await He("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(Xe.dim(" no camera asks"));return}for(let n of t)console.log(Og(n))})),Ih=new yt("watching").description("agents watching a phone camera right now").option("--json","print as JSON").action(e=>Qt(async()=>{let{active:o}=await He("GET","/webrtc/camera/watch");if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(Xe.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(` ${Xe.dim(t.callId)} ${t.agentId} ${t.frames} frames, ${t.looks} looks, ${n} min left`)}})),Nh=new yt("decline").description("turn down a camera ask").argument("<id>","ask id, from `agentx camera list`").action(e=>Qt(async()=>{let{call:o}=await He("POST",`/calls/${encodeURIComponent(e)}/decline`,{});console.log(Og(o))})),Rh=new yt("stop").description("end a live watch (the share id from `agentx camera watching`)").argument("<id>","share id").action(e=>Qt(async()=>{await He("POST",`/webrtc/camera/watch/${encodeURIComponent(e)}/stop`,{}),console.log(Xe.green(` ${e} stopped`))})),Ig=new yt("camera").description("agents ask to see through your phone camera").addCommand(jh).addCommand(Oh).addCommand(Ch).addCommand(Ih).addCommand(Nh).addCommand(Rh);Tn();Ja();Oa();An();import{Command as _h}from"commander";import{readFileSync as Dh}from"fs";var Ng=new _h().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?Dh(e.file,"utf8"):await Ph()}catch(r){wt(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return wt("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return wt(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return wt("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return wt("spec needs at least one entry in `questions`");try{La(t.questions)}catch(r){return wt(r?.message??String(r))}let n=t.seat||e.seat;jt(),process.env[Ga(n)]="active";let s=null;if(e.record!==!1)try{s=new ms({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
327
- `)}Ha({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await bo(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return wt(`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 wt(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Ph(){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")}Tn();import{Command as uy}from"commander";import{execFile as fy,spawn as zg}from"child_process";import{promisify as hy}from"util";import{existsSync as yy,statSync as wy}from"fs";import{join as Yg}from"path";import{tmpdir as $y}from"os";import se from"chalk";var Mh={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."}]},Lh={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."}]},qh={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."}]},Dr=[Mh,Lh,qh];te();te();import uo from"chalk";import{execFile as Uh}from"child_process";import{promisify as Fh}from"util";import{createInterface as Wh}from"readline";var Rg=Fh(Uh);function Bh(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 Jh(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Rg("open",["-a",e]).catch(()=>{});try{let s=(await Zi()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function _g(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 Rg("open",["-a",o.app]),i=await Jh(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=js(n,t.agents,!1),a=t.voice.listener??Nl,c=Pt(n,t.agents[n]),l=new Dl({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:Zi,presence:t.voice.pointer?new Is(c,Le,n):Cs,speech:new Mt,model:Lt({system:_l(r.persona,a)}),act:Pl});l.on(Bh),console.log(uo.bold(`
324
+ `),ti=Ch(Oh(),".agentx","paste-undo.txt");function Nh(e){try{jh(Ih(ti),{recursive:!0}),Ng(ti,e,{mode:384})}catch{}}function Rh(){try{let e=Th(ti,"utf-8");return Ng(ti,"",{mode:384}),e.length?e:null}catch{return null}}async function _h(){let{stdout:e}=await Pr("pbpaste",[],{maxBuffer:16777216});return e}async function Dg(e){await new Promise((o,t)=>{Ig("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Dh(){if(!Ah(Le))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Pr(Le,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Ph(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Ph(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 Mh}from"commander";import Ge from"chalk";te();function Pg(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 Ds(()=>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 Lh=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function qh(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
325
+ ${n}`:n,a=await fetch(`${Lh}/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 Fh(e){let o;try{o=T(e.config)}catch{o=void 0}let t=xs(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??As(o);return{alert:Xc(t),banner:t.banner,channel:n}}var Mg=new Mh().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 Fc,n=kc(),{alert:s,banner:i,channel:r}=Fh(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=vo(o.config),d=Pg(s,_s("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?Ge.yellow("\u25D0"):Ge.green("\u25CB")} ${vc(n)} ${Ge.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(Ge.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=qh(r,o.chatId);if(o.flush){let g=await Zc(l,{queue:t,alert:s});console.log(g?Ge.green(` delivered ${g} held notification(s)`):Ge.dim(" nothing was held"));return}e?.trim()||(console.log(Ge.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await Qc({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?Ge.green("\u2192"):Ge.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Ge.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Ge.yellow("?"):Ge.green("\u2713")} banner: ${d.shot.path}${Ge.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Ge.yellow(` ${d.error}`))}catch(g){console.log(Ge.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});import{Command as yt}from"commander";import Xe from"chalk";function Lg(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?Xe.yellow("missed"):e.status==="ringing"?Xe.green("asking"):e.status==="answered"?Xe.green("showing"):Xe.dim(e.status),n=e.note?Xe.dim(` (${e.note})`):"";return` ${Xe.dim(e.id)} ${o} ${e.agentId} ${t}${n}
326
+ ${e.reason}`}async function Zt(e){try{await e()}catch(o){console.log(Xe.red(` ${o?.message??o}`)),process.exit(1)}}function qg(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 Uh=new yt("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=>Zt(async()=>{let o=qg("a camera ask"),t=await He("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal",kind:"camera"},Cn());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?Xe.green("\u{1F4F7}"):Xe.yellow("\u23F8")} ${t.call.id} ${n}`)})),Wh=new yt("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=>Zt(async()=>{let o=qg("a look"),t=await He("POST","/webrtc/camera/look",{agentId:o},Cn());if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(` ${t.frame.path}`),console.log(Xe.dim(` ${t.frame.width}x${t.frame.height}, taken ${new Date(t.frame.takenAt).toLocaleTimeString()} (share ${t.callId})`))})),Bh=new yt("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=>Zt(async()=>{let o=new URLSearchParams({limit:String(e.limit),kind:"camera"});e.status&&o.set("status",e.status);let{calls:t}=await He("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(Xe.dim(" no camera asks"));return}for(let n of t)console.log(Lg(n))})),Jh=new yt("watching").description("agents watching a phone camera right now").option("--json","print as JSON").action(e=>Zt(async()=>{let{active:o}=await He("GET","/webrtc/camera/watch");if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(Xe.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(` ${Xe.dim(t.callId)} ${t.agentId} ${t.frames} frames, ${t.looks} looks, ${n} min left`)}})),Hh=new yt("decline").description("turn down a camera ask").argument("<id>","ask id, from `agentx camera list`").action(e=>Zt(async()=>{let{call:o}=await He("POST",`/calls/${encodeURIComponent(e)}/decline`,{});console.log(Lg(o))})),Gh=new yt("stop").description("end a live watch (the share id from `agentx camera watching`)").argument("<id>","share id").action(e=>Zt(async()=>{await He("POST",`/webrtc/camera/watch/${encodeURIComponent(e)}/stop`,{}),console.log(Xe.green(` ${e} stopped`))})),Fg=new yt("camera").description("agents ask to see through your phone camera").addCommand(Uh).addCommand(Wh).addCommand(Bh).addCommand(Jh).addCommand(Hh).addCommand(Gh);jn();Ka();Da();Tn();import{Command as zh}from"commander";import{readFileSync as Yh}from"fs";var Ug=new zh().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?Yh(e.file,"utf8"):await Vh()}catch(r){wt(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return wt("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return wt(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return wt("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return wt("spec needs at least one entry in `questions`");try{Ha(t.questions)}catch(r){return wt(r?.message??String(r))}let n=t.seat||e.seat;Ot(),process.env[Za(n)]="active";let s=null;if(e.record!==!1)try{s=new ps({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
327
+ `)}Qa({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await ko(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return wt(`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 wt(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Vh(){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")}jn();import{Command as Ty}from"commander";import{execFile as jy,spawn as tm}from"child_process";import{promisify as Oy}from"util";import{existsSync as Cy,statSync as Iy}from"fs";import{join as nm}from"path";import{tmpdir as Ny}from"os";import se from"chalk";var Xh={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."}]},Kh={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."}]},Qh={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."}]},Mr=[Xh,Kh,Qh];te();te();import uo from"chalk";import{execFile as Zh}from"child_process";import{promisify as ey}from"util";import{createInterface as oy}from"readline";var Wg=ey(Zh);function ty(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 ny(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Wg("open",["-a",e]).catch(()=>{});try{let s=(await er()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function Bg(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 Wg("open",["-a",o.app]),i=await ny(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=Os(n,t.agents,!1),a=t.voice.listener??ql,c=Mt(n,t.agents[n]),l=new Wl({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:er,presence:t.voice.pointer?new Ns(c,Le,n):Is,speech:new Lt,model:qt({system:Ul(r.persona,a)}),act:Bl});l.on(ty),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=Wh({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}te();import wo from"chalk";import{execFile as iy}from"child_process";import{existsSync as qr,writeFileSync as ry}from"fs";import{homedir as ay}from"os";import{join as Hg,resolve as cy}from"path";import{promisify as ly}from"util";var Re={w:1e3,h:640},Mr=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Mg=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Dg=["none","semi","solid","fill","pattern"],Lr=180,Lg=48,Hh=["s","m","l","xl"],Gh=["draw","sans","serif","mono"];function qg(){return[`You are an illustrator drawing on a tldraw canvas ${Re.w} wide and ${Re.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 ${Lr}. 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 ${Lg} 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"}`,'Shapes and paths take an optional "rot": degrees clockwise, -90 to 90, applied after they are drawn (a tilted parasol, cocked sunglasses).','Move: {"id":"m1","say":"Nudge the boat left.","move":"boat","dx":-60,"dy":0,"rot":0,"scale":1} slides an EARLIER shape or path by dx,dy, turns it by rot degrees and resizes it by scale (0.3 to 3), animated. The viewer is watching you work, so show the craft: tilt anything that leans with rot, and after the main pieces are down use 3 to 6 moves to adjust the composition (slide pieces side by side, straighten or tilt, grow or shrink them), each placed right after the elements it adjusts.',"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: ${Mg.join(", ")}.`,`color is one of: ${Mr.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 the subject readable: no prop may cover a face, eyes or the props that matter. Put tall props (a parasol, a tree, a sign) beside the subject or behind it, drawing them before the subject so it sits in front, and keep a clear gap around the head.","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 Zt(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function fo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var ho=(e,o,t)=>Math.min(t,Math.max(o,e)),Pg=e=>ho(fo(e)??1,.1,1),Pr=e=>ho(fo(e)??0,-90,90),zh=/^#[0-9a-f]{6}$/i;function Yh(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))Mr.includes(t)&&typeof n=="string"&&zh.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Vh(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,Lg)){if(!Array.isArray(t))return null;let n=fo(t[0]),s=fo(t[1]);if(n===null||s===null)return null;o.push([ho(n,0,Re.w),ho(s,0,Re.h)])}return o.length>=2?o:null}function Ug(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=Yh(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=Zt(n.color,Mr,"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(typeof n.move=="string"){let l=n.move;if(!o.has(l)||l==="palette")return null;let g=ho(fo(n.dx)??0,-Re.w,Re.w),d=ho(fo(n.dy)??0,-Re.h,Re.h),u=ho(fo(n.scale)??1,.3,3),f=Pr(n.rot);return!g&&!d&&!f&&u===1?null:{kind:"move",id:s,say:i,target:l,dx:g,dy:d,rot:f,scale:u}}if("path"in n){let l=Vh(n.path),g=Zt(n.fill,Dg,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Pg(n.opacity),rot:Pr(n.rot)}}let a=fo(n.x),c=fo(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:ho(a,0,Re.w-20),y:ho(c,0,Re.h-20),size:Zt(n.size,Hh,"l"),color:r,font:Zt(n.font,Gh,"draw")};if(typeof n.geo=="string"){let l=fo(n.w),g=fo(n.h);if(l===null||g===null||l<4||g<4)return null;let d=ho(a,0,Re.w-4),u=ho(c,0,Re.h-4);return{kind:"geo",id:s,say:i,geo:Zt(n.geo,Mg,"rectangle"),x:d,y:u,w:Math.min(l,Re.w-d),h:Math.min(g,Re.h-u),color:r,fill:Zt(n.fill,Dg,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Pg(n.opacity),rot:Pr(n.rot)}}return null}var ti=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 Xh=500,Kh=e=>`
329
+ `));let g=oy({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}te();import wo from"chalk";import{execFile as wy}from"child_process";import{existsSync as Ur,writeFileSync as $y}from"fs";import{homedir as by}from"os";import{join as em,resolve as ky}from"path";import{promisify as vy}from"util";var Re={w:1e3,h:640},qr=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Gg=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Jg=["none","semi","solid","fill","pattern"],Fr=180,zg=48,sy=["s","m","l","xl"],iy=["draw","sans","serif","mono"];function Yg(){return[`You are an illustrator drawing on a tldraw canvas ${Re.w} wide and ${Re.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 ${Fr}. 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 ${zg} 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"}`,'Shapes and paths take an optional "rot": degrees clockwise, -90 to 90, applied after they are drawn (a tilted parasol, cocked sunglasses).','Move: {"id":"m1","say":"Nudge the boat left.","move":"boat","dx":-60,"dy":0,"rot":0,"scale":1} slides an EARLIER shape or path by dx,dy, turns it by rot degrees and resizes it by scale (0.3 to 3), animated. The viewer is watching you work, so show the craft: tilt anything that leans with rot, and after the main pieces are down use 3 to 6 moves to adjust the composition (slide pieces side by side, straighten or tilt, grow or shrink them), each placed right after the elements it adjusts.',"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: ${Gg.join(", ")}.`,`color is one of: ${qr.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 the subject readable: no prop may cover a face, eyes or the props that matter. Put tall props (a parasol, a tree, a sign) beside the subject or behind it, drawing them before the subject so it sits in front, and keep a clear gap around the head.","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 en(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function fo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var ho=(e,o,t)=>Math.min(t,Math.max(o,e)),Hg=e=>ho(fo(e)??1,.1,1),Lr=e=>ho(fo(e)??0,-90,90),ry=/^#[0-9a-f]{6}$/i;function ay(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))qr.includes(t)&&typeof n=="string"&&ry.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function cy(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,zg)){if(!Array.isArray(t))return null;let n=fo(t[0]),s=fo(t[1]);if(n===null||s===null)return null;o.push([ho(n,0,Re.w),ho(s,0,Re.h)])}return o.length>=2?o:null}function Vg(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=ay(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=en(n.color,qr,"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(typeof n.move=="string"){let l=n.move;if(!o.has(l)||l==="palette")return null;let g=ho(fo(n.dx)??0,-Re.w,Re.w),d=ho(fo(n.dy)??0,-Re.h,Re.h),u=ho(fo(n.scale)??1,.3,3),f=Lr(n.rot);return!g&&!d&&!f&&u===1?null:{kind:"move",id:s,say:i,target:l,dx:g,dy:d,rot:f,scale:u}}if("path"in n){let l=cy(n.path),g=en(n.fill,Jg,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Hg(n.opacity),rot:Lr(n.rot)}}let a=fo(n.x),c=fo(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:ho(a,0,Re.w-20),y:ho(c,0,Re.h-20),size:en(n.size,sy,"l"),color:r,font:en(n.font,iy,"draw")};if(typeof n.geo=="string"){let l=fo(n.w),g=fo(n.h);if(l===null||g===null||l<4||g<4)return null;let d=ho(a,0,Re.w-4),u=ho(c,0,Re.h-4);return{kind:"geo",id:s,say:i,geo:en(n.geo,Gg,"rectangle"),x:d,y:u,w:Math.min(l,Re.w-d),h:Math.min(g,Re.h-u),color:r,fill:en(n.fill,Jg,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Hg(n.opacity),rot:Lr(n.rot)}}return null}var ni=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 ly=500,dy=e=>`
332
332
  editor.zoomToBounds({ x: 0, y: 0, w: ${Re.w}, h: ${Re.h} }, { inset: ${e}, immediate: true })
333
333
  const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${Re.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) / ${Re.w} }`;function Fg(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 Wg(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 Qh(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 Bg(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) / ${Re.w} }`;function Xg(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 Kg(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 gy(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 Qg(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 Zh(e,o){if(e.kind==="palette")return Bg(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
343
+ return true`}function my(e,o){if(e.kind==="palette")return Qg(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(Xh/10)}))
345
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(ly/10)}))
346
346
  const ease = (t) => 1 - Math.pow(1 - t, 3)
347
347
  const tilt = async (id, deg) => {
348
348
  if (!deg) return
@@ -399,75 +399,80 @@ return id`:`${n}
399
399
  const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
400
400
  const aid = typeof arrow === 'string' ? arrow : arrow?.id
401
401
  if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
402
- return aid ?? null`}function ey(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[yo(s[0][0],s[0][1]),yo(i[0],i[1])]}if(e.kind==="geo")return[yo(e.x,e.y),yo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Wg(e);return[yo(s.x,s.y+s.h/2),yo(s.x+s.w,s.y+s.h/2)]}if(e.kind==="move"){let s=o.get(e.target),i=s.x+s.w/2,r=s.y+s.h/2;return[yo(i,r),yo(i+e.dx,r+e.dy)]}let t=o.get(e.from),n=o.get(e.to);return[yo(t.x+t.w/2,t.y+t.h/2),yo(n.x+n.w/2,n.y+n.h/2)]}var yo=(e,o)=>({x:e,y:o,w:0,h:0});function oy(e,o){let t=e.w*o.scale,n=e.h*o.scale;return{x:e.x+o.dx+(e.w-t)/2,y:e.y+o.dy+(e.h-n)/2,w:t,h:n}}async function Jg(e,o,t,n=()=>{}){let s=o.sleep??(v=>new Promise(x=>setTimeout(x,v))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Kh(60)),g=new Set,d=new Map,u=[],f=!1,p=0,y=null,w=null,b=null,k=()=>{b?.(),b=null},$=v=>{if(g.size>=Lr)return;let x=Ug(v,g);if(!x){v.trim()&&n({type:"skipped",line:v.slice(0,120)});return}g.add(x.id),y??=i()-c,u.push(x),n({type:"planned",n:g.size,el:x,atMs:i()-c}),k()},E=(async()=>{let v=new ti;try{for await(let x of o.model.reply(`Draw: ${e}`,t.signal))v.push(x).forEach($);v.flush().forEach($)}catch(x){w=x?.message??String(x)}finally{p=i()-c,f=!0,k()}})(),S=0;for(;!t.signal?.aborted;){let v=u.shift();if(!v){if(f)break;await new Promise(P=>{b=P});continue}if(v.kind==="arrow"&&!(d.has(v.from)&&d.has(v.to))){n({type:"error",error:`${v.id}: an end was not drawn`});continue}if(v.kind==="move"&&!d.has(v.target)){n({type:"error",error:`${v.id}: ${v.target} was not drawn`});continue}let x=i();if(v.kind==="palette"){v.say&&o.presence.say(v.say);try{await o.api.exec(t.docId,Bg(v))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:v,ms:i()-x});continue}let[R,I]=ey(v,d);v.say&&o.presence.say(v.say),o.presence.moveTo(Fg(l,R.x,R.y)),await s(250),o.presence.moveTo(Fg(l,I.x,I.y));try{await o.api.exec(t.docId,Zh(v,a))}catch(P){n({type:"error",error:`${v.id}: ${P?.message??P}`});continue}v.kind==="move"?d.set(v.target,oy(d.get(v.target),v)):d.set(v.id,v.kind==="geo"?v:v.kind==="text"?Wg(v):v.kind==="path"?Qh(v.pts):yo(0,0)),S++,n({type:"drawn",n:S,el:v,ms:i()-x});let C=(v.say?r:0)-(i()-x);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 ty}from"fs";import{homedir as ny}from"os";import{join as sy}from"path";var Vn=sy(ny(),"Library","Application Support","tldraw","server.json"),ni=class{constructor(o=Vn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=ty(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 dy=ly(iy),gy="claude-sonnet-5";function my(e){e.type==="planned"?console.log(wo.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${wo.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${wo.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(wo.yellow(` skipped: ${e.line}`)):console.log(wo.red(` error: ${e.error}`))}async function py(){if(!qr(Vn)){await dy("open",["-a","tldraw offline"]);for(let e=0;e<40&&!qr(Vn);e++)await new Promise(o=>setTimeout(o,500));if(!qr(Vn))throw new Error("tldraw offline did not start")}}async function Gg(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||gy,i=cy(o.out||Hg(ay(),"Documents")),r=Pt(n,t.agents[n]),a=Lt({system:qg(),model:s}),c=t.voice.pointer?new Is(r,Le,n):Cs,l=new ni;try{await py();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(b=>setTimeout(b,800)),console.log(wo.bold(`
402
+ return aid ?? null`}function py(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[yo(s[0][0],s[0][1]),yo(i[0],i[1])]}if(e.kind==="geo")return[yo(e.x,e.y),yo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Kg(e);return[yo(s.x,s.y+s.h/2),yo(s.x+s.w,s.y+s.h/2)]}if(e.kind==="move"){let s=o.get(e.target),i=s.x+s.w/2,r=s.y+s.h/2;return[yo(i,r),yo(i+e.dx,r+e.dy)]}let t=o.get(e.from),n=o.get(e.to);return[yo(t.x+t.w/2,t.y+t.h/2),yo(n.x+n.w/2,n.y+n.h/2)]}var yo=(e,o)=>({x:e,y:o,w:0,h:0});function uy(e,o){let t=e.w*o.scale,n=e.h*o.scale;return{x:e.x+o.dx+(e.w-t)/2,y:e.y+o.dy+(e.h-n)/2,w:t,h:n}}async function Zg(e,o,t,n=()=>{}){let s=o.sleep??(v=>new Promise(x=>setTimeout(x,v))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,dy(60)),g=new Set,d=new Map,u=[],f=!1,p=0,y=null,w=null,b=null,k=()=>{b?.(),b=null},$=v=>{if(g.size>=Fr)return;let x=Vg(v,g);if(!x){v.trim()&&n({type:"skipped",line:v.slice(0,120)});return}g.add(x.id),y??=i()-c,u.push(x),n({type:"planned",n:g.size,el:x,atMs:i()-c}),k()},E=(async()=>{let v=new ni;try{for await(let x of o.model.reply(`Draw: ${e}`,t.signal))v.push(x).forEach($);v.flush().forEach($)}catch(x){w=x?.message??String(x)}finally{p=i()-c,f=!0,k()}})(),S=0;for(;!t.signal?.aborted;){let v=u.shift();if(!v){if(f)break;await new Promise(P=>{b=P});continue}if(v.kind==="arrow"&&!(d.has(v.from)&&d.has(v.to))){n({type:"error",error:`${v.id}: an end was not drawn`});continue}if(v.kind==="move"&&!d.has(v.target)){n({type:"error",error:`${v.id}: ${v.target} was not drawn`});continue}let x=i();if(v.kind==="palette"){v.say&&o.presence.say(v.say);try{await o.api.exec(t.docId,Qg(v))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:v,ms:i()-x});continue}let[R,I]=py(v,d);v.say&&o.presence.say(v.say),o.presence.moveTo(Xg(l,R.x,R.y)),await s(250),o.presence.moveTo(Xg(l,I.x,I.y));try{await o.api.exec(t.docId,my(v,a))}catch(P){n({type:"error",error:`${v.id}: ${P?.message??P}`});continue}v.kind==="move"?d.set(v.target,uy(d.get(v.target),v)):d.set(v.id,v.kind==="geo"?v:v.kind==="text"?Kg(v):v.kind==="path"?gy(v.pts):yo(0,0)),S++,n({type:"drawn",n:S,el:v,ms:i()-x});let C=(v.say?r:0)-(i()-x);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 fy}from"fs";import{homedir as hy}from"os";import{join as yy}from"path";var Xn=yy(hy(),"Library","Application Support","tldraw","server.json"),si=class{constructor(o=Xn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=fy(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 xy=vy(wy),Sy="claude-sonnet-5";function Ey(e){e.type==="planned"?console.log(wo.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${wo.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${wo.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(wo.yellow(` skipped: ${e.line}`)):console.log(wo.red(` error: ${e.error}`))}async function Ay(){if(!Ur(Xn)){await xy("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Ur(Xn);e++)await new Promise(o=>setTimeout(o,500));if(!Ur(Xn))throw new Error("tldraw offline did not start")}}async function om(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||Sy,i=ky(o.out||em(by(),"Documents")),r=Mt(n,t.agents[n]),a=qt({system:Yg(),model:s}),c=t.voice.pointer?new Ns(r,Le,n):Is,l=new si;try{await Ay();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(b=>setTimeout(b,800)),console.log(wo.bold(`
403
403
  ${r.name} draws: ${e}`)+wo.dim(` (${s}, ${d.filePath})
404
- `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Jg(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},my);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"):Hg(i,`agentx-draw-${g}.png`);ry(y,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(wo.bold(`
404
+ `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Zg(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Ey);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"):em(i,`agentx-draw-${g}.png`);$y(y,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(wo.bold(`
405
405
  ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+wo.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(wo.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(wo.dim(` ${d.filePath}
406
406
  ${y}
407
- `))}finally{a.close(),c.close()}}var Fr=hy(fy),Vg=new uy().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, "${Wo}" 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 Gg(String(o.live),o):await _g(String(o.live),o),process.exit(0)}catch(g){console.log(se.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(se.bold(`
407
+ `))}finally{a.close(),c.close()}}var Br=Oy(jy),sm=new Ty().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, "${Wo}" 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 om(String(o.live),o):await Bg(String(o.live),o),process.exit(0)}catch(g){console.log(se.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(se.bold(`
408
408
  lessons
409
- `));for(let g of Dr)console.log(` ${se.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${se.dim(g.appHint)}
410
- `);return}let t=Dr.find(g=>g.id===e);t||(console.log(se.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),yy(Le)||(console.log(se.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:vy(o.voice,o.agent);console.log(se.bold(`
409
+ `));for(let g of Mr)console.log(` ${se.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${se.dim(g.appHint)}
410
+ `);return}let t=Mr.find(g=>g.id===e);t||(console.log(se.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Cy(Le)||(console.log(se.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Dy(o.voice,o.agent);console.log(se.bold(`
411
411
  ${t.title}`)),console.log(se.dim(` ${t.appHint}
412
- `));try{t.start&&(await Fr("/usr/bin/open",by(t.start)),await Zo(2e3),await si(t.start.ready))}catch(g){console.log(se.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=Yg(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(se.dim(` recording \u2192 ${i}`)),s=zg("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Zo(2e3));let r=o.hud===!1?null:zg(Le,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
413
- `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${se.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 si(d.before)}let u=o.speak===!1?Promise.resolve():Sy(d.say,n),f=d.find?await ky(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 Fr(Le,["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 Ur(["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(se.yellow(" \xB7 clicked, but the screen did not change")),await Zo(d.afterClickWaitMs??1500)}if(d.type){await si(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await Ur(["type","--text",d.type]);if(p)throw console.log(se.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 si(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Ur(["key","--name",d.key]);if(p)throw console.log(se.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 Zo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Zo(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 zn(d.verify,p?{settle:!0,screen:ko()}:{})}catch(w){y=null,console.log(se.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"?se.green("\u2713"):y.outcome==="refuted"?se.red("\u2717"):se.yellow("?");if(console.log(` ${w} ${se.dim(y.reason)}`),!y.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(se.red(`
414
- stopping: could not confirm \u2014 ${d.verify}`)),console.log(se.dim(` ${y.reason}`)),console.log(se.dim(` screenshot: ${y.sighting.shot.path}`)),await Zo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(se.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 Zo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Zo(2500);try{let{size:g}=wy(i);console.log(se.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(se.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(se.red(` lesson stopped before the end.
412
+ `));try{t.start&&(await Br("/usr/bin/open",Ry(t.start)),await Zo(2e3),await ii(t.start.ready))}catch(g){console.log(se.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=nm(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(se.dim(` recording \u2192 ${i}`)),s=tm("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Zo(2e3));let r=o.hud===!1?null:tm(Le,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
413
+ `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${se.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 ii(d.before)}let u=o.speak===!1?Promise.resolve():My(d.say,n),f=d.find?await _y(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 Br(Le,["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 Wr(["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(se.yellow(" \xB7 clicked, but the screen did not change")),await Zo(d.afterClickWaitMs??1500)}if(d.type){await ii(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await Wr(["type","--text",d.type]);if(p)throw console.log(se.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 ii(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Wr(["key","--name",d.key]);if(p)throw console.log(se.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 Zo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Zo(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 Yn(d.verify,p?{settle:!0,screen:vo()}:{})}catch(w){y=null,console.log(se.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"?se.green("\u2713"):y.outcome==="refuted"?se.red("\u2717"):se.yellow("?");if(console.log(` ${w} ${se.dim(y.reason)}`),!y.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(se.red(`
414
+ stopping: could not confirm \u2014 ${d.verify}`)),console.log(se.dim(` ${y.reason}`)),console.log(se.dim(` screenshot: ${y.sighting.shot.path}`)),await Zo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(se.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 Zo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Zo(2500);try{let{size:g}=Iy(i);console.log(se.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(se.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(se.red(` lesson stopped before the end.
415
415
  `)),process.exitCode=3;return}console.log(se.green(`
416
416
  done.
417
- `))});function by(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Yg($y(),"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 si(e){let o=await zn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Ur(e){try{let{stdout:o}=await Fr(Le,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 ky(e,o=[]){try{let t=await Ns({max:45});if(t.candidates.length<2)return null;let n=await bo(Jn,Xs({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Ks(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Qs(n.answers,t.candidates);return s.present<.5?null:Rn(t,s.id)}catch{return null}}function vy(e,o){if(e?.trim().toLowerCase()===Wo)return{provider:"system",elevenlabs:Nn(),system:null,fallback:!0};let t=e?Ts(e,In()):null;if(t)return{provider:"system",elevenlabs:Nn(),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(se.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Sl(vl(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Nn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(se.dim(` no agent voice (${String(n?.message??n).split(`
418
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Nn(),system:null,fallback:!0}}}var xy=new Mt;async function Sy(e,o){o&&await xy.say({voice:o,text:e})}var Zo=e=>new Promise(o=>setTimeout(o,e));te();import{Command as Xg}from"commander";import Ke from"chalk";import{createInterface as Kg}from"readline";var Ey=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function en(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Ey()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Ay(e){e.type==="line"?console.log(`${Ke.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ke.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ke.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ke.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ke.dim(" \xB7 hushed")):e.type==="error"?console.log(Ke.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ke.dim(` \xB7 ended (${e.reason})`))}function Qg(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 Ty(e,o,t){let n=T(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await en("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Il(()=>n,()=>d),i.usePool(await Cl(kl()))}let r=e.map(d=>s[d]?js(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 Rl({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new Mt,listener:n.voice.listener,model:(d,u)=>Lt({system:u})});l.on(Ay),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ke.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Kg({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(Ke.dim(` ${Qg(l.gaps)}`))}async function jy(e,o,t){let n=await en("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=Kg({input:process.stdin});s.on("line",a=>{a.trim()&&en("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void en("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await en("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ke.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(Ke.dim(` ${Qg(r)}`))}var Zg=new Xg().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?Ty:jy)([e,o],s,n),process.exit(0)}catch(i){console.error(Ke.red(` ${i?.message??i}`)),process.exit(1)}}),em=new Xg().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(Ke.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await en("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ke.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});te();import{Command as Oy}from"commander";import W from"chalk";import{existsSync as Cy,readFileSync as tm,writeFileSync as nm}from"fs";import{resolve as om}from"path";Jp();var Ao=new Oy().name("voice").description("list installed system voices and pick each agent's voice");function $t(e){let o=e?[e]:[om(process.cwd(),"agentx.json"),om(process.cwd(),".agentx/config.json")],t=o.find(n=>Cy(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Iy(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()===Wo,w=y?null:Ts(t,s,a??e?.voice?.locale),b=w?`system voice ${Vi(w)}`:"the OS default voice";if((w||y)&&g==="system")u(y?Wo:t),d.push(`${b}${f}`);else if(g==="elevenlabs"&&!w&&!y&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||y)u(y?Wo:t),d.push(`fallback ${b}${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}}Ao.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=In(),t;try{t=T(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?xl(t.agents,t.voice,o):new Map;if(t)for(let[a,c]of Object.entries(t.agents)){let l=i.get(a),g=Object.values(Xi(a,c.voice?.system,c.voice?.gender,t.voice,o));for(let d of new Set([l,...g]))d&&s.set(d.id,[...s.get(d.id)??[],a])}if(!o.length)console.log(W.yellow(`
417
+ `))});function Ry(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${nm(Ny(),"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 ii(e){let o=await Yn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Wr(e){try{let{stdout:o}=await Br(Le,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 _y(e,o=[]){try{let t=await Rs({max:45});if(t.candidates.length<2)return null;let n=await ko(Hn,Ks({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Qs(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Zs(n.answers,t.candidates);return s.present<.5?null:_n(t,s.id)}catch{return null}}function Dy(e,o){if(e?.trim().toLowerCase()===Wo)return{provider:"system",elevenlabs:Rn(),system:null,fallback:!0};let t=e?js(e,Nn()):null;if(t)return{provider:"system",elevenlabs:Rn(),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(se.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Il(Ol(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Rn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(se.dim(` no agent voice (${String(n?.message??n).split(`
418
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Rn(),system:null,fallback:!0}}}var Py=new Lt;async function My(e,o){o&&await Py.say({voice:o,text:e})}var Zo=e=>new Promise(o=>setTimeout(o,e));te();import{Command as im}from"commander";import Ke from"chalk";import{createInterface as rm}from"readline";var Ly=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function on(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Ly()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function qy(e){e.type==="line"?console.log(`${Ke.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ke.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ke.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ke.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ke.dim(" \xB7 hushed")):e.type==="error"?console.log(Ke.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ke.dim(` \xB7 ended (${e.reason})`))}function am(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 Fy(e,o,t){let n=T(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await on("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Ll(()=>n,()=>d),i.usePool(await Ml(jl()))}let r=e.map(d=>s[d]?Os(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 Fl({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new Lt,listener:n.voice.listener,model:(d,u)=>qt({system:u})});l.on(qy),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ke.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=rm({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(Ke.dim(` ${am(l.gaps)}`))}async function Uy(e,o,t){let n=await on("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=rm({input:process.stdin});s.on("line",a=>{a.trim()&&on("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void on("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await on("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ke.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(Ke.dim(` ${am(r)}`))}var cm=new im().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?Fy:Uy)([e,o],s,n),process.exit(0)}catch(i){console.error(Ke.red(` ${i?.message??i}`)),process.exit(1)}}),lm=new im().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(Ke.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await on("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ke.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});te();import{Command as Xy}from"commander";import L from"chalk";import{existsSync as um,readFileSync as Gr,writeFileSync as fm}from"fs";import{homedir as Ky}from"os";import{join as Qy,resolve as Hr}from"path";nu();var Wy=/\[(teach|door|presence)\] (.*)$/,By=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z) (.*)$/,Jy=/^([\w.-]+) \((teach|watch|act)\): (.*)$/,Hy=/^(\d+)\. ([a-z_]+)(?: "(.*)")?: (.*)$/,Gy=/^(.*) \(screen (\d+) ms, plan (\d+) ms\)$/,zy=/^ended \((.*)\)$/,Yy=/^([\w.-]+) seat=\S+ chose=(\S+) p=([\d.]+) → (\w+)/,Vy=/^"(.*)" → lesson( \(ended\))?$/,dm=(e,o)=>e&&o?Date.parse(o)-Date.parse(e):null;function gm(e){let o=[],t=null,n=null;for(let s of e.split(`
419
+ `)){let i=Wy.exec(s);if(!i)continue;let[,r,a]=i;if(r==="presence"){let p=Yy.exec(a);p&&["teach","watch","act"].includes(p[4])&&(n={agentId:p[1],chose:p[2],p:Number(p[3])});continue}if(r==="door"){if(!t)continue;if(a.startsWith("hush \u2192 lesson")){t.hushes++;continue}let p=Vy.exec(a);p&&t.words.push({text:p[1],ended:!!p[2],afterStep:t.steps.length});continue}let c=By.exec(a),l=c?c[1]:null,g=c?c[2]:a,d=Jy.exec(g);if(d){let[,p,y,w]=d,b=n&&n.agentId===p?{seat:!0,chose:n.chose,p:n.p}:{seat:!1};n=null,t={agentId:p,mode:y,goal:w,startedBy:b,startedAt:l,steps:[],firstStepMs:null,hushes:0,words:[],end:null,durationMs:null},o.push(t);continue}if(!t)continue;let u=Hy.exec(g);if(u){let p=Gy.exec(u[4]);t.steps.push({n:Number(u[1]),action:u[2],target:u[3]??null,say:p?p[1]:u[4],at:l,readMs:p?Number(p[2]):null,planMs:p?Number(p[3]):null}),t.steps.length===1&&(t.firstStepMs=dm(t.startedAt,l));continue}let f=zy.exec(g);f&&(t.end={reason:f[1],at:l},t.durationMs=dm(t.startedAt,l),t=null)}return o}var $t=e=>`${(e/1e3).toFixed(1)} s`;function Jr(e){let o=[],t=e.steps[0];o.push({point:'"Looking at \u2026" shows from the start until the first step',verdict:"by eye",note:t?`the first step came ${e.firstStepMs===null?"with no time on it":`after ${$t(e.firstStepMs)}`}`:"no step was logged"});let n=e.words.filter(a=>!a.ended),s="Words said mid-lesson pause it and reach the next step";if(!n.length)e.startedAt===null&&e.hushes&&e.end?.reason==="stopped by the listener"?o.push({point:s,verdict:"not ok",note:"a hush ended it: the daemon runs a build older than 0.94.0"}):e.end?.reason==="no words after the hush"?o.push({point:s,verdict:"not seen",note:"a hush came and nothing was said within a minute, so it ended"}):o.push({point:s,verdict:"not seen",note:e.hushes?"a hush came, but no words followed it":"nothing was said to the lesson"});else{let a=n.filter(l=>e.steps.length>l.afterStep),c=n.map(l=>`"${l.text}"`).join(", ");a.length===n.length?o.push({point:s,verdict:"ok",note:`${c}: the lesson went on, and a step followed each`}):o.push({point:s,verdict:e.end?"not ok":"not seen",note:`${c}: the lesson went on, but no step followed${e.end?` (ended: ${e.end.reason})`:" yet"}`})}let i=e.words.find(a=>a.ended);return i?o.push({point:"A spoken stop ends it",verdict:e.end?.reason==="stopped by the listener"?"ok":"not ok",note:`"${i.text}" ${e.end?`ended it (${e.end.reason})`:"was taken as a stop, but no end was logged"}`}):e.end?o.push({point:"A spoken stop ends it",verdict:"not seen",note:`ended another way: ${e.end.reason}`}):o.push({point:"A spoken stop ends it",verdict:"not seen",note:"still running when the log was read, or the daemon stopped"}),e.startedAt!==null&&e.steps.every(a=>a.at!==null&&a.planMs!==null)?t?o.push({point:"[teach] lines carry a time and the screen-read and plan durations",verdict:"ok",note:`step 1: screen ${$t(t.readMs)}, plan ${$t(t.planMs)}`}):o.push({point:"[teach] lines carry a time and the screen-read and plan durations",verdict:"not seen",note:"no step was logged"}):o.push({point:"[teach] lines carry a time and the screen-read and plan durations",verdict:"not ok",note:"no times on the lines: the daemon runs a build older than 0.94.0"}),e.firstStepMs===null?o.push({point:`First step under ${$t(1e4)} on an idle Mac`,verdict:"not seen",note:t?"no time on the start or the step line":"no step was logged"}):o.push({point:`First step under ${$t(1e4)} on an idle Mac`,verdict:e.firstStepMs<1e4?"ok":"not ok",note:`${$t(e.firstStepMs)} from the start to step 1${e.firstStepMs>=1e4?"; a busy Mac or a slow plan model":""}`}),o}function mm(e,o=(t,n)=>n){let t=[],n=e.startedAt?e.startedAt.replace(/\.\d+Z$/,"Z"):"no time";t.push(` ${n} ${e.agentId} (${e.mode}): "${e.goal}"`),t.push(` started by ${e.startedBy.seat?`a voice turn: the presence seat chose ${e.startedBy.chose} (p=${e.startedBy.p.toFixed(2)})`:"the terminal or the API"}`);let s=e.end?`ended ${e.durationMs===null?"":`after ${$t(e.durationMs)} `}(${e.end.reason})`:"no end logged";t.push(` ${e.steps.length} step${e.steps.length===1?"":"s"}, ${e.hushes} hush${e.hushes===1?"":"es"}, ${s}`);for(let i of e.steps){let r=i.planMs===null?"":` (screen ${i.readMs} ms, plan ${i.planMs} ms)`;t.push(` ${i.n}. ${i.action}${i.target?` "${i.target}"`:""}: ${i.say}${r}`)}for(let i of e.words)t.push(` heard "${i.text}" \u2192 ${i.ended?"the lesson ended":"the lesson's next step"}`);for(let i of Jr(e))t.push(` ${o(i.verdict,i.verdict.padEnd(8))} ${i.point}: ${i.note}`);return t.join(`
420
+ `)}var $o=new Xy().name("voice").description("list installed system voices and pick each agent's voice");function bt(e){let o=e?[e]:[Hr(process.cwd(),"agentx.json"),Hr(process.cwd(),".agentx/config.json")],t=o.find(n=>um(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Zy(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()===Wo,w=y?null:js(t,s,a??e?.voice?.locale),b=w?`system voice ${Xi(w)}`:"the OS default voice";if((w||y)&&g==="system")u(y?Wo:t),d.push(`${b}${f}`);else if(g==="elevenlabs"&&!w&&!y&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||y)u(y?Wo:t),d.push(`fallback ${b}${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}}$o.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=Nn(),t;try{t=T(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(Ki(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(L.yellow(`
419
421
  No system voices found (system voices need macOS).
420
- `));else{let a=e.all?Yi(o,""):Yi(o,n);console.log(W.bold(`
422
+ `));else{let a=e.all?Vi(o,""):Vi(o,n);console.log(L.bold(`
421
423
  System voices${e.all?"":` (${n})`}, best first
422
- `));for(let c of a){let l=c.siri?W.magenta("siri"):c.quality==="standard"?W.dim("standard"):W.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)} ${W.dim((c.gender??"").padEnd(7))} ${g?W.cyan(g):""}`)}o.some(c=>c.quality!=="standard")||(console.log(W.dim(`
423
- More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(W.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}let r=t?Al(t,o):[];if(r.length){console.log(W.bold.yellow(`
424
+ `));for(let c of a){let l=c.siri?L.magenta("siri"):c.quality==="standard"?L.dim("standard"):L.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)} ${L.dim((c.gender??"").padEnd(7))} ${g?L.cyan(g):""}`)}o.some(c=>c.quality!=="standard")||(console.log(L.dim(`
425
+ More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(L.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}let r=t?Rl(t,o):[];if(r.length){console.log(L.bold.yellow(`
424
426
  Not installed
425
- `));for(let a of r)console.log(` ${Ki(a.voice).padEnd(24)} ${W.cyan(a.agents.join(", "))}`);console.log(W.dim(`
426
- Reinstall in ${El}.`)),console.log(W.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(t){console.log(W.bold(`
427
+ `));for(let a of r)console.log(` ${Qi(a.voice).padEnd(24)} ${L.cyan(a.agents.join(", "))}`);console.log(L.dim(`
428
+ Reinstall in ${Nl}.`)),console.log(L.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(t){console.log(L.bold(`
427
429
  Agents
428
- `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=y=>y?Vi(y):W.dim("system default"),d=Object.entries(Xi(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,y])=>(y?.id??null)!==(i.get(a)?.id??null)).map(([y,w])=>`${W.dim(`${y}:`)} ${g(w)}`).join(W.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??W.dim("(default voice)")}`:`system ${g(i.get(a))}${d?W.dim(" \xB7 ")+d:""}`,f=r.filter(y=>y.agents.includes(a)).map(y=>Ki(y.voice)),p=f.length?W.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?W.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});Ao.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Wo}" 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=$t(t.config),{raw:s,summary:i}=Iy(JSON.parse(tm(n,"utf8")),e,o,t,In());nm(n,JSON.stringify(s,null,2)+`
429
- `),console.log(W.green(` ${e}: ${i}`)),console.log(W.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(W.red(` ${n.message}`)),process.exit(1)}});function on(e,o){let t=jl(o,T(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
430
- `));let n=JSON.parse(tm(e,"utf8"));Ol(n,o),nm(e,JSON.stringify(n,null,2)+`
431
- `)}Ao.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${Ra.join(", ")}; "default" follows the agent's colour, or voice.palette when it has none)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=$t(t.config);if(e&&o){let i=o==="default"?null:o;on(n,{agents:{[e]:{palette:i}}}),console.log(W.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(W.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(W.bold(`
430
+ `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=y=>y?Xi(y):L.dim("system default"),d=Object.entries(Ki(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,y])=>(y?.id??null)!==(i.get(a)?.id??null)).map(([y,w])=>`${L.dim(`${y}:`)} ${g(w)}`).join(L.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??L.dim("(default voice)")}`:`system ${g(i.get(a))}${d?L.dim(" \xB7 ")+d:""}`,f=r.filter(y=>y.agents.includes(a)).map(y=>Qi(y.voice)),p=f.length?L.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?L.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});$o.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Wo}" 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=bt(t.config),{raw:s,summary:i}=Zy(JSON.parse(Gr(n,"utf8")),e,o,t,Nn());fm(n,JSON.stringify(s,null,2)+`
431
+ `),console.log(L.green(` ${e}: ${i}`)),console.log(L.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(L.red(` ${n.message}`)),process.exit(1)}});function tn(e,o){let t=Dl(o,T(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
432
+ `));let n=JSON.parse(Gr(e,"utf8"));Pl(n,o),fm(e,JSON.stringify(n,null,2)+`
433
+ `)}$o.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${qa.join(", ")}; "default" follows the agent's colour, or voice.palette when it has none)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=bt(t.config);if(e&&o){let i=o==="default"?null:o;tn(n,{agents:{[e]:{palette:i}}}),console.log(L.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(L.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(L.bold(`
432
434
  Orb palettes
433
- `));for(let i of Ca)console.log(` ${i.id.padEnd(10)} ${W.dim(i.colors.join(" "))}`);console.log(W.bold(`
435
+ `));for(let i of Pa)console.log(` ${i.id.padEnd(10)} ${L.dim(i.colors.join(" "))}`);console.log(L.bold(`
434
436
  Agents
435
- `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Pt(i,r).color,c=_a(r.presence,s.voice.palette);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${W.dim(c.set?"chosen":r.presence?.color?`nearest its colour ${a}`:"the default, voice.palette")}`)}console.log()}catch(n){console.log(W.red(` ${n.message}`)),process.exit(1)}});Ao.command("look [look]").description(`what shows the assistant's state in AgentX Voice: ${Ia.join(" or ")}`).option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=$t(o.config);e!==void 0&&on(t,{general:{look:e}});let n=T(t).voice.look;console.log(` Shown as: ${n==="character"?"the character, above the bottom edge of the screen":"the orb, in the pill"}`),e!==void 0&&console.log(W.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(W.red(` ${t.message}`)),process.exit(1)}});Ao.command("start [form]").description("how the pill is when AgentX Voice starts: full, or reduced to its orb").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=$t(o.config);if(e!==void 0&&e!=="full"&&e!=="reduced")throw new Error("The pill starts full or reduced");e!==void 0&&on(t,{general:{startReduced:e==="reduced"}});let n=T(t).voice;console.log(` Starts as: ${n.startReduced?"the orb alone, reduced":"the full pill"}`),n.startReduced&&n.look==="character"&&console.log(W.dim(" No effect while the character is shown: the pill has no orb to reduce to.")),e!==void 0&&console.log(W.dim(" AgentX Voice picks this up the next time it starts."))}catch(t){console.log(W.red(` ${t.message}`)),process.exit(1)}});Ao.command("animations [often]").description("how often the character plays a small animation by itself when idle: off, rarely, sometimes or often").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=$t(o.config);if(e!==void 0&&!Na.includes(e))throw new Error("Animations are off, rarely, sometimes or often");e!==void 0&&on(t,{general:{animations:e}});let n=T(t).voice;console.log(` When idle: ${n.animations==="off"?"the character plays no animation by itself":`the character plays a small animation ${n.animations}`}`),n.animations!=="off"&&n.look!=="character"&&console.log(W.dim(" No effect while the orb is shown.")),e!==void 0&&console.log(W.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(W.red(` ${t.message}`)),process.exit(1)}});Ao.command("stroll [state]").description("whether the character takes a slow stroll when it has nothing to do: on or off").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=$t(o.config);if(e!==void 0&&e!=="on"&&e!=="off")throw new Error("The stroll is on or off");e!==void 0&&on(t,{general:{stroll:e==="on"}});let n=T(t).voice;console.log(` When idle: ${n.stroll?"the character takes a slow stroll now and then":"the character stays where it rests"}`),n.stroll&&n.look!=="character"&&console.log(W.dim(" No effect while the orb is shown.")),e!==void 0&&console.log(W.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(W.red(` ${t.message}`)),process.exit(1)}});Ao.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, ${Qi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Qi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=$t(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&&on(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(W.dim(" AgentX Voice picks this up within a few seconds."))}catch(o){console.log(W.red(` ${o.message}`)),process.exit(1)}});import{Command as Ny}from"commander";import N from"chalk";var et=new Ny().name("attach").description("wear an agentx agent identity in this Claude Code session"),ii=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${ct()}`;function ri(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ai(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 ci(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 im(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function Ry(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)} ${im(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function _y(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 Dy(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)}`)}et.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ui.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ii).action(async(e,o)=>{let t=ri(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)),ec(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Ui.join(", ")}`)),process.exit(1)),Pn()||(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 ai(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)} (${im(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: ${ci(n)}`)),process.exit(1)}});function sm(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function Py(e){let o=sm(e.kinds),t=sm(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}et.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",ii).action(async e=>{let o=ri(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)),Pn()||(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 ai(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: ${ci(t)}`)),process.exit(1)}});et.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",ii).action(async e=>{let o=ri(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ai(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: ${ci(t)}`)),process.exit(1)}});et.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ii).option("--json","raw JSON output").action(async e=>{let o=ri();try{let n=(await ai(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Pn(),sessions:n},null,2));return}console.log(),console.log(Pn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(Dn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=_y(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)Ry(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)Dy(a,a.sessionId===o)}r>0&&console.log(N.gray(`
436
- ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(N.red(`Could not read attach state: ${ci(t)}`)),process.exit(1)}});et.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||ct()),t=yd(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
437
+ `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Mt(i,r).color,c=Fa(r.presence,s.voice.palette);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${L.dim(c.set?"chosen":r.presence?.color?`nearest its colour ${a}`:"the default, voice.palette")}`)}console.log()}catch(n){console.log(L.red(` ${n.message}`)),process.exit(1)}});$o.command("look [look]").description(`what shows the assistant's state in AgentX Voice: ${Ma.join(" or ")}`).option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=bt(o.config);e!==void 0&&tn(t,{general:{look:e}});let n=T(t).voice.look;console.log(` Shown as: ${n==="character"?"the character, above the bottom edge of the screen":"the orb, in the pill"}`),e!==void 0&&console.log(L.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(L.red(` ${t.message}`)),process.exit(1)}});$o.command("start [form]").description("how the pill is when AgentX Voice starts: full, or reduced to its orb (the character alone, with the character)").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=bt(o.config);if(e!==void 0&&e!=="full"&&e!=="reduced")throw new Error("The pill starts full or reduced");e!==void 0&&tn(t,{general:{startReduced:e==="reduced"}});let n=T(t).voice,s=n.look==="character"?"the character alone, without its speech bubble":"the orb alone, reduced";console.log(` Starts as: ${n.startReduced?s:"the full pill"}`),e!==void 0&&console.log(L.dim(" AgentX Voice picks this up the next time it starts."))}catch(t){console.log(L.red(` ${t.message}`)),process.exit(1)}});$o.command("animations [often]").description("how often the character plays a small animation by itself when idle: off, rarely, sometimes or often").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=bt(o.config);if(e!==void 0&&!La.includes(e))throw new Error("Animations are off, rarely, sometimes or often");e!==void 0&&tn(t,{general:{animations:e}});let n=T(t).voice;console.log(` When idle: ${n.animations==="off"?"the character plays no animation by itself":`the character plays a small animation ${n.animations}`}`),n.animations!=="off"&&n.look!=="character"&&console.log(L.dim(" No effect while the orb is shown.")),e!==void 0&&console.log(L.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(L.red(` ${t.message}`)),process.exit(1)}});$o.command("stroll [state]").description("whether the character takes a slow stroll when it has nothing to do: on or off").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=bt(o.config);if(e!==void 0&&e!=="on"&&e!=="off")throw new Error("The stroll is on or off");e!==void 0&&tn(t,{general:{stroll:e==="on"}});let n=T(t).voice;console.log(` When idle: ${n.stroll?"the character takes a slow stroll now and then":"the character stays where it rests"}`),n.stroll&&n.look!=="character"&&console.log(L.dim(" No effect while the orb is shown.")),e!==void 0&&console.log(L.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(L.red(` ${t.message}`)),process.exit(1)}});function pm(e=Ky()){return[Qy(e,".agentx","logs","daemon-stderr.log"),"/tmp/agentx-daemon.log"]}$o.command("lessons").description("what the last live lessons did, read from the daemon log and graded against the hands-free check").option("--log <path>","the daemon log to read, or - for standard input (default: the first of ~/.agentx/logs/daemon-stderr.log and /tmp/agentx-daemon.log that exists)").option("-n, --last <n>","how many lessons to show, oldest first","3").option("--json","print the lessons and their checks as JSON").action(e=>{try{let o=e.log==="-"?0:e.log?Hr(e.log):pm().find(i=>um(i));if(o===void 0)throw new Error(`No daemon log found. Searched: ${pm().join(", ")}. Give one with --log <path>.`);let t=Math.max(1,Number(e.last)||3),n=gm(Gr(o,"utf8")).slice(-t);if(e.json){console.log(JSON.stringify(n.map(i=>({...i,checks:Jr(i)})),null,2));return}if(!n.length){console.log(L.yellow(` No lesson in ${o===0?"the input":o}.`)),console.log(L.dim(' A lesson writes [teach] lines there as it runs. Start one by voice ("show me how\u2026") or with agentx teach --live.'));return}let s=(i,r)=>i==="ok"?L.green(r):i==="not ok"?L.red(r):i==="by eye"?L.yellow(r):L.dim(r);console.log(L.bold(`
438
+ Last ${n.length===1?"lesson":`${n.length} lessons`} in ${o===0?"the input":o}
439
+ `));for(let i of n)console.log(mm(i,s)+`
440
+ `);console.log(L.dim(" ok: the log shows it. not ok: the log shows the opposite. not seen: the lesson did not reach that point. by eye: only the screen can tell.")),console.log()}catch(o){console.log(L.red(` ${o.message}`)),process.exit(1)}});$o.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, ${Zi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Zi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=bt(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&&tn(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(L.dim(" AgentX Voice picks this up within a few seconds."))}catch(o){console.log(L.red(` ${o.message}`)),process.exit(1)}});import{Command as ew}from"commander";import N from"chalk";var et=new ew().name("attach").description("wear an agentx agent identity in this Claude Code session"),ri=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${ct()}`;function ai(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ci(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 li(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 ym(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function ow(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)} ${ym(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function tw(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 nw(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)}`)}et.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ui.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ri).action(async(e,o)=>{let t=ai(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)),ac(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Ui.join(", ")}`)),process.exit(1)),Mn()||(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 ci(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)} (${ym(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: ${li(n)}`)),process.exit(1)}});function hm(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function sw(e){let o=hm(e.kinds),t=hm(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}et.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",ri).action(async e=>{let o=ai(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)),Mn()||(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 ci(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:sw(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: ${li(t)}`)),process.exit(1)}});et.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",ri).action(async e=>{let o=ai(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ci(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: ${li(t)}`)),process.exit(1)}});et.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ri).option("--json","raw JSON output").action(async e=>{let o=ai();try{let n=(await ci(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Mn(),sessions:n},null,2));return}console.log(),console.log(Mn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(Pn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=tw(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)ow(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)nw(a,a.sessionId===o)}r>0&&console.log(N.gray(`
441
+ ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(N.red(`Could not read attach state: ${li(t)}`)),process.exit(1)}});et.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||ct()),t=Ad(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
437
442
  settings \u2014 without this an attached production identity would be less
438
- 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)}});et.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=wd({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)}});te();import{Command as My}from"commander";import be from"chalk";var li=new My().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function am(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 cm(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function rm(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 Ly(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}li.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}=am(e),n;try{n=await fetch(`${o}/api/processes`,{headers:cm(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=Ly(r.state)(r.state.padEnd(9)),c=rm(r.spawnedAt),l=r.lastTurnAt?rm(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}`)}});li.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}=am(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:cm(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 qy}from"commander";import Fe from"chalk";import{existsSync as Wr,rmSync as Uy}from"fs";import{resolve as Br}from"path";var tn=new qy().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");tn.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(Fe.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await sc(e,o,{verbose:n}),r=Date.now()-s;console.log(Fe.green(` \u2713 indexed ${i.docs} doc(s) for ${Fe.bold(e)} in ${r}ms`)),console.log(Fe.dim(` \u2192 ${i.path}`))});tn.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Br(e.cwd,".agentx","rag");if(!Wr(o)){console.log(Fe.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Wr(Br(o,s,"index.json")));if(n.length===0){console.log(Fe.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Fi(s);console.log(` ${Fe.bold(s)} ${i.docs} doc(s) ${Fe.dim(i.path)}`)}});tn.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=ic(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Fi(e);i.exists?console.log(Fe.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Fe.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Fe.bold(i.title)} ${Fe.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Fe.dim(i.path)}`),console.log(` ${Fe.dim(i.snippet.slice(0,200))}`)});tn.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Br(process.cwd(),".agentx","rag",e);if(!Wr(o)){console.log(Fe.dim(` no index for ${e} \u2014 nothing to clear`));return}Uy(o,{recursive:!0,force:!0}),console.log(Fe.green(` \u2713 cleared index for ${e}`))});te();import{Command as Fy}from"commander";import ee from"chalk";import nn from"prompts";var bt=new Fy().name("backlog").description("manage the local backlog used by business workSource=backlog");function Xn(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 Ml(n)}}function Wy(e){return e?ee.cyan(`${e.type}:${e.project}#${e.iid}`):ee.dim("manual")}function By(e){return{todo:ee.gray("todo"),doing:ee.yellow("doing"),blocked:ee.red("blocked"),done:ee.green("done")}[e]}bt.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}=Xn(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(ee.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?ee.magenta(`@${n.assignee}`):ee.dim("unassigned");console.log(` ${By(n.status).padEnd(7)} ${Wy(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(ee.dim(` ${n.source.url}`))}console.log(),console.log(ee.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});bt.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=Xn(t.config);n.store.findById(e)||(console.error(ee.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(ee.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Ll([o],i.source,n.config),a=await or(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(ee.dim(" sync:"),...c));console.log(a.ok?ee.dim(` synced -> ${a.url??i.source.type}`):ee.yellow(` sync failed: ${a.error}`))}});bt.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=Xn(o.config);t.store.findById(e)||(console.error(ee.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(ee.green(` done: ${s.title}`)),s.source){let i=await or(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(ee.dim(" sync:"),...r));console.log(i.ok?ee.dim(` synced -> ${i.url??s.source.type}`):ee.yellow(` sync failed: ${i.error}`))}});bt.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}=Xn(o.config);t.remove(e)||(console.error(ee.red(` item ${e} not found`)),process.exit(1)),console.log(ee.green(` removed ${e}`))});bt.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=Xn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(ee.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 nn({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(ee.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(ee.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Hy(o.config):Gy(o.config);w.length?(i=(await nn({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(k=>({title:k,value:k})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await nn({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await nn({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await nn({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(ee.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await zy(o.config,i,a):await Yy(o.config,i,a);if(!c.length){console.log(ee.yellow(" no open issues matched"));return}console.log(ee.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 b=er({type:s,project:l,iid:w.iid,url:w.url}),k=g.has(b),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${k?ee.dim(" (already imported)"):""}`,value:w,disabled:k}}),f=(await nn({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(ee.dim(" nothing selected"));return}let p=f.map(w=>{let b={type:s,host:s==="gitlab"?Jy(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:er(b),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:b,importedAt:new Date().toISOString()}}),y=o.store.addMany(p);console.log(ee.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let w of y)console.log(ee.dim(` ${w.id} \u2014 ${w.title}`))});function Jy(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Hy(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 Gy(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 zy(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 Yy(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(lm)}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(lm):[]}function lm(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 Vy}from"commander";import B from"chalk";import{existsSync as Xy,readFileSync as Ky}from"fs";import{resolve as Qy}from"path";import Zy from"prompts";te();function dm(e){let o=e||Qy(process.cwd(),"agentx.json");return Xy(o)||(console.log(B.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Ky(o,"utf-8"))}async function ew(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(B.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Zy([{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(B.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var No=new Vy().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');No.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: ${Ji})`,Ji).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){No.help();return}o.agent||(console.log(B.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(B.red(' --do "<prompt>" is required')),process.exit(1));let t=Bi(e);t||(console.log(B.red(` Couldn't parse: "${e}"`)),console.log(B.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(B.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(B.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=dm(o.config),s=Ma(n);n.agents?.[o.agent]||(console.log(B.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(B.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await ew(o.notify,s),r=o.id||hc(t.matched,o.agent),a=wc({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:yc(o.onError),enabled:!o.disabled}),c=a.onError,l=await re(d=>Ie(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(B.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(B.green(` \u2713 ${g} cron ${B.cyan(r)}`)),console.log(B.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(B.dim(` Agent: ${o.agent}`)),i&&console.log(B.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(B.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(B.dim(" Daemon hot-reloaded."))});No.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=dm(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(B.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?B.yellow("\u25D0"):i.enabled?B.green("\u25CF"):B.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${B.cyan(s.padEnd(32))} ${B.dim(i.schedule.padEnd(14))} ${B.dim("\u2192")} ${i.agent}`),console.log(B.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(B.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(B.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=bc($c(i.schedule,c),c);console.log(B.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(B.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])No.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await xc(t,o);n.success||(console.log(B.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(B.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(B.dim(" Daemon hot-reloaded."))});No.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await re(t=>{if(!Dt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);dc(t,`crons.${e}`)});o.success||(console.log(B.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(B.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(B.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",kc,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",vc,"reject an agent's pending create/delete request (drops the request)"]])No.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(B.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(B.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(B.dim(" Daemon hot-reloaded."))});No.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Bi(o);t||(console.log(B.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(B.green(` "${o}"`)),console.log(B.dim(` \u2192 ${t.cron}`)),console.log(B.dim(` \u2192 ${t.human}`))});import{Command as ow}from"commander";import ke from"chalk";import Ro from"chalk";function gm(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 mm=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function pm(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(Ro.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?gm():n?el(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(Ro.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={...Ut().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await sl(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(Ro.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(Ro.dim(` not answered${r.why?` (${r.why})`:""}; the card is still waiting`));return}let a=await As({root:process.cwd()},`card:${s.id}`,r.action,{by:"operator (popup)",...r.action==="yes"?{choice:r.choice,text:r.text}:{}});if(!a.ok){console.error(Ro.red(` ${a.error}`)),process.exitCode=1;return}console.log(Ro.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(`${mm()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(Ro.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(Ro.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(Ro.red(` couldn't reach the daemon at ${mm()}: ${n?.message??n}`)),process.exitCode=1}})}var _o=new ow("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),tw={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function um(){return{root:process.cwd()}}function Jr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function nw(e){console.log(` ${ke.cyan(e.key)} ${ke.dim(`[${tw[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ke.dim(` (later: until ${Jr(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 ${Jr(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}`:""}`))}_o.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=nl(um(),{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)nw(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 Hr(e,o,t){let n=Ut(),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 As(um(),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}`))}_o.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)=>Hr(e,"yes",o));_o.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)=>Hr(e,"no",o));_o.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)=>Hr(e,"later",o));_o.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: ${Zc.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=Ut(),t=ol(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 ${Jr(t.card.expires)}, then: ${t.card.if_silent}`))});pm(_o);_o.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=Gl(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 zl(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=Ut(),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 sw}from"commander";import z from"chalk";te();ps();Gp();var oo=new sw("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),iw=["owner","member","guest"];function di(){let e=90;try{e=T().members.logRetentionDays}catch{}return new mc(process.cwd(),Date.now,e)}var fm=(e,o=[])=>[...o,e];function wm(e){let o=[];try{o=Object.keys(T().agents)}catch{return}let t=e.filter(n=>!o.includes(n));t.length&&(console.log(z.yellow(` ! not an agent on this machine: ${t.join(", ")}. Agents here: ${o.join(", ")||"none"}.`)),console.log(z.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var $m="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.",rw="An owner is never limited. Change the role first if that is what you want.",Gr=["tools","skills"];function aw(e){let o=e.toLowerCase().replace(/^(tool|skill)$/,"$1s");return Gr.includes(o)?o:null}async function sn(e){let o="",t=await re(n=>{n.people=Array.isArray(n.people)?n.people:[],o=e(n.people)});t.success||(console.error(z.red(`\u2717 ${(t.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(z.green(`\u2713 ${o}`)),t.reloaded&&console.log(z.dim(" daemon hot-reloaded"))}function Kn(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 bm(e,o){let t=Mi(e),n=Mi(o);return!!t&&!!n&&t.channel===n.channel&&t.value===n.value}function km(e){let o=Gr.filter(t=>e.deny?.[t]?.length).map(t=>` \xB7 no ${t}: ${e.deny[t].join(", ")}`).join("");console.log(` ${z.bold(e.id)} ${e.name} ${z.dim(`\xB7 ${e.role}`)}${e.agents?.length?z.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}${z.dim(o)}`),console.log(z.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}oo.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(z.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${Pi}"; senders on other channels are unknown.`)),console.log(z.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let t of o)km(t);console.log()});oo.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${iw.join(" | ")}`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",fm,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",fm,[]).action(async(e,o)=>{await sn(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($m);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(", ")}`:""}`}),wm(o.agent)});oo.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 sn(n=>{let s=Kn(n,e);if(!t&&s.role==="owner")throw new Error($m);return s.agents=t?[]:[...new Set(o)],t?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),t||wm(o)});oo.command("deny <id> <level> <names...>").description(`stop a person's turns using these tools or skills. Level: tools | skills. Names match without case; * is a wildcard. "none" lifts the limit`).action(async(e,o,t)=>{let n=aw(o);n||(console.error(z.red(`\u2717 level must be one of: ${Gr.join(", ")}`)),process.exit(1));let s=t.length===1&&t[0].toLowerCase()==="none";await sn(i=>{let r=Kn(i,e);if(!s&&r.role==="owner")throw new Error(rw);return r.deny={...r.deny??{},[n]:s?[]:[...new Set(t)]},s?`${e} may use every ${n.slice(0,-1)}`:`${e} may not use these ${n}: ${r.deny[n].join(", ")}`})});oo.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,o)=>{await sn(t=>{let n=Kn(t,e);return n.identities.some(s=>bm(s,o))?`${e} already has ${o}`:(n.identities.push(o),`${o} is now ${e}`)})});oo.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,o)=>{await sn(t=>{let n=Kn(t,e),s=n.identities.length;if(n.identities=n.identities.filter(i=>!bm(i,o)),n.identities.length===s)throw new Error(`"${e}" has no identity ${o}.`);return`${o} is no longer ${e}`})});oo.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 sn(t=>(Kn(t,e),t.splice(t.findIndex(n=>n?.id===e),1),`removed ${e}`));let o=Zl({tokens:new no,members:di()},e);o.length&&console.log(z.green(`\u2713 ended ${o.length} machine(s) of ${e}: ${o.map(t=>t.name).join(", ")}`)),console.log(z.dim(" If you shared this computer with them on the private network, remove that share too."))});oo.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=Un(),n=fr(hr(),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(`
439
- `));let s=(o.url?String(o.url):ur()).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=Kl({tokens:new no,codes:new Ss,members:di(),people:()=>i},e);if(!r.ok)throw new Error(r.error);console.log(),console.log(` Invite for ${z.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(z.dim(" Tailscale admin console \u2192 Machines \u2192 this computer \u2192 Share \u2192 send them the link.")),console.log(z.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(` ${z.cyan(`${s}/member`)}`),console.log(` ${z.bold(xs(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(z.dim(` Their key stops after ${Xl} days; invite again then. Machine id: ${r.tokenId}`)),console.log()}catch(t){console.log(z.red(` ${t.message}`)),process.exit(1)}});oo.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=di().devices(e);if(o.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(z.dim(`
443
+ 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)}});et.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=Td({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)}});te();import{Command as iw}from"commander";import be from"chalk";var di=new iw().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function $m(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 bm(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function wm(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 rw(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}di.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}=$m(e),n;try{n=await fetch(`${o}/api/processes`,{headers:bm(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=rw(r.state)(r.state.padEnd(9)),c=wm(r.spawnedAt),l=r.lastTurnAt?wm(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}`)}});di.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}=$m(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:bm(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 aw}from"commander";import Ue from"chalk";import{existsSync as zr,rmSync as cw}from"fs";import{resolve as Yr}from"path";var nn=new aw().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");nn.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 gc(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}`))});nn.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Yr(e.cwd,".agentx","rag");if(!zr(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=>zr(Yr(o,s,"index.json")));if(n.length===0){console.log(Ue.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Wi(s);console.log(` ${Ue.bold(s)} ${i.docs} doc(s) ${Ue.dim(i.path)}`)}});nn.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=mc(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Wi(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))}`)});nn.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Yr(process.cwd(),".agentx","rag",e);if(!zr(o)){console.log(Ue.dim(` no index for ${e} \u2014 nothing to clear`));return}cw(o,{recursive:!0,force:!0}),console.log(Ue.green(` \u2713 cleared index for ${e}`))});te();import{Command as lw}from"commander";import ee from"chalk";import sn from"prompts";var kt=new lw().name("backlog").description("manage the local backlog used by business workSource=backlog");function Kn(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 Jl(n)}}function dw(e){return e?ee.cyan(`${e.type}:${e.project}#${e.iid}`):ee.dim("manual")}function gw(e){return{todo:ee.gray("todo"),doing:ee.yellow("doing"),blocked:ee.red("blocked"),done:ee.green("done")}[e]}kt.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}=Kn(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(ee.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?ee.magenta(`@${n.assignee}`):ee.dim("unassigned");console.log(` ${gw(n.status).padEnd(7)} ${dw(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(ee.dim(` ${n.source.url}`))}console.log(),console.log(ee.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});kt.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=Kn(t.config);n.store.findById(e)||(console.error(ee.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(ee.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Hl([o],i.source,n.config),a=await tr(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(ee.dim(" sync:"),...c));console.log(a.ok?ee.dim(` synced -> ${a.url??i.source.type}`):ee.yellow(` sync failed: ${a.error}`))}});kt.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=Kn(o.config);t.store.findById(e)||(console.error(ee.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(ee.green(` done: ${s.title}`)),s.source){let i=await tr(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(ee.dim(" sync:"),...r));console.log(i.ok?ee.dim(` synced -> ${i.url??s.source.type}`):ee.yellow(` sync failed: ${i.error}`))}});kt.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}=Kn(o.config);t.remove(e)||(console.error(ee.red(` item ${e} not found`)),process.exit(1)),console.log(ee.green(` removed ${e}`))});kt.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=Kn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(ee.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 sn({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(ee.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(ee.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?pw(o.config):uw(o.config);w.length?(i=(await sn({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(k=>({title:k,value:k})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await sn({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await sn({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await sn({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(ee.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await fw(o.config,i,a):await hw(o.config,i,a);if(!c.length){console.log(ee.yellow(" no open issues matched"));return}console.log(ee.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 b=or({type:s,project:l,iid:w.iid,url:w.url}),k=g.has(b),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${k?ee.dim(" (already imported)"):""}`,value:w,disabled:k}}),f=(await sn({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(ee.dim(" nothing selected"));return}let p=f.map(w=>{let b={type:s,host:s==="gitlab"?mw(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:or(b),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:b,importedAt:new Date().toISOString()}}),y=o.store.addMany(p);console.log(ee.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let w of y)console.log(ee.dim(` ${w.id} \u2014 ${w.title}`))});function mw(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function pw(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 uw(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 fw(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 hw(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(km)}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(km):[]}function km(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 yw}from"commander";import J from"chalk";import{existsSync as ww,readFileSync as $w}from"fs";import{resolve as bw}from"path";import kw from"prompts";te();function vm(e){let o=e||bw(process.cwd(),"agentx.json");return ww(o)||(console.log(J.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse($w(o,"utf-8"))}async function vw(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(J.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await kw([{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(J.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var No=new yw().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');No.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: ${Hi})`,Hi).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){No.help();return}o.agent||(console.log(J.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(J.red(' --do "<prompt>" is required')),process.exit(1));let t=Ji(e);t||(console.log(J.red(` Couldn't parse: "${e}"`)),console.log(J.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(J.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(J.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=vm(o.config),s=Ja(n);n.agents?.[o.agent]||(console.log(J.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(J.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await vw(o.notify,s),r=o.id||xc(t.matched,o.agent),a=Ec({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 re(d=>Ie(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(J.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(J.green(` \u2713 ${g} cron ${J.cyan(r)}`)),console.log(J.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(J.dim(` Agent: ${o.agent}`)),i&&console.log(J.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(J.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(J.dim(" Daemon hot-reloaded."))});No.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=vm(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(J.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?J.yellow("\u25D0"):i.enabled?J.green("\u25CF"):J.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${J.cyan(s.padEnd(32))} ${J.dim(i.schedule.padEnd(14))} ${J.dim("\u2192")} ${i.agent}`),console.log(J.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(J.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(J.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Tc(Ac(i.schedule,c),c);console.log(J.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(J.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])No.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Cc(t,o);n.success||(console.log(J.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(J.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(J.dim(" Daemon hot-reloaded."))});No.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await re(t=>{if(!Pt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);yc(t,`crons.${e}`)});o.success||(console.log(J.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(J.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(J.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",jc,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Oc,"reject an agent's pending create/delete request (drops the request)"]])No.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(J.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(J.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(J.dim(" Daemon hot-reloaded."))});No.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ji(o);t||(console.log(J.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(J.green(` "${o}"`)),console.log(J.dim(` \u2192 ${t.cron}`)),console.log(J.dim(` \u2192 ${t.human}`))});import{Command as xw}from"commander";import ke from"chalk";import Ro from"chalk";function xm(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 Sm=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Em(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(Ro.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?xm():n?al(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(Ro.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={...Ut().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await gl(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(Ro.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(Ro.dim(` not answered${r.why?` (${r.why})`:""}; the card is still waiting`));return}let a=await Ts({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(Ro.red(` ${a.error}`)),process.exitCode=1;return}console.log(Ro.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(`${Sm()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(Ro.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(Ro.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(Ro.red(` couldn't reach the daemon at ${Sm()}: ${n?.message??n}`)),process.exitCode=1}})}var _o=new xw("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Sw={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function Am(){return{root:process.cwd()}}function Vr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Ew(e){console.log(` ${ke.cyan(e.key)} ${ke.dim(`[${Sw[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ke.dim(` (later: until ${Vr(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 ${Vr(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}`:""}`))}_o.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=dl(Am(),{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)Ew(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 Xr(e,o,t){let n=Ut(),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 Ts(Am(),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}`))}_o.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)=>Xr(e,"yes",o));_o.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)=>Xr(e,"no",o));_o.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)=>Xr(e,"later",o));_o.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: ${rl.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(async e=>{let o=Ut(),t={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},n=o.forwardTo?await Aw(t):cl(process.cwd(),t,{settings:o});if(!n.ok){console.error(ke.red(` ${n.error}`)),process.exitCode=1;return}let s=o.forwardTo?` on ${o.forwardTo}`:"";console.log(ke.green(` \u2713 card:${n.card.id} raised${s}; expires ${Vr(n.card.expires)}, then: ${n.card.if_silent}`))});async function Aw(e){let o=(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,""),t={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(t.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${o}/approvals`,{method:"POST",headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));return n.ok?{ok:!0,card:s.card}:{ok:!1,error:s.error??`HTTP ${n.status}`}}catch(n){return{ok:!1,error:`couldn't reach the daemon at ${o} (it forwards cards when approvals.forwardTo is set): ${n?.message??n}`}}}Em(_o);_o.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("--forward-to <peer>",`send this machine's cards to that mesh peer's inbox and popup; "none" to keep them here`).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),e.forwardTo!==void 0&&(o.forwardTo=e.forwardTo==="none"?null:e.forwardTo),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=Zl(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 ed(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=Ut(),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(` Cards go to ${i.forwardTo?`${i.forwardTo} (mesh peer)`:"this machine"}`),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 Tw}from"commander";import B from"chalk";te();us();iu();var oo=new Tw("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),Kr=Wa,Tm="-".repeat(64);function gi(){let e=90;try{e=T().members.logRetentionDays}catch{}return new $c(process.cwd(),Date.now,e)}var jm=(e,o=[])=>[...o,e];function Im(e){let o=[];try{o=Object.keys(T().agents)}catch{return}let t=e.filter(n=>!o.includes(n));t.length&&(console.log(B.yellow(` ! not an agent on this machine: ${t.join(", ")}. Agents here: ${o.join(", ")||"none"}.`)),console.log(B.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var Nm="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.",jw="An owner is never limited. Change the role first if that is what you want.",Qr=["tools","skills"];function Ow(e){let o=e.toLowerCase().replace(/^(tool|skill)$/,"$1s");return Qr.includes(o)?o:null}async function rn(e){let o="",t=await re(n=>{n.people=Array.isArray(n.people)?n.people:[],o=e(n.people)});t.success||(console.error(B.red(`\u2717 ${(t.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(B.green(`\u2713 ${o}`)),t.reloaded&&console.log(B.dim(" daemon hot-reloaded"))}function Qn(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 Rm(e,o){let t=Li(e),n=Li(o);return!!t&&!!n&&t.channel===n.channel&&t.value===n.value}function _m(e){let o=Qr.filter(t=>e.deny?.[t]?.length).map(t=>` \xB7 no ${t}: ${e.deny[t].join(", ")}`).join("");console.log(` ${B.bold(e.id)} ${e.name} ${B.dim(`\xB7 ${e.role}`)}${e.agents?.length?B.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}${B.dim(o)}`),console.log(B.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}oo.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(B.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${Mi}"; senders on other channels are unknown.`)),console.log(B.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let t of o)_m(t);console.log()});oo.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${Kr.join(" | ")}. A client is someone you do work for; their page is "Your project"`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",jm,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",jm,[]).action(async(e,o)=>{await rn(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(!Kr.includes(o.role))throw new Error(`--role must be one of: ${Kr.join(", ")}`);if(o.role==="owner"&&o.agent.length)throw new Error(Nm);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(", ")}`:""}`}),Im(o.agent)});oo.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 rn(n=>{let s=Qn(n,e);if(!t&&s.role==="owner")throw new Error(Nm);return s.agents=t?[]:[...new Set(o)],t?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),t||Im(o)});oo.command("deny <id> <level> <names...>").description(`stop a person's turns using these tools or skills. Level: tools | skills. Names match without case; * is a wildcard. "none" lifts the limit`).action(async(e,o,t)=>{let n=Ow(o);n||(console.error(B.red(`\u2717 level must be one of: ${Qr.join(", ")}`)),process.exit(1));let s=t.length===1&&t[0].toLowerCase()==="none";await rn(i=>{let r=Qn(i,e);if(!s&&r.role==="owner")throw new Error(jw);return r.deny={...r.deny??{},[n]:s?[]:[...new Set(t)]},s?`${e} may use every ${n.slice(0,-1)}`:`${e} may not use these ${n}: ${r.deny[n].join(", ")}`})});oo.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,o)=>{await rn(t=>{let n=Qn(t,e);return n.identities.some(s=>Rm(s,o))?`${e} already has ${o}`:(n.identities.push(o),`${o} is now ${e}`)})});oo.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,o)=>{await rn(t=>{let n=Qn(t,e),s=n.identities.length;if(n.identities=n.identities.filter(i=>!Rm(i,o)),n.identities.length===s)throw new Error(`"${e}" has no identity ${o}.`);return`${o} is no longer ${e}`})});oo.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 rn(t=>(Qn(t,e),t.splice(t.findIndex(n=>n?.id===e),1),`removed ${e}`));let o=cd({tokens:new no,members:gi()},e);o.length&&console.log(B.green(`\u2713 ended ${o.length} machine(s) of ${e}: ${o.map(t=>t.name).join(", ")}`)),console.log(B.dim(" If you shared this computer with them on the private network, remove that share too."))});oo.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own page (/member): My work for a teammate, Your project for a client. Ends with a message to forward to them as it is").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=Un(),n=yr(wr(),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(`
444
+ `));let s=(o.url?String(o.url):hr()).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=sd({tokens:new no,codes:new Es,members:gi(),people:()=>i},e);if(!r.ok)throw new Error(r.error);console.log(),console.log(` Invite for ${B.bold(r.person.name)} (${r.person.id}, ${r.person.role}). Their page is ${B.bold(ir(r.person.role))}.`),console.log(),console.log(" 1. Share this computer with them on your private network, if you have not yet:"),console.log(B.dim(" Tailscale admin console \u2192 Machines \u2192 this computer \u2192 Share \u2192 send them the link.")),console.log(B.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 the message below, or this address and code. The code works once, for ${id} minutes:`),console.log(),console.log(` ${B.cyan(`${s}/member`)}`),console.log(` ${B.bold(Ss(r.code))}`),console.log(),console.log(` 3. When they pair, a card "New machine for ${r.person.name}" asks you to approve that machine. Then ${ir(r.person.role)} opens for them.`),console.log(B.dim(` Their key stops after ${nd} days; invite again then. Machine id: ${r.tokenId}`)),console.log(),console.log(` ${B.bold("Message to forward")} ${B.dim("(copy everything between the two lines; the rest of this output is for you)")}`),console.log(B.dim(Tm)),console.log(rd({person:r.person,origin:s,code:r.code})),console.log(B.dim(Tm)),console.log()}catch(t){console.log(B.red(` ${t.message}`)),process.exit(1)}});oo.command("devices [id]").description("the machines paired to people's own pages (My work, Your project): state, where from, first and last use").option("--json","machine-readable output").action((e,o)=>{let t=gi().devices(e);if(o.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(B.dim(`
440
445
  No machines${e?` for ${e}`:""}. Run \`agentx people invite <id>\`.
441
- `));return}console.log();for(let n of t){let s=n.state==="active"?z.green("active"):n.state==="pending"?z.yellow("waiting for your approval"):z.red(`removed${n.removedReason?`: ${n.removedReason}`:""}`);console.log(` ${z.cyan(n.tokenId)} ${z.bold(n.personId)} ${n.name} ${s}`),console.log(z.dim(` paired: ${n.createdAt} from ${n.address??"?"}${n.network?` as ${n.network}`:""}${n.lastSeenAt?` last used: ${n.lastSeenAt} from ${n.lastAddress??"?"}`:""}`))}console.log()});oo.command("revoke-device <tokenId>").description("end one machine's access at once").action(e=>{let o=Ql({tokens:new no,members:di()},e);o||(console.log(z.red(` No machine with id ${e}. See \`agentx people devices\`.`)),process.exit(1)),console.log(z.green(`
446
+ `));return}console.log();for(let n of t){let s=n.state==="active"?B.green("active"):n.state==="pending"?B.yellow("waiting for your approval"):B.red(`removed${n.removedReason?`: ${n.removedReason}`:""}`);console.log(` ${B.cyan(n.tokenId)} ${B.bold(n.personId)} ${n.name} ${s}`),console.log(B.dim(` paired: ${n.createdAt} from ${n.address??"?"}${n.network?` as ${n.network}`:""}${n.lastSeenAt?` last used: ${n.lastSeenAt} from ${n.lastAddress??"?"}`:""}`))}console.log()});oo.command("revoke-device <tokenId>").description("end one machine's access at once").action(e=>{let o=ad({tokens:new no,members:gi()},e);o||(console.log(B.red(` No machine with id ${e}. See \`agentx people devices\`.`)),process.exit(1)),console.log(B.green(`
442
447
  \u2713 Ended ${e} (${o.name}, ${o.personId})
443
- `))});var hm=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC",ym=(e,o=100)=>(e??"").replace(/\s+/g," ").trim().slice(0,o);oo.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=qo({quiet:!0}),s=n?Yl(n,e,Number(o.limit)||20):[],i=n?Vl(n,e):[];if(o.json){console.log(JSON.stringify({person:t??null,openRequests:i,runs:s},null,2));return}if(console.log(),t?km(t):console.log(z.dim(` "${e}" is not in the list${e===Pi?" (it is the built-in owner of this machine)":""}; showing what is recorded under that id`)),!n){console.log(z.yellow(`
448
+ `))});var Om=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC",Cm=(e,o=100)=>(e??"").replace(/\s+/g," ").trim().slice(0,o);oo.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=qo({quiet:!0}),s=n?od(n,e,Number(o.limit)||20):[],i=n?td(n,e):[];if(o.json){console.log(JSON.stringify({person:t??null,openRequests:i,runs:s},null,2));return}if(console.log(),t?_m(t):console.log(B.dim(` "${e}" is not in the list${e===Mi?" (it is the built-in owner of this machine)":""}; showing what is recorded under that id`)),!n){console.log(B.yellow(`
444
449
  couldn't open .agentx/db.sqlite: run this from the folder that holds agentx.json
445
450
  `));return}if(i.length){console.log(`
446
- Open requests (${i.length})`);for(let r of i)console.log(` ${z.cyan(r.id)} ${z.dim(`${hm(r.createdAt)} \xB7 ${r.channel} \xB7 ${r.agentId} \xB7 ${r.state.replace(/_/g," ")}`)}
447
- ${ym(r.text,200)}`)}console.log(`
448
- Latest runs (${s.length})`),s.length===0&&console.log(z.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?z.green("ok"):r.status==="in-flight"?z.yellow("running"):z.red(r.status);console.log(` ${z.dim(hm(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${ym(r.messagePreview)}`)}console.log()});ps();Hp();import{Command as cw}from"commander";import{existsSync as lw}from"fs";import ye from"chalk";var rn=new cw("requests").description("what you asked agents for that is not finished, oldest first"),vm={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 zr(){if(!lw(lc()))return console.error(ye.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=qo();return e?new Da(e):(process.exitCode=1,null)}var gi=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function xm(e){let o=e.state==="needs_attention"?ye.red:e.state==="waiting_owner"?ye.yellow:ye.dim;console.log(` ${ye.cyan(e.id)} ${o(`[${vm[e.state]??e.state}]`)} ${ye.dim(`${gi(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(ye.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(ye.red(` ${e.attentionReason}`)),e.evidence&&console.log(ye.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(ye.dim(` Reason: ${e.closeReason}`))}rn.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=zr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Gi().enabled||console.log(ye.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(ye.dim(" no open requests"));return}for(let n of t)xm(n);console.log(ye.dim(`
449
- ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});rn.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=zr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(ye.red(` no request "${e}"`)),process.exitCode=1;return}xm(t),console.log(ye.dim(` Last activity ${gi(t.updatedAt)}${t.closedAt?` \xB7 closed ${gi(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(ye.dim(` ${n.kind} ${n.ref} (${gi(n.at)})`))});function Sm(e,o,t,n){rn.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=zr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(ye.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(ye.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(ye.red(` ${s} is already closed (${vm[c.state]??c.state})`)),process.exitCode=1;return}console.log(ye.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>","");rn.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(ye.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await tl(o);if(!n.success){console.error(ye.red(` ${n.error}`)),process.exitCode=1;return}console.log(ye.green(" \u2713 saved")+(n.reloaded?ye.dim(" (daemon reloaded)"):""))}let t=Gi();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 dw}from"commander";import an from"chalk";te();var Em=new dw("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",sr.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(an.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(i=>{n=ed(i,e,o==="on")});s.success||(console.error(an.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(an.green(`\u2713 ${n}`)),s.reloaded&&console.log(an.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of sr)console.log(` ${n.padEnd(8)} ${t.includes(n)?an.green("on"):an.dim("off")}`)});import{Command as Rw}from"commander";import cn from"chalk";import ce from"chalk";import Zn from"prompts";import{readFileSync as gw,writeFileSync as mw,existsSync as pw}from"fs";import{resolve as Am}from"path";var uw=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function fw(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Yr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Tm(e=".env"){let o=Am(e);if(!pw(o))return[];let t=gw(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(uw);i?n.push({kind:"kv",key:i[1],value:fw(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function hw(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Yr(o.value)}`:o.raw).join(`
451
+ Open requests (${i.length})`);for(let r of i)console.log(` ${B.cyan(r.id)} ${B.dim(`${Om(r.createdAt)} \xB7 ${r.channel} \xB7 ${r.agentId} \xB7 ${r.state.replace(/_/g," ")}`)}
452
+ ${Cm(r.text,200)}`)}console.log(`
453
+ Latest runs (${s.length})`),s.length===0&&console.log(B.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?B.green("ok"):r.status==="in-flight"?B.yellow("running"):B.red(r.status);console.log(` ${B.dim(Om(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${Cm(r.messagePreview)}`)}console.log()});us();su();import{Command as Cw}from"commander";import{existsSync as Iw}from"fs";import ye from"chalk";var an=new Cw("requests").description("what you asked agents for that is not finished, oldest first"),Dm={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 Zr(){if(!Iw(hc()))return console.error(ye.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=qo();return e?new Ua(e):(process.exitCode=1,null)}var mi=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function Pm(e){let o=e.state==="needs_attention"?ye.red:e.state==="waiting_owner"?ye.yellow:ye.dim;console.log(` ${ye.cyan(e.id)} ${o(`[${Dm[e.state]??e.state}]`)} ${ye.dim(`${mi(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(ye.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(ye.red(` ${e.attentionReason}`)),e.evidence&&console.log(ye.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(ye.dim(` Reason: ${e.closeReason}`))}an.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Zr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(zi().enabled||console.log(ye.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(ye.dim(" no open requests"));return}for(let n of t)Pm(n);console.log(ye.dim(`
454
+ ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});an.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Zr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(ye.red(` no request "${e}"`)),process.exitCode=1;return}Pm(t),console.log(ye.dim(` Last activity ${mi(t.updatedAt)}${t.closedAt?` \xB7 closed ${mi(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(ye.dim(` ${n.kind} ${n.ref} (${mi(n.at)})`))});function Mm(e,o,t,n){an.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=Zr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(ye.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(ye.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(ye.red(` ${s} is already closed (${Dm[c.state]??c.state})`)),process.exitCode=1;return}console.log(ye.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}Mm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");Mm("drop","drop a request you no longer want","--reason <text>","");an.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(ye.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await ll(o);if(!n.success){console.error(ye.red(` ${n.error}`)),process.exitCode=1;return}console.log(ye.green(" \u2713 saved")+(n.reloaded?ye.dim(" (daemon reloaded)"):""))}let t=zi();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 Nw}from"commander";import cn from"chalk";te();var Lm=new Nw("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",rr.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(cn.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(i=>{n=ld(i,e,o==="on")});s.success||(console.error(cn.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(cn.green(`\u2713 ${n}`)),s.reloaded&&console.log(cn.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of rr)console.log(` ${n.padEnd(8)} ${t.includes(n)?cn.green("on"):cn.dim("off")}`)});import{Command as o$}from"commander";import ln from"chalk";import ce from"chalk";import es from"prompts";import{readFileSync as Rw,writeFileSync as _w,existsSync as Dw}from"fs";import{resolve as qm}from"path";var Pw=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Mw(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function ea(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Fm(e=".env"){let o=qm(e);if(!Dw(o))return[];let t=Rw(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(Pw);i?n.push({kind:"kv",key:i[1],value:Mw(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Lw(e){return e.map(o=>o.kind==="kv"?`${o.key}=${ea(o.value)}`:o.raw).join(`
450
455
  `)+`
451
- `}function Qn(e,o,t=".env"){let n=Am(t),s=Tm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Yr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Yr(o)}`})),mw(n,hw(s))}function Vr(e,o=".env"){return Tm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var jm="https://t.me/BotFather";async function yw(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 ww(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 Om(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${jm}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Zn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&dt(jm);let{token:t}=await Zn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:k=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(k.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await yw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.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(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Zn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Zn({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(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(f,t.trim()),process.env[f]=t.trim();let p=await re(k=>{Ie(k,"channels.telegram.enabled",!0),Ie(k,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Dt(k,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(k,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Zn({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(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await ww(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let b=await re(k=>{Ie(k,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!b.success){console.log(ce.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Xr from"prompts";import{existsSync as Qr,mkdirSync as $w,readdirSync as bw,readFileSync as Cm}from"fs";import{resolve as Kr}from"path";var kw=".agentx/whatsapp-sessions";function vw(){let e=Kr(process.cwd(),".agentx/daemon.pid");if(!Qr(e))return!1;try{let o=parseInt(Cm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function xw(e){if(!Qr(e))return!1;try{return bw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Sw(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;$w(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 Im(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),vw()){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 Xr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Kr(process.cwd(),"agentx.json");Qr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Cm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||kw,s=Kr(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 Xr({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(xw(s)&&a){let{keep:l}=await Xr({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 Sw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(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 Nm from"prompts";var mi="agentx-mesh:",pi="//join/";function Aw(e){return Buffer.from(e,"utf-8").toString("base64url")}function Tw(e){return Buffer.from(e,"base64url").toString("utf-8")}function jw(e){return`${mi}${pi}${Aw(JSON.stringify(e))}`}function Ow(e){if(!e.startsWith(`${mi}${pi}`))throw new Error(`Not a mesh invite link \u2014 expected ${mi}${pi}\u2026`);let o=e.slice(mi.length+pi.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 Cw(){return Ew(32).toString("hex")}function Iw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Nw(e){return e?.node?.name||e?.node?.id||"node"}async function Rm(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=Vr("MESH_TOKEN");r||(r=Cw(),Qn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Iw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Nm({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 re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=jw({url:a,token:r,name:Nw(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 _m(e,o={}){let t;try{t=Ow(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Vr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Nm({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))}Qn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=Dt(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 ln=new Rw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ln.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 Om({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ln.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 Im({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Dm=ln.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Dm.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 Rm({url:e.url,configPath:e.config})});Dm.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 _m(e,{configPath:o.config})});ln.action(()=>{console.log(),console.log(cn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${cn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${cn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${cn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${cn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(cn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as _w}from"commander";import X from"chalk";var kt=new _w().name("usage").description("token usage analysis and reporting");kt.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(X.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(X.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${X.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: ${X.red(String(s.totalErrors))}`),console.log(),console.log(X.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(` ${X.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${X.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${e.message}`))}});kt.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:X.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(X.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(X.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?X.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(X.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${o.message}`))}});kt.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(X.red(` Script not found: ${s}`)),console.log(X.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(X.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(X.red(" Analysis failed. Is Python 3 installed?"))}});kt.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:o,writeFileSync:t}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:i}=await import("./usage-channels-KBLEC4NE.js"),r=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!r(e.from)||!r(e.to)||e.from>e.to){console.log(X.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&t(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(o(e.baseline,"utf-8"))}catch(p){console.log(X.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(X.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(X.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(X.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of f){let b=i(y),k=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let $=i(w),E=b!==null&&$?`${((b-$)/$*100).toFixed(0)}%`:"-";k+=` ${l($).padStart(9)} ${E.padStart(7)}`}console.log(k)}console.log(),c&&console.log(X.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(X.dim(` Saved ${e.save}`)),console.log()});kt.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-CH3SHO77.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-V2JEVJAD.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(X.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${X.dim("\xB7")} ${d}`);console.log(),console.log(X.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(X.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(X.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(X.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(X.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(X.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=X.dim(`${i.days}d`);console.log(` ${X.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(X.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 Pw}from"fs";import{resolve as Mw}from"path";te();var ot=new Dw().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ot.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{za(Mw(process.cwd(),".env"))}catch{}let o=Lw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-SAYBNLZW.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 Lw(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.
456
+ `}function Zn(e,o,t=".env"){let n=qm(t),s=Fm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${ea(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${ea(o)}`})),_w(n,Lw(s))}function oa(e,o=".env"){return Fm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Um="https://t.me/BotFather";async function qw(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 Fw(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 Wm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${Um}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await es({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&dt(Um);let{token:t}=await es({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:k=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(k.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.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(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await es({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await es({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(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Zn(f,t.trim()),process.env[f]=t.trim();let p=await re(k=>{Ie(k,"channels.telegram.enabled",!0),Ie(k,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Pt(k,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(k,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await es({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(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await Fw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let b=await re(k=>{Ie(k,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!b.success){console.log(ce.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import ta from"prompts";import{existsSync as sa,mkdirSync as Uw,readdirSync as Ww,readFileSync as Bm}from"fs";import{resolve as na}from"path";var Bw=".agentx/whatsapp-sessions";function Jw(){let e=na(process.cwd(),".agentx/daemon.pid");if(!sa(e))return!1;try{let o=parseInt(Bm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Hw(e){if(!sa(e))return!1;try{return Ww(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gw(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;Uw(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 Jm(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),Jw()){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 ta({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||na(process.cwd(),"agentx.json");sa(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Bm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Bw,s=na(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 ta({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(Hw(s)&&a){let{keep:l}=await ta({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 Gw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(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 zw}from"crypto";import je from"chalk";import Hm from"prompts";var pi="agentx-mesh:",ui="//join/";function Yw(e){return Buffer.from(e,"utf-8").toString("base64url")}function Vw(e){return Buffer.from(e,"base64url").toString("utf-8")}function Xw(e){return`${pi}${ui}${Yw(JSON.stringify(e))}`}function Kw(e){if(!e.startsWith(`${pi}${ui}`))throw new Error(`Not a mesh invite link \u2014 expected ${pi}${ui}\u2026`);let o=e.slice(pi.length+ui.length),t=JSON.parse(Vw(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 Qw(){return zw(32).toString("hex")}function Zw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function e$(e){return e?.node?.name||e?.node?.id||"node"}async function Gm(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=oa("MESH_TOKEN");r||(r=Qw(),Zn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Zw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Hm({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 re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=Xw({url:a,token:r,name:e$(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 zm(e,o={}){let t;try{t=Kw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=oa("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Hm({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))}Zn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=Pt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),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 dn=new o$().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");dn.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 Wm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});dn.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 Jm({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Ym=dn.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 Gm({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 zm(e,{configPath:o.config})});dn.action(()=>{console.log(),console.log(ln.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ln.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ln.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ln.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ln.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ln.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as t$}from"commander";import X from"chalk";var vt=new t$().name("usage").description("token usage analysis and reporting");vt.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(X.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(X.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${X.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: ${X.red(String(s.totalErrors))}`),console.log(),console.log(X.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(` ${X.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${X.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${e.message}`))}});vt.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:X.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(X.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(X.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?X.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(X.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${o.message}`))}});vt.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(X.red(` Script not found: ${s}`)),console.log(X.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(X.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(X.red(" Analysis failed. Is Python 3 installed?"))}});vt.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:o,writeFileSync:t}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:i}=await import("./usage-channels-KBLEC4NE.js"),r=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!r(e.from)||!r(e.to)||e.from>e.to){console.log(X.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&t(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(o(e.baseline,"utf-8"))}catch(p){console.log(X.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(X.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(X.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(X.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of f){let b=i(y),k=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let $=i(w),E=b!==null&&$?`${((b-$)/$*100).toFixed(0)}%`:"-";k+=` ${l($).padStart(9)} ${E.padStart(7)}`}console.log(k)}console.log(),c&&console.log(X.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(X.dim(` Saved ${e.save}`)),console.log()});vt.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-HCJTUS6Z.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-EZLJIVQX.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(X.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${X.dim("\xB7")} ${d}`);console.log(),console.log(X.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(X.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(X.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(X.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(X.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(X.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=X.dim(`${i.days}d`);console.log(` ${X.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(X.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as n$}from"commander";import xe from"chalk";import{readFileSync as s$}from"fs";import{resolve as i$}from"path";te();var ot=new n$().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ot.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{ec(i$(process.cwd(),".env"))}catch{}let o=r$(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-3TVUCOSI.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 r$(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.
452
457
  `)),{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}}}}ot.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(xe.dim(`
453
458
  No boards configured.
454
- `));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)}});ot.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{es(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)}});ot.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{es(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 Zr=ot.command("column").description("manage a board's columns (add / remove / edit / list)");Zr.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)}});Zr.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{es(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)}});Zr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{es(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)}});ot.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{es(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 es(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(xe.green(`
459
+ `));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)}});ot.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{os(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)}});ot.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{os(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 ia=ot.command("column").description("manage a board's columns (add / remove / edit / list)");ia.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(s$("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)}});ia.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{os(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)}});ia.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{os(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)}});ot.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{os(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 os(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(xe.green(`
455
460
  \u2713 ${o}
456
461
  `)),t&&console.log(xe.dim(` Backup: ${t}`)),console.log(xe.dim(` Restart the dashboard to pick up the change if not auto-reloading.
457
- `))}import{Command as Fw}from"commander";import m from"chalk";import Ae from"chalk";import{resolve as qw}from"path";var Uw=e=>e||qw(process.cwd(),".agentx/wiki");async function dn(e){let{FactLedger:o}=await import("./ledger-CH7R756S.js");return new o(Uw(e))}function gn(e){return async(...o)=>{try{await e(...o)}catch(t){t?.name!=="LedgerCorruptError"&&console.error(Ae.red(` ${t?.message??t}`)),process.exitCode=1}}}function Pm(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(gn(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await dn(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(gn(async(n,s)=>{let i=(await dn(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: ${qi.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(gn(async n=>{if(n.class&&!Ka(n.class)){console.error(Ae.red(` --class must be one of ${qi.join(", ")}`)),process.exitCode=1;return}let i=(await dn(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(gn(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await dn(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(`
458
- 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(gn(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await dn(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(gn(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await dn(s.dir),n,s.by,s.reason);console.log(Ae.dim(` rejected: ${r.claim}`))}))}import{resolve as q,relative as Mm,dirname as Lm}from"path";import{execSync as vt}from"child_process";import{writeFileSync as xt,mkdirSync as Do,readFileSync as os,readdirSync as Ww,renameSync as ui,rmSync as Bw,existsSync as to}from"fs";function Oe(e,o){return new Li(St(e),void 0,o||"graph")}function St(e){return e||q(process.cwd(),".agentx/wiki")}function oa(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ne=new Fw().name("wiki").description("wiki knowledge base management");Pm(ne);ne.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 [${oa(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())});ne.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(St(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()});ne.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 to(u)?new Uo({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 b=f.find(S=>S.id===w);if(!b)continue;let k=c(b);if(!k?.length)continue;let $=k.join("/"),E=p.get($);E?E.n++:p.set($,{path:k,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(x=>!f||(x.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 x of p.slice(0,3))console.log(m.dim(` [${x.date} via ${x.source}] ${x.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(),b=y.getWorldview()||t.getSharedStore().getWorldview()||"",k=p.map(x=>`--- ENTRY ${x.id} [${x.date} ${x.agentId} via ${x.source}] ---
462
+ `))}import{Command as l$}from"commander";import m from"chalk";import Ae from"chalk";import{resolve as a$}from"path";var c$=e=>e||a$(process.cwd(),".agentx/wiki");async function gn(e){let{FactLedger:o}=await import("./ledger-CH7R756S.js");return new o(c$(e))}function mn(e){return async(...o)=>{try{await e(...o)}catch(t){t?.name!=="LedgerCorruptError"&&console.error(Ae.red(` ${t?.message??t}`)),process.exitCode=1}}}function Vm(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(mn(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await gn(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(mn(async(n,s)=>{let i=(await gn(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: ${Fi.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(mn(async n=>{if(n.class&&!sc(n.class)){console.error(Ae.red(` --class must be one of ${Fi.join(", ")}`)),process.exitCode=1;return}let i=(await gn(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(mn(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await gn(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(`
463
+ 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(mn(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await gn(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(mn(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await gn(s.dir),n,s.by,s.reason);console.log(Ae.dim(` rejected: ${r.claim}`))}))}import{resolve as F,relative as Xm,dirname as Km}from"path";import{execSync as xt}from"child_process";import{writeFileSync as St,mkdirSync as Do,readFileSync as ts,readdirSync as d$,renameSync as fi,rmSync as g$,existsSync as to}from"fs";function Oe(e,o){return new qi(Et(e),void 0,o||"graph")}function Et(e){return e||F(process.cwd(),".agentx/wiki")}function aa(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ne=new l$().name("wiki").description("wiki knowledge base management");Vm(ne);ne.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 [${aa(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())});ne.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(Et(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()});ne.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=F(process.cwd(),".agentx/graph");return to(u)?new Fo({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 b=f.find(S=>S.id===w);if(!b)continue;let k=c(b);if(!k?.length)continue;let $=k.join("/"),E=p.get($);E?E.n++:p.set($,{path:k,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(x=>!f||(x.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 x of p.slice(0,3))console.log(m.dim(` [${x.date} via ${x.source}] ${x.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(),b=y.getWorldview()||t.getSharedStore().getWorldview()||"",k=p.map(x=>`--- ENTRY ${x.id} [${x.date} ${x.agentId} via ${x.source}] ---
459
464
  ${x.content}
460
465
  --- END ENTRY ---`).join(`
461
466
 
462
- `),$="";if(e.facts!==!1){let{extractHints:x,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:P,defaultSources:J,recordsFromEntries:L}=await import("./facts-ROUMKS7I.js");if(!a){let H=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&H.add(Se.meta.title);a=[...H]}let Y=x(p.map(H=>({context:H.sourceContext,content:H.content,sender:typeof H.meta?.sender=="string"?H.meta.sender:void 0})),{known:a}),fe=L(p);if(Y.length>0||fe.length>0){let H=J(),{records:Ce,results:Se}=Y.length>0?await R(Y,{sources:H}):{records:[],results:[]},M=I([...fe,...Ce]);$=C(M);let eo=[...fe.length>0?[`entries:${fe.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${Y.length} entities \u2192 ${M.length} resolved${eo.length?` (${eo.join(" ")})`:""}`));for(let Ee of P(Se,H))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=Cc(o,u,b,w.articles,k,p.length,$);console.log(m.dim(` Mode: ${oa(o)}`));let S=q(y.baseDir,"_tmp");Do(S,{recursive:!0});let v=q(S,"absorb-prompt.txt");xt(v,E),console.log(m.dim(" Compiling with Claude..."));try{let x;try{x=vt(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ot({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(x=M.stdout||"",!x)throw M}let R=x;try{let M=JSON.parse(x);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 Y=R[L],fe=Y==="{"?"}":"]",H=0,Ce=-1;for(let M=L;M<R.length;M++)if(R[M]===Y)H++;else if(R[M]===fe&&(H--,H===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 eo=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:eo,lastUpdated:eo,sources:M.sources||[],graphPath:Ee},M.content,u);let rt=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("+")} ${rt}${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"),eo=new M(St(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)}`})));eo.added>0&&console.log(m.dim(` queued ${eo.added} for follow-up (agentx wiki questions)`))}catch{}}y.rebuildIndex()}catch(x){console.log(m.red(` Absorb failed: ${x.message?.slice(0,200)}`)),x.stderr&&console.log(m.dim(String(x.stderr).slice(0,300))),x.stdout&&console.log(m.dim("stdout: "+String(x.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()});ne.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=Jw(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-56ZPJNXW.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!to(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(!to(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 Ic({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 fi=ne.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function hi(e){return e?q(e):q(process.cwd(),".agentx","wiki")}fi.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(hi(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}`))}});fi.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(hi(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(`
467
+ `),$="";if(e.facts!==!1){let{extractHints:x,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:P,defaultSources:H,recordsFromEntries:q}=await import("./facts-ROUMKS7I.js");if(!a){let G=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&G.add(Se.meta.title);a=[...G]}let Y=x(p.map(G=>({context:G.sourceContext,content:G.content,sender:typeof G.meta?.sender=="string"?G.meta.sender:void 0})),{known:a}),fe=q(p);if(Y.length>0||fe.length>0){let G=H(),{records:Ce,results:Se}=Y.length>0?await R(Y,{sources:G}):{records:[],results:[]},M=I([...fe,...Ce]);$=C(M);let eo=[...fe.length>0?[`entries:${fe.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${Y.length} entities \u2192 ${M.length} resolved${eo.length?` (${eo.join(" ")})`:""}`));for(let Ee of P(Se,G))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=Mc(o,u,b,w.articles,k,p.length,$);console.log(m.dim(` Mode: ${aa(o)}`));let S=F(y.baseDir,"_tmp");Do(S,{recursive:!0});let v=F(S,"absorb-prompt.txt");St(v,E),console.log(m.dim(" Compiling with Claude..."));try{let x;try{x=xt(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ct({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(x=M.stdout||"",!x)throw M}let R=x;try{let M=JSON.parse(x);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("{"),H=R.indexOf("["),q=P>=0&&(H<0||P<H)?P:H;if(q===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let Y=R[q],fe=Y==="{"?"}":"]",G=0,Ce=-1;for(let M=q;M<R.length;M++)if(R[M]===Y)G++;else if(R[M]===fe&&(G--,G===0)){Ce=M+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let Se=R.slice(q,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 eo=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:eo,lastUpdated:eo,sources:M.sources||[],graphPath:Ee},M.content,u);let rt=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("+")} ${rt}${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"),eo=new M(Et(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)}`})));eo.added>0&&console.log(m.dim(` queued ${eo.added} for follow-up (agentx wiki questions)`))}catch{}}y.rebuildIndex()}catch(x){console.log(m.red(` Absorb failed: ${x.message?.slice(0,200)}`)),x.stderr&&console.log(m.dim(String(x.stderr).slice(0,300))),x.stdout&&console.log(m.dim("stdout: "+String(x.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()});ne.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=m$(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-GU4S5VQH.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!to(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=F(process.cwd(),".agentx/db.sqlite");if(!to(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 Lc({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var hi=ne.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function yi(e){return e?F(e):F(process.cwd(),".agentx","wiki")}hi.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(yi(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}`))}});hi.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(yi(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(`
463
468
  `).map(s=>` ${s}`).join(`
464
- `)),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>)`))}});fi.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-KY3Y2PVU.js"),n=t(hi(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`))});fi.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-KY3Y2PVU.js"),n=t(hi(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 Jw(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)}ne.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-BYCRYDM3.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 b=r(d,w),k=[];try{k=t(b).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of k){if(u.length>=g)break;try{let E=JSON.parse(n(r(b,$),"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 b=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(b.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
469
+ `)),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>)`))}});hi.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-UGWANGI2.js"),n=t(yi(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`))});hi.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-UGWANGI2.js"),n=t(yi(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 m$(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)}ne.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",F(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-ZET7Z5FT.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 b=r(d,w),k=[];try{k=t(b).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of k){if(u.length>=g)break;try{let E=JSON.parse(n(r(b,$),"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 b=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(b.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
465
470
  `)||"_(none returned)_",E;try{let S=await o(b.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")E=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let v=S.citations.map(x=>`\`${x.title}\` [${x.type||"?"}]`).join(", ");E=`**Answer:**
466
471
 
467
472
  ${S.answer}
468
473
 
469
474
  **Citations:** ${v}`}}catch(S){E=`_(error: ${S.message})_`}console.log(m.dim("done")),p.push(`## ${w+1}. ${b.id}`,"",`> ${b.message.replace(/\n/g," ").slice(0,400)}${b.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",$,"","### NEW \u2014 agentic query","",E,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let y=p.join(`
470
- `);e.out?((await import("fs")).writeFileSync(e.out,y),console.log(),console.log(m.green(` Wrote ${y.length} bytes to ${e.out}`))):(console.log(),console.log(y))});ne.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-NZOBHQGS.js"),s=e.answers?os(e.answers,"utf-8").split(/\r?\n/).filter(_=>_.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=Oe(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(_){console.log(m.red(` can't open wiki for agent "${e.agent}": ${_.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async _=>{if(s){let $e=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${$e.slice(0,80)}${$e.length>80?"\u2026":""}`)+`
475
+ `);e.out?((await import("fs")).writeFileSync(e.out,y),console.log(),console.log(m.green(` Wrote ${y.length} bytes to ${e.out}`))):(console.log(),console.log(y))});ne.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-NZOBHQGS.js"),s=e.answers?ts(e.answers,"utf-8").split(/\r?\n/).filter(_=>_.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=Oe(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(_){console.log(m.red(` can't open wiki for agent "${e.agent}": ${_.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async _=>{if(s){let $e=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${$e.slice(0,80)}${$e.length>80?"\u2026":""}`)+`
471
476
  `),$e.trim()}return(await c.question(_)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(d)){console.log(m.dim(` Types: ${n.join(" | ")}`));let _=await l(m.cyan(" Type? "));if(_==="/abort"){c?.close();return}u.has(_)?d=_:(console.log(m.yellow(` "${_}" isn't a valid type. Falling back to "concept".`)),d="concept")}let f={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},p=f[d]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(d)}`)),console.log(m.dim(` ${p.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let y=[],w=!1;for(let _=0;_<p.length;_++){let $e=p[_],ro=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${$e}
472
477
  ${m.green(">")} `);if(ro==="/abort"){w=!0;break}if(ro==="/done")break;ro!=="/skip"&&ro&&y.push({q:$e,a:ro})}if(!w){let _=await l(`
473
478
  ${m.dim("Anything else worth capturing?")}
@@ -476,16 +481,16 @@ ${S.answer}
476
481
  `),$=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...y.map(_=>`
477
482
  Q: ${_.q}
478
483
  A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",k||"(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(`
479
- `),E=q(a.baseDir,"_tmp");Do(E,{recursive:!0});let S=q(E,`interview-${t().slice(0,8)}.txt`);xt(S,$),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";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=vt(_,{env:Ot({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let ro=JSON.parse($e);v=String(ro.result||ro.content||"")}catch{v=$e}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}v=v.trim();let x=v.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);x&&(v=x[1].trim());let R=v.indexOf("---");R>0&&(v=v.slice(R));let I=v.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(v.slice(0,600)),c?.close();return}let C={};for(let _ of I[1].split(`
480
- `)){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),fe=`${{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: ${fe}`)),console.log(),console.log(v),console.log();let H=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),H==="scrap"||H==="/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(H==="edit"){let _=process.env.EDITOR||"vi",$e=q(E,`draft-${t().slice(0,8)}.md`);xt($e,v);try{vt(`${_} '${$e}'`,{stdio:"inherit"});let Ri=os($e,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Ri){let Lo={};for(let En of Ri[1].split(`
481
- `)){let _i=En.match(/^(\w+):\s*(.+)$/);_i&&(Lo[_i[1]]=_i[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=Ri[2],Se={...Se,title:Lo.title||Se.title,type:Lo.type||Se.type,access:Lo.access||Se.access,related:Lo.related?Lo.related.replace(/^\[|\]$/g,"").split(",").map(En=>En.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:Lo.tags?Lo.tags.replace(/^\[|\]$/g,"").split(",").map(En=>En.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(ro){console.log(m.red(` editor failed: ${ro.message}`));return}}if(!a.writeArticle(fe,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${fe} saved.`));let eo=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let rt=eo.filter(_=>!Ee.has(_.toLowerCase()));if(rt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of rt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ne.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-BYCRYDM3.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=os(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 b=w[0].replace(/^Q:\s*/i,"").trim(),k=w.slice(1).join(" ").trim();b&&k&&r.push({q:b,verdict:k})}}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 Y=r[f];if(!Y)break;p=Y.q,y=Y.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(Y){console.log(m.red(`failed: ${Y.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 Y=w.citations.map(fe=>`${fe.title} [${fe.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
482
- `)),console.log(m.dim(" citations: "+Y))}r||(y=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+y);let b={q:p,answer:w.answer,citations:w.citations,verdict:y},k=y.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!k){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(b);continue}let $=k[1].toLowerCase(),E=(k[2]||"").trim();if(d.push(b),$==="/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 v=i.readArticle(S.path);if(!v){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let x=Gw(v.content,$,E,v.meta.title,v.meta.type),R=q(i.baseDir,"_tmp");Do(R,{recursive:!0});let I=q(R,`quiz-patch-${t().slice(0,8)}.txt`);xt(I,x);let C="";try{let Y=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=vt(Y,{env:Ot({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(fe);C=String(Ce.result||Ce.content||"")}catch{C=fe}let H=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);H&&(C=H[1].trim()),C=C.trim()}catch(Y){console.log(m.red(` patch failed: ${Y.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=v.content.split(`
483
- `).length,J=C.split(`
484
- `).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)")),b.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},C,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,b.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}\``:""),"")}xt(e.out,f.join(`
485
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ne.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=Fm(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{vt(`${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)}`))}});ne.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=Fm(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=Hw(l.content,l.meta.title,l.meta.type,t),d=q(a.baseDir,"_tmp");Do(d,{recursive:!0});let u=q(d,`patch-${i().slice(0,8)}.txt`);xt(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"`,v=vt(S,{env:Ot({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(v);f=String(R.result||R.content||"")}catch{f=v}let x=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);x&&(f=x[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(`
484
+ `),E=F(a.baseDir,"_tmp");Do(E,{recursive:!0});let S=F(E,`interview-${t().slice(0,8)}.txt`);St(S,$),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";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=xt(_,{env:Ct({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let ro=JSON.parse($e);v=String(ro.result||ro.content||"")}catch{v=$e}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}v=v.trim();let x=v.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);x&&(v=x[1].trim());let R=v.indexOf("---");R>0&&(v=v.slice(R));let I=v.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(v.slice(0,600)),c?.close();return}let C={};for(let _ of I[1].split(`
485
+ `)){let $e=_.match(/^(\w+):\s*(.+)$/);$e&&(C[$e[1]]=$e[2].trim().replace(/^"(.*)"$/,"$1"))}let P=I[2],H=C.title||g,q=H.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),fe=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${q}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${fe}`)),console.log(),console.log(v),console.log();let G=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),G==="scrap"||G==="/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:H,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(G==="edit"){let _=process.env.EDITOR||"vi",$e=F(E,`draft-${t().slice(0,8)}.md`);St($e,v);try{xt(`${_} '${$e}'`,{stdio:"inherit"});let _i=ts($e,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(_i){let Lo={};for(let An of _i[1].split(`
486
+ `)){let Di=An.match(/^(\w+):\s*(.+)$/);Di&&(Lo[Di[1]]=Di[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=_i[2],Se={...Se,title:Lo.title||Se.title,type:Lo.type||Se.type,access:Lo.access||Se.access,related:Lo.related?Lo.related.replace(/^\[|\]$/g,"").split(",").map(An=>An.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:Lo.tags?Lo.tags.replace(/^\[|\]$/g,"").split(",").map(An=>An.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(ro){console.log(m.red(` editor failed: ${ro.message}`));return}}if(!a.writeArticle(fe,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${fe} saved.`));let eo=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let rt=eo.filter(_=>!Ee.has(_.toLowerCase()));if(rt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of rt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ne.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-ZET7Z5FT.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=ts(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 b=w[0].replace(/^Q:\s*/i,"").trim(),k=w.slice(1).join(" ").trim();b&&k&&r.push({q:b,verdict:k})}}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 Y=r[f];if(!Y)break;p=Y.q,y=Y.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(Y){console.log(m.red(`failed: ${Y.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 Y=w.citations.map(fe=>`${fe.title} [${fe.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
487
+ `)),console.log(m.dim(" citations: "+Y))}r||(y=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+y);let b={q:p,answer:w.answer,citations:w.citations,verdict:y},k=y.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!k){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(b);continue}let $=k[1].toLowerCase(),E=(k[2]||"").trim();if(d.push(b),$==="/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 v=i.readArticle(S.path);if(!v){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let x=u$(v.content,$,E,v.meta.title,v.meta.type),R=F(i.baseDir,"_tmp");Do(R,{recursive:!0});let I=F(R,`quiz-patch-${t().slice(0,8)}.txt`);St(I,x);let C="";try{let Y=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=xt(Y,{env:Ct({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(fe);C=String(Ce.result||Ce.content||"")}catch{C=fe}let G=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);G&&(C=G[1].trim()),C=C.trim()}catch(Y){console.log(m.red(` patch failed: ${Y.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=v.content.split(`
488
+ `).length,H=C.split(`
489
+ `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${H} lines (${H-P>=0?"+":""}${H-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),b.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},C,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,b.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}\``:""),"")}St(e.out,f.join(`
490
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ne.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=ep(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=F(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{xt(`${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)}`))}});ne.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=ep(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=p$(l.content,l.meta.title,l.meta.type,t),d=F(a.baseDir,"_tmp");Do(d,{recursive:!0});let u=F(d,`patch-${i().slice(0,8)}.txt`);St(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"`,v=xt(S,{env:Ct({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(v);f=String(R.result||R.content||"")}catch{f=v}let x=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);x&&(f=x[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(`
486
491
  `).length,y=f.split(`
487
- `).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}),v=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),w=v==="y"||v==="yes"}if(!w){console.log(m.dim(" aborted."));return}let b=new Set,k=a.extractWikilinks(f).filter(S=>b.has(S)?!1:(b.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:k.length?k: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=>!k.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 Fm(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 Hw(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(`
488
- `)}function Gw(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
492
+ `).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}),v=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),w=v==="y"||v==="yes"}if(!w){console.log(m.dim(" aborted."));return}let b=new Set,k=a.extractWikilinks(f).filter(S=>b.has(S)?!1:(b.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:k.length?k: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=>!k.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 ep(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 p$(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(`
493
+ `)}function u$(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
489
494
 
490
495
  ${t}
491
496
 
@@ -498,8 +503,8 @@ Incorporate it into the most relevant existing section, or create a short new se
498
503
  ${t}
499
504
 
500
505
  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(`
501
- `)}ne.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(!to(u))continue;let f=q(u,i),p=r.map(k=>({mode:k,dir:q(u,k)})).filter(k=>to(k.dir));if(p.length===0)continue;let y=new Map;ea(f,k=>{let $=Mm(f,k);if($.startsWith("_")||$.startsWith("raw/")||$.includes("_tmp/"))return;let E=qm(os(k,"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 k of p)ea(k.dir,$=>{let E=Mm(k.dir,$);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=qm(os($,"utf-8"));S?.meta.title&&w.push({mode:k.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 b=p.map(k=>k.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${b}`));for(let k of w){let $=k.title.toLowerCase(),E=y.get($),S;E?!E.type&&k.type||!!E.type==!!k.type&&k.lastUpdated&&E.lastUpdated&&k.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let v=k.type?m.magenta(`[${k.type}]`):m.yellow("[untyped]"),x=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=k.relPath.length>46?k.relPath.slice(0,43)+"...":k.relPath.padEnd(46);if(console.log(` ${x} ${v} ${m.dim(k.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,k.relPath);to(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${k.relPath}`)),Um(u,k),g++):(Do(Lm(I),{recursive:!0}),ui(k.absPath,I),y.set($,{relPath:k.relPath,type:k.type,lastUpdated:k.lastUpdated}),c++)}else if(S==="upgrade"){let I=q(f,E.relPath);if(to(I)){let C=q(u,"_versions",E.relPath.replace(/\.md$/,""));Do(C,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");ui(I,q(C,`${P}.md`))}Do(Lm(I),{recursive:!0}),ui(k.absPath,I),y.set($,{relPath:E.relPath,type:k.type,lastUpdated:k.lastUpdated}),l++}else Um(u,k),g++}catch(I){console.log(m.red(` ! ${S} failed: ${I.message?.slice(0,120)}`))}}if(n){for(let k of p)try{Bw(k.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(k){console.log(m.dim(` (catalog rebuild skipped: ${k.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 ea(e,o){if(to(e))for(let t of Ww(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?ea(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function qm(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
502
- `)){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 Um(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));Do(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");ui(o.absPath,q(t,`${n}.md`))}ne.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(b=>!b.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");Do(w,{recursive:!0});for(let b=0;b<p;b+=n){let k=u.slice(b,Math.min(b+n,p)),$=Yw(k),E=q(w,"migrate-prompt.txt");xt(E,$);let S;try{let v=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=vt(v,{env:Ot({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(x),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(v){console.log(m.red(` LLM classify failed: ${v.message?.slice(0,150)}`));continue}for(let v of k){let x=S.find(L=>L.path===v.path),R=zw(x?.type);if(!x||!R){console.log(m.yellow(` ? ${v.path}: unclassified${x?` (got "${x.type}")`:""}`));continue}let I=g.extractWikilinks(v.content),C={...v.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} ${v.path}${P}`),i&&(g.writeArticle(v.path,C,v.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 zw(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 Yw(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}"
506
+ `)}ne.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?F(e.dir):F(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=F(s,"agents",d);if(!to(u))continue;let f=F(u,i),p=r.map(k=>({mode:k,dir:F(u,k)})).filter(k=>to(k.dir));if(p.length===0)continue;let y=new Map;ra(f,k=>{let $=Xm(f,k);if($.startsWith("_")||$.startsWith("raw/")||$.includes("_tmp/"))return;let E=Qm(ts(k,"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 k of p)ra(k.dir,$=>{let E=Xm(k.dir,$);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=Qm(ts($,"utf-8"));S?.meta.title&&w.push({mode:k.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 b=p.map(k=>k.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${b}`));for(let k of w){let $=k.title.toLowerCase(),E=y.get($),S;E?!E.type&&k.type||!!E.type==!!k.type&&k.lastUpdated&&E.lastUpdated&&k.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let v=k.type?m.magenta(`[${k.type}]`):m.yellow("[untyped]"),x=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=k.relPath.length>46?k.relPath.slice(0,43)+"...":k.relPath.padEnd(46);if(console.log(` ${x} ${v} ${m.dim(k.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=F(f,k.relPath);to(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${k.relPath}`)),Zm(u,k),g++):(Do(Km(I),{recursive:!0}),fi(k.absPath,I),y.set($,{relPath:k.relPath,type:k.type,lastUpdated:k.lastUpdated}),c++)}else if(S==="upgrade"){let I=F(f,E.relPath);if(to(I)){let C=F(u,"_versions",E.relPath.replace(/\.md$/,""));Do(C,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");fi(I,F(C,`${P}.md`))}Do(Km(I),{recursive:!0}),fi(k.absPath,I),y.set($,{relPath:E.relPath,type:k.type,lastUpdated:k.lastUpdated}),l++}else Zm(u,k),g++}catch(I){console.log(m.red(` ! ${S} failed: ${I.message?.slice(0,120)}`))}}if(n){for(let k of p)try{g$(k.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(k){console.log(m.dim(` (catalog rebuild skipped: ${k.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 ra(e,o){if(to(e))for(let t of d$(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?ra(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Qm(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
507
+ `)){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 Zm(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));Do(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");fi(o.absPath,F(t,`${n}.md`))}ne.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(b=>!b.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=F(y,"_tmp");Do(w,{recursive:!0});for(let b=0;b<p;b+=n){let k=u.slice(b,Math.min(b+n,p)),$=h$(k),E=F(w,"migrate-prompt.txt");St(E,$);let S;try{let v=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=xt(v,{env:Ct({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(x),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(v){console.log(m.red(` LLM classify failed: ${v.message?.slice(0,150)}`));continue}for(let v of k){let x=S.find(q=>q.path===v.path),R=f$(x?.type);if(!x||!R){console.log(m.yellow(` ? ${v.path}: unclassified${x?` (got "${x.type}")`:""}`));continue}let I=g.extractWikilinks(v.content),C={...v.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":""}`):"",H=R.alias?m.dim(` (from "${R.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+R.type+"]")}${H} ${v.path}${P}`),i&&(g.writeArticle(v.path,C,v.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 f$(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 h$(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}"
503
508
  title: "${t.meta.title}"
504
509
  tags: [${i}]
505
510
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -539,51 +544,51 @@ Output (JSON array, one entry per input article, same order):
539
544
  [
540
545
  {"path": "path/to/article.md", "type": "project"},
541
546
  ...
542
- ]`}ne.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()});ne.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-J6CNV23P.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(),id(o,t,e.agent,n,e.mode)});ne.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-EO3EVBH3.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 b=c.getAgentWiki(w);for(let k of b.listArticles(w)){if(u.length>=g)break e;let $=b.readArticle(k.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:k.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:k.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 v=n(S.answers),x=e.fields?r($.meta.type,S.answers):null;v.completeness>=d&&!(x&&!x.fit)||u.push({agent:w,type:$.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...x?{missing:x.missingCritical.join(",")||"-",cov:`${Math.round(x.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,b)=>parseFloat(w.score)-parseFloat(b.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(b=>String(b[w]).length))),y=w=>w.map((b,k)=>String(b).padEnd(p[k])).join(" ");console.log(),console.log(m.bold(y(f)));for(let w of u)console.log(y(f.map(b=>w[b])));if(e.fields){let w=u.filter(b=>b.missing!=="-").length;console.log(m.dim(`
547
+ ]`}ne.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()});ne.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-ZHQYXFOJ.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(),ud(o,t,e.agent,n,e.mode)});ne.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-L6XJ2BFA.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 b=c.getAgentWiki(w);for(let k of b.listArticles(w)){if(u.length>=g)break e;let $=b.readArticle(k.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:k.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:k.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 v=n(S.answers),x=e.fields?r($.meta.type,S.answers):null;v.completeness>=d&&!(x&&!x.fit)||u.push({agent:w,type:$.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...x?{missing:x.missingCritical.join(",")||"-",cov:`${Math.round(x.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,b)=>parseFloat(w.score)-parseFloat(b.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(b=>String(b[w]).length))),y=w=>w.map((b,k)=>String(b).padEnd(p[k])).join(" ");console.log(),console.log(m.bold(y(f)));for(let w of u)console.log(y(f.map(b=>w[b])));if(e.fields){let w=u.filter(b=>b.missing!=="-").length;console.log(m.dim(`
543
548
  ${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(`
544
- ${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."))});ne.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-BYCRYDM3.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()}});ne.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()});ne.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(!to(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Uo({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,b=0,k=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let v of $.meta.sources){let x=y.get(v);if(!x)continue;let R=String(x.meta?.sender??""),I=s.fingerprint({text:x.content,channel:x.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;b++,l++;let S;for(let v of E.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),k++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${b} matched \xB7 ${m.green(k)} 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()});ne.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-J6CNV23P.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()});ne.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 Li(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 k of d.articles){for(let $ of k.tags||[])p.add($);y+=k.tags?.length||0;for(let $ of k.sources||[])w.add($)}let b=new Set(d.articles.map(k=>k.path.includes("/")?k.path.split("/")[0]:"/"));return{mode:c,label:oa(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:b.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()});ne.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");to(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=to(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Vw(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ne.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-EO3EVBH3.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 v of d){let x=l.getAgentWiki(v);for(let R of x.listArticles(v)){if(f>=u)break e;let I=x.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:v,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:v,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:v,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(St(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"],b=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),k=w.map(v=>Math.max(v.length,...p.map(x=>b(x[v]).length))),$=(v,x)=>String(v)+" ".repeat(Math.max(0,k[x]-b(v).length));console.log(),console.log(m.bold(w.map((v,x)=>$(v,x)).join(" ")));for(let v of p)console.log(w.map((x,R)=>$(v[x],R)).join(" "));let E=p.filter(v=>v.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:v}=await import("./article-fields-PITN4NHA.js"),x=v[e.notifyTier]??v.pillar,R=g.filter(I=>(v[I.tier??"furniture"]??9)<=x);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-J6CNV23P.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(H=>`\u2022 ${H.question}`).join(`
545
- `),L=R.length>10?`
549
+ ${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."))});ne.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-ZET7Z5FT.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=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ne.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()});ne.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=F(process.cwd(),".agentx/graph");if(!to(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Fo({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,b=0,k=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let v of $.meta.sources){let x=y.get(v);if(!x)continue;let R=String(x.meta?.sender??""),I=s.fingerprint({text:x.content,channel:x.source,sender:R}),C=r.get(I);if(!C?.length)continue;let P=C.join("/"),H=E.get(P);H?H.n++:E.set(P,{path:C,n:1})}if(E.size===0)continue;b++,l++;let S;for(let v of E.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),k++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${b} matched \xB7 ${m.green(k)} 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()});ne.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-ZHQYXFOJ.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()});ne.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new qi(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 k of d.articles){for(let $ of k.tags||[])p.add($);y+=k.tags?.length||0;for(let $ of k.sources||[])w.add($)}let b=new Set(d.articles.map(k=>k.path.includes("/")?k.path.split("/")[0]:"/"));return{mode:c,label:aa(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:b.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()});ne.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");to(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=to(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${y$(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ne.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-L6XJ2BFA.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 v of d){let x=l.getAgentWiki(v);for(let R of x.listArticles(v)){if(f>=u)break e;let I=x.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:v,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 H of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&H.needsHuman||(e.ask&&H.needsHuman&&g.push({kind:"field",agentId:v,path:R.path,subject:I.meta.title,field:H.field,tier:H.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${H.label}?`}),p.push({tier:H.tier,need:H.field,how:H.needsHuman?m.yellow("ask"):H.sources.join("/"),uncertain:H.uncertain?"?":"",agent:v,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(Et(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"],b=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),k=w.map(v=>Math.max(v.length,...p.map(x=>b(x[v]).length))),$=(v,x)=>String(v)+" ".repeat(Math.max(0,k[x]-b(v).length));console.log(),console.log(m.bold(w.map((v,x)=>$(v,x)).join(" ")));for(let v of p)console.log(w.map((x,R)=>$(v[x],R)).join(" "));let E=p.filter(v=>v.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:v}=await import("./article-fields-PITN4NHA.js"),x=v[e.notifyTier]??v.pillar,R=g.filter(I=>(v[I.tier??"furniture"]??9)<=x);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-ZHQYXFOJ.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 H=R.slice(0,10).map(G=>`\u2022 ${G.question}`).join(`
550
+ `),q=R.length>10?`
546
551
  \u2026and ${R.length-10} more`:"",Y=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
547
- ${J}${L}
552
+ ${H}${q}
548
553
 
549
- agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let H=await fetch(`http://127.0.0.1:${fe}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:Y})});console.log(H.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${H.status}) \u2014 questions are still queued.`))}catch(H){console.log(m.yellow(` Push failed (${String(H?.message??H).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ne.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-EO3EVBH3.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(),b=c(d(f.getSharedStore().listEntries())),k=new Map(b.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],v=!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 Y=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(!Y){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let H=t(L.meta.type,Y.answers).missing.filter(_=>i.includes(_));if(H.length===0)continue;let{records:Ce,results:Se}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=k.get(L.meta.title.toLowerCase().trim());if(!v){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));v=!0}let eo=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(eo.length===0)continue;let{content:Ee,edits:rt}=u(L.content,eo[0],H);if(rt.length!==0){for(let _ of rt)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 x=["agent","article","field","action","got"],R=x.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(x)));for(let C of S)console.log(I(x.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.")))});ne.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(St(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`))});ne.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(St(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(St(t.dir));try{let b=w.get(c.factId);if(b){let k=w.write({subject:b.subject,attribute:b.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:b.volatility},{confirmedBy:"operator"});console.log(m.green(` ${k.status}: ${b.id} ${b.subject} \xB7 ${b.attribute}: ${k.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(b){b?.name!=="LedgerCorruptError"&&console.log(m.red(` ${b?.message??b}`)),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}`))});ne.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-EO3EVBH3.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:b}=r(p,y),k=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,v=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 (${b} in backlog) \u2014 grading ${k.length}`));for(let L of e.load?[]:k){let Y=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!Y){S++;continue}let fe=Y.answers;E.push({entry:L,verdict:s(Y.answers,$),citeWorthy:fe.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 x=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),C=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:x,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 ${x.n} (${x.positives} kept by absorb, ${x.negatives} passed over)`),console.log(` recall ${P(x.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(x.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(x.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${x.lostPositives>0?m.yellow(`lost ${x.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)")}`),x.lostPositives>0){let L=x.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=x.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:Y,points:fe}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${fe.length} policies, recall floor ${P(L)})`)),Y)console.log(` best: ${Y.requireTyped?`typed & type>=${Y.minType}`:"type gate OFF"} worth>=${Y.minWorth} durability>=${Y.minDurability}`),console.log(` recall ${P(Y.recall)} \xB7 filtered ${P(Y.filtered)} \xB7 precision ${P(Y.precision)} \xB7 lost ${Y.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 H=fe.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];H&&console.log(m.dim(` Best recall available: ${P(H.recall)} at ${H.requireTyped?`type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} dur>=${H.minDurability}, filtering ${P(H.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ne.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);to(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");to(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 Vw(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"}Xp();import{Command as Xw}from"commander";import D from"chalk";import{resolve as yi}from"path";import{existsSync as Kw}from"fs";te();var mn=new Xw().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");mn.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 Uo({baseDir:yi(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=fs(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 b=Qw(y,a,c),k=null;try{k=await Zw(n,t,b,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!k||!k.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(k.decision).toLowerCase().trim(),E=(k.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{e$(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()});mn.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=yi(process.cwd(),o.graph.baseDir);if(!Kw(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 Uo({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()});mn.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 Uo({baseDir:yi(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(x=>x.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let x=await fetch(`${t}/graph/schema`,{headers:s});if(!x.ok)throw new Error(`schema HTTP ${x.status}`);l=(await x.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(x){console.log(D.red(` fetch failed: ${x.message}`));return}let u=r.levels.map(x=>x.id).join(","),f=l?.levels?.map(x=>x.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((x,R)=>w.set(x.id,R));let b=[...g].sort((x,R)=>(w.get(x.level)??99)-(w.get(R.level)??99)),k=0,$=0,E=0;for(let x of b){if(c.has(x.id)){$++;continue}if(e.dryRun){k++,c.add(x.id);continue}try{i.addNode({...x,createdBy:x.createdBy?`${x.createdBy} (sync)`:`sync:${t}`}),c.add(x.id),k++}catch(R){E++,console.log(D.yellow(` skip node ${x.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${k} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,v=0;for(let x of d)if(!(!x.msgHash||!Array.isArray(x.path))){if(i.getFingerprint(x.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint(x.msgHash,{path:x.path,leaf:x.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${v} 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 Qw(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(`
554
+ agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let G=await fetch(`http://127.0.0.1:${fe}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:Y})});console.log(G.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${G.status}) \u2014 questions are still queued.`))}catch(G){console.log(m.yellow(` Push failed (${String(G?.message??G).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ne.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-L6XJ2BFA.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(),b=c(d(f.getSharedStore().listEntries())),k=new Map(b.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],v=!1;e:for(let C of p){let P=f.getAgentWiki(C);for(let H of P.listArticles(C)){if($>=y)break e;if(H.meta.type!=="person")continue;let q=P.readArticle(H.path);if(!q)continue;$++;let Y=await r(s,n({title:q.meta.title,type:q.meta.type,body:q.content}),o(q.meta.type),{links:[{kind:"article",id:H.path}],features:{agent:C,op:"backfill"}});if(!Y){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let G=t(q.meta.type,Y.answers).missing.filter(_=>i.includes(_));if(G.length===0)continue;let{records:Ce,results:Se}=await a([{name:q.meta.title,type:"person"}],{sources:w}),M=k.get(q.meta.title.toLowerCase().trim());if(!v){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));v=!0}let eo=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(eo.length===0)continue;let{content:Ee,edits:rt}=u(q.content,eo[0],G);if(rt.length!==0){for(let _ of rt)S.push({agent:C,article:q.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(H.path,q.meta,Ee,C)?E++:console.log(m.red(` could not write ${H.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 x=["agent","article","field","action","got"],R=x.map(C=>Math.max(C.length,...S.map(P=>String(P[C]).length))),I=C=>C.map((P,H)=>String(P).padEnd(R[H])).join(" ");console.log(),console.log(m.bold(I(x)));for(let C of S)console.log(I(x.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.")))});ne.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(Et(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`))});ne.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(Et(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(Et(t.dir));try{let b=w.get(c.factId);if(b){let k=w.write({subject:b.subject,attribute:b.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:b.volatility},{confirmedBy:"operator"});console.log(m.green(` ${k.status}: ${b.id} ${b.subject} \xB7 ${b.attribute}: ${k.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(b){b?.name!=="LedgerCorruptError"&&console.log(m.red(` ${b?.message??b}`)),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}`))});ne.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-L6XJ2BFA.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(q=>q.id)),{labeled:w,backlog:b}=r(p,y),k=a(w,q=>q.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,v=Date.now();if(e.load){let{readFileSync:q}=await import("fs");E.push(...JSON.parse(q(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 (${b} in backlog) \u2014 grading ${k.length}`));for(let q of e.load?[]:k){let Y=await i(o,n(q),t,{features:{source:q.source??"",absorbed:q.absorbed}});if(!Y){S++;continue}let fe=Y.answers;E.push({entry:q,verdict:s(Y.answers,$),citeWorthy:fe.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:q}=await import("fs");q(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let x=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),C=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:x,calibration:I,failures:S,elapsed:C},null,2));return}let P=q=>`${(q*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${x.n} (${x.positives} kept by absorb, ${x.negatives} passed over)`),console.log(` recall ${P(x.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(x.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(x.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${x.lostPositives>0?m.yellow(`lost ${x.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)")}`),x.lostPositives>0){let q=x.droppedBy;console.log(m.dim(` dropped by: type ${q.type} \xB7 worth ${q.worth} \xB7 durability ${q.durability} (a positive can fail several)`))}let H=x.positiveMeans;if(console.log(m.dim(` positives avg: worth ${H.worth.toFixed(2)} \xB7 durability ${H.durability.toFixed(2)} \xB7 typeConf ${H.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 q=parseFloat(e.minRecall),{best:Y,points:fe}=g(E,{minRecall:q});if(console.log(),console.log(m.bold(` threshold sweep (${fe.length} policies, recall floor ${P(q)})`)),Y)console.log(` best: ${Y.requireTyped?`typed & type>=${Y.minType}`:"type gate OFF"} worth>=${Y.minWorth} durability>=${Y.minDurability}`),console.log(` recall ${P(Y.recall)} \xB7 filtered ${P(Y.filtered)} \xB7 precision ${P(Y.precision)} \xB7 lost ${Y.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(q)} recall \u2014 not even keeping everything typed.`));let G=fe.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];G&&console.log(m.dim(` Best recall available: ${P(G.recall)} at ${G.requireTyped?`type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} dur>=${G.minDurability}, filtering ${P(G.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ne.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=F(process.cwd(),e);to(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");to(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function y$(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"}lu();import{Command as w$}from"commander";import D from"chalk";import{resolve as wi}from"path";import{existsSync as $$}from"fs";te();var pn=new w$().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");pn.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 Fo({baseDir:wi(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=hs(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 b=b$(y,a,c),k=null;try{k=await k$(n,t,b,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!k||!k.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(k.decision).toLowerCase().trim(),E=(k.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{v$(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()});pn.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=wi(process.cwd(),o.graph.baseDir);if(!$$(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 Fo({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()});pn.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 Fo({baseDir:wi(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(x=>x.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let x=await fetch(`${t}/graph/schema`,{headers:s});if(!x.ok)throw new Error(`schema HTTP ${x.status}`);l=(await x.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(x){console.log(D.red(` fetch failed: ${x.message}`));return}let u=r.levels.map(x=>x.id).join(","),f=l?.levels?.map(x=>x.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((x,R)=>w.set(x.id,R));let b=[...g].sort((x,R)=>(w.get(x.level)??99)-(w.get(R.level)??99)),k=0,$=0,E=0;for(let x of b){if(c.has(x.id)){$++;continue}if(e.dryRun){k++,c.add(x.id);continue}try{i.addNode({...x,createdBy:x.createdBy?`${x.createdBy} (sync)`:`sync:${t}`}),c.add(x.id),k++}catch(R){E++,console.log(D.yellow(` skip node ${x.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${k} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,v=0;for(let x of d)if(!(!x.msgHash||!Array.isArray(x.path))){if(i.getFingerprint(x.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint(x.msgHash,{path:x.path,leaf:x.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${v} 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 b$(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(`
550
555
  `),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(`
551
- `)}async function Zw(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 Ba((c?.content||"").toString())}finally{clearTimeout(r)}}function e$(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function ta(){let e=T();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=yi(process.cwd(),e.graph.baseDir);return{store:new Uo({baseDir:o}),baseDir:o}}var na=mn.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");na.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=ta();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(fs(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]"))});na.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=ta();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}: ${fs(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});na.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=ta();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 r$}from"commander";import Q from"chalk";import{Command as Bm}from"commander";import pe from"chalk";import{existsSync as o$}from"fs";import{resolve as t$}from"path";import n$ from"better-sqlite3";function s$(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(pe.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function i$(e){let o=t$(process.cwd(),e);return o$(o)||(console.log(pe.red(` No db at ${o}`)),process.exit(1)),new n$(o,{readonly:!0})}var Jm=new Bm().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(Cn)).option("--max <n>","max clusters distilled per run",String($s)).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(pe.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=i$(e.path),t=await Nc(o,{since:s$(e.since),agentId:e.agent,sessions:new Xa(process.cwd()),minOccurrences:Number(e.minOccurrences)||Cn,max:Number(e.max)||$s,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(pe.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(` ${pe.cyan(n.key)} ${pe.bold(`\xD7${n.count}`)} ${pe.dim(n.status)}`),n.sampleMessage&&console.log(pe.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(pe.dim(`
556
+ `)}async function k$(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 Xa((c?.content||"").toString())}finally{clearTimeout(r)}}function v$(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function ca(){let e=T();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=wi(process.cwd(),e.graph.baseDir);return{store:new Fo({baseDir:o}),baseDir:o}}var la=pn.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");la.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=ca();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(hs(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]"))});la.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=ca();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}: ${hs(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});la.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=ca();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 j$}from"commander";import Q from"chalk";import{Command as tp}from"commander";import pe from"chalk";import{existsSync as x$}from"fs";import{resolve as S$}from"path";import E$ from"better-sqlite3";function A$(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(pe.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function T$(e){let o=S$(process.cwd(),e);return x$(o)||(console.log(pe.red(` No db at ${o}`)),process.exit(1)),new E$(o,{readonly:!0})}var np=new tp().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(In)).option("--max <n>","max clusters distilled per run",String(bs)).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(pe.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=T$(e.path),t=await qc(o,{since:A$(e.since),agentId:e.agent,sessions:new nc(process.cwd()),minOccurrences:Number(e.minOccurrences)||In,max:Number(e.max)||bs,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(pe.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(` ${pe.cyan(n.key)} ${pe.bold(`\xD7${n.count}`)} ${pe.dim(n.status)}`),n.sampleMessage&&console.log(pe.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(pe.dim(`
552
557
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(pe.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(pe.green(` \u2713 draft written: ${n.id}`)+pe.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(pe.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(pe.yellow(` \u26A0 ${n}`));t.dryRun?console.log(pe.dim(`
553
558
  dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(pe.dim(`
554
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Wm={hourly:"0 * * * *",daily:"0 3 * * *"},Hm=new Bm().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(Cn)).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?Wm.hourly:e.daily?Wm.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(pe.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(pe.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Cn,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 ${$s} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
555
- `),i=await re(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(pe.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(pe.green(` \u2713 ${r} procedure extraction: off`)):(console.log(pe.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(pe.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(pe.dim(" on-task counting: enabled")),console.log(pe.dim(` threshold: ${t} occurrences`))),console.log(pe.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var $o=new r$().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");$o.addCommand(Jm);$o.addCommand(Hm);$o.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 Fo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Q.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"?Q.green(n.meta.status):n.meta.status==="draft"?Q.yellow(n.meta.status):Q.dim(n.meta.status);console.log(` ${Q.cyan(n.meta.id)} ${Q.bold(n.meta.title)} ${s}`),console.log(` ${Q.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Q.dim("source:")} ${Q.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Q.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Q.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});$o.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 Fo,t=e.steps?String(e.steps):`## Steps
559
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),op={hourly:"0 * * * *",daily:"0 3 * * *"},sp=new tp().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(In)).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?op.hourly:e.daily?op.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(pe.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(pe.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||In,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 ${bs} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
560
+ `),i=await re(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(pe.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(pe.green(` \u2713 ${r} procedure extraction: off`)):(console.log(pe.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(pe.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(pe.dim(" on-task counting: enabled")),console.log(pe.dim(` threshold: ${t} occurrences`))),console.log(pe.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var bo=new j$().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");bo.addCommand(np);bo.addCommand(sp);bo.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 Uo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Q.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"?Q.green(n.meta.status):n.meta.status==="draft"?Q.yellow(n.meta.status):Q.dim(n.meta.status);console.log(` ${Q.cyan(n.meta.id)} ${Q.bold(n.meta.title)} ${s}`),console.log(` ${Q.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Q.dim("source:")} ${Q.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Q.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Q.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});bo.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 Uo,t=e.steps?String(e.steps):`## Steps
556
561
 
557
562
  1. (fill in)
558
563
 
559
564
  ## Notes
560
565
 
561
- `;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(Q.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Q.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Q.red(` add failed: ${n.message}`)),process.exit(1)}});$o.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new Fo,t=o.get(e)??o.getDraft(e);t||(console.log(Q.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Q.bold(` ${t.meta.title}`)+Q.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Q.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Q.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Q.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Q.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Q.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Q.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Q.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});$o.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new Fo;try{let t=o.promoteDraft(e);console.log(Q.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Q.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Q.red(` ${t.message}`)),process.exit(1)}});$o.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new Fo;try{o.rejectDraft(e),console.log(Q.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Q.red(` ${t.message}`)),process.exit(1)}});$o.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new Fo;try{o.deprecate(e),console.log(Q.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Q.red(` ${t.message}`)),process.exit(1)}});$o.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 Fo,n=gc(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Q.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Q.cyan(s.procedure.meta.id)} ${Q.bold(s.score.toFixed(2))} ${Q.dim(s.reasons.join(", "))}`),console.log(Q.dim(` ${s.procedure.meta.trigger}`))});import{Command as l$}from"commander";import A from"chalk";import{resolve as un,basename as d$}from"path";import{existsSync as sa,readFileSync as ia,writeFileSync as wi}from"fs";import _T from"better-sqlite3";import{readFileSync as a$}from"fs";import{resolve as pn,dirname as Gm}from"path";import{fileURLToPath as c$}from"url";var ts=[{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 zm(e){let o=Gm(c$(import.meta.url)),t=process.argv[1]?Gm(process.argv[1]):"",n=[pn(o,`${e}.yaml`),pn(o,"workflows/templates",`${e}.yaml`),pn(o,"..","workflows/templates",`${e}.yaml`),pn(o,"../..","workflows/templates",`${e}.yaml`),t?pn(t,"workflows/templates",`${e}.yaml`):"",t?pn(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return a$(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
566
+ `;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(Q.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Q.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Q.red(` add failed: ${n.message}`)),process.exit(1)}});bo.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new Uo,t=o.get(e)??o.getDraft(e);t||(console.log(Q.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Q.bold(` ${t.meta.title}`)+Q.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Q.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Q.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Q.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Q.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Q.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Q.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Q.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});bo.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new Uo;try{let t=o.promoteDraft(e);console.log(Q.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Q.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Q.red(` ${t.message}`)),process.exit(1)}});bo.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new Uo;try{o.rejectDraft(e),console.log(Q.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Q.red(` ${t.message}`)),process.exit(1)}});bo.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new Uo;try{o.deprecate(e),console.log(Q.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Q.red(` ${t.message}`)),process.exit(1)}});bo.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 Uo,n=wc(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Q.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Q.cyan(s.procedure.meta.id)} ${Q.bold(s.score.toFixed(2))} ${Q.dim(s.reasons.join(", "))}`),console.log(Q.dim(` ${s.procedure.meta.trigger}`))});import{Command as I$}from"commander";import A from"chalk";import{resolve as fn,basename as N$}from"path";import{existsSync as da,readFileSync as ga,writeFileSync as $i}from"fs";import ij from"better-sqlite3";import{readFileSync as O$}from"fs";import{resolve as un,dirname as ip}from"path";import{fileURLToPath as C$}from"url";var ns=[{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 rp(e){let o=ip(C$(import.meta.url)),t=process.argv[1]?ip(process.argv[1]):"",n=[un(o,`${e}.yaml`),un(o,"workflows/templates",`${e}.yaml`),un(o,"..","workflows/templates",`${e}.yaml`),un(o,"../..","workflows/templates",`${e}.yaml`),t?un(t,"workflows/templates",`${e}.yaml`):"",t?un(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return O$(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
562
567
  ${n.join(`
563
- `)}`)}var Qe=new l$().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Qe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new at().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"}.`))});Qe.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 at().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(oc(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))});Qe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=un(process.cwd(),e);sa(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=ia(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Rt(r,{filePath:e}):JSON.parse(r),l=Nt.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=hs(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 ys?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let t=new at().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)});Qe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${ts.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");ts.some(a=>a.name===t)||(console.log(A.red(` unknown template "${o.template}"`)),console.log(A.dim(` available: ${ts.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 at;!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=zm(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=Rt(s,{filePath:`${e}.yaml`}),c=Nt.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=un(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Rt(s,{filePath:`${e}.yaml`}),c=Nt.parse(a);wi(r,JSON.stringify(c,null,2)+`
564
- `)}else wi(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()});Qe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of ts)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()});Qe.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=un(process.cwd(),e);sa(t)||(console.log(A.red(` file not found: ${t}`)),process.exit(1));let n=ia(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Rt(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof ys?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=Nt.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=hs(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 at,l=s?d$(e).match(/\.yml$/i)?"yml":"yaml":"json",g=un(c.baseDir,`${r.data.id}.${l}`);if(wi(g,s?n:JSON.stringify(r.data,null,2)+`
565
- `),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`))}});Qe.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 jn({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"}.`))});Qe.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=un(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&sa(s)){let c=ia(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?Rt(c,{filePath:e}):JSON.parse(c)}catch(k){let $=k instanceof ys?k.message:`parse error: ${k?.message??k}`;console.log(A.red(` ${$}`)),process.exit(1)}let d=Nt.safeParse(g);if(!d.success){console.log(A.red(" \u2717 schema:"));for(let k of d.error.issues)console.log(` ${k.path.join(".")||"<root>"}: ${k.message}`);process.exit(1)}let u=hs(d.data);if(u.length){console.log(A.red(" \u2717 lint:"));for(let k of u)console.log(` ${k}`);process.exit(1)}let f=new at,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,y=l?"yaml":"json",w=un(f.baseDir,`${p}.${y}`),b=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
566
- `;wi(w,b),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 g$({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function g$(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())}Qe.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}Ym(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)Ym(i)});function Ym(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()}Qe.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 jn({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Qe.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 jn({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Qe.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 jn({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 Vm}from"commander";import le from"chalk";import Et from"prompts";import{readFileSync as m$,existsSync as p$}from"fs";import{resolve as u$}from"path";var ns=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],ra=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Xm={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 Km(){let e=u$(process.cwd(),"agentx.json");if(!p$(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(m$(e,"utf-8"))}function f$(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?le.yellow("\u26A0 no signing secret"):le.green("\u2713 active"):le.dim("disabled")}function h$(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=ra.has(e.source)?le.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${le.cyan(e.id)} ${f$(e)}`),console.log(` ${le.dim(e.source)} \u2192 ${le.bold(e.agentId)}${n}`),console.log(` POST ${le.dim(t)}`),e.secretEnv&&console.log(` secret: ${le.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${le.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${le.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${le.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var Po=new Vm().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");Po.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Km(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(le.dim(`
568
+ `)}`)}var Qe=new I$().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Qe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new at().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"}.`))});Qe.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 at().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(cc(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))});Qe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=fn(process.cwd(),e);da(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=ga(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?_t(r,{filePath:e}):JSON.parse(r),l=Rt.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=ys(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 ws?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let t=new at().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)});Qe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${ns.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");ns.some(a=>a.name===t)||(console.log(A.red(` unknown template "${o.template}"`)),console.log(A.dim(` available: ${ns.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 at;!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=rp(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=_t(s,{filePath:`${e}.yaml`}),c=Rt.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=fn(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=_t(s,{filePath:`${e}.yaml`}),c=Rt.parse(a);$i(r,JSON.stringify(c,null,2)+`
569
+ `)}else $i(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()});Qe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of ns)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()});Qe.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=fn(process.cwd(),e);da(t)||(console.log(A.red(` file not found: ${t}`)),process.exit(1));let n=ga(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?_t(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof ws?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=Rt.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=ys(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 at,l=s?N$(e).match(/\.yml$/i)?"yml":"yaml":"json",g=fn(c.baseDir,`${r.data.id}.${l}`);if($i(g,s?n:JSON.stringify(r.data,null,2)+`
570
+ `),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`))}});Qe.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 On({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"}.`))});Qe.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=fn(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&da(s)){let c=ga(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?_t(c,{filePath:e}):JSON.parse(c)}catch(k){let $=k instanceof ws?k.message:`parse error: ${k?.message??k}`;console.log(A.red(` ${$}`)),process.exit(1)}let d=Rt.safeParse(g);if(!d.success){console.log(A.red(" \u2717 schema:"));for(let k of d.error.issues)console.log(` ${k.path.join(".")||"<root>"}: ${k.message}`);process.exit(1)}let u=ys(d.data);if(u.length){console.log(A.red(" \u2717 lint:"));for(let k of u)console.log(` ${k}`);process.exit(1)}let f=new at,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,y=l?"yaml":"json",w=fn(f.baseDir,`${p}.${y}`),b=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
571
+ `;$i(w,b),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 R$({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function R$(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())}Qe.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}ap(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)ap(i)});function ap(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()}Qe.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 On({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Qe.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 On({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Qe.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 On({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 cp}from"commander";import le from"chalk";import At from"prompts";import{readFileSync as _$,existsSync as D$}from"fs";import{resolve as P$}from"path";var ss=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],ma=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),lp={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 dp(){let e=P$(process.cwd(),"agentx.json");if(!D$(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(_$(e,"utf-8"))}function M$(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?le.yellow("\u26A0 no signing secret"):le.green("\u2713 active"):le.dim("disabled")}function L$(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=ma.has(e.source)?le.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${le.cyan(e.id)} ${M$(e)}`),console.log(` ${le.dim(e.source)} \u2192 ${le.bold(e.agentId)}${n}`),console.log(` POST ${le.dim(t)}`),e.secretEnv&&console.log(` secret: ${le.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${le.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${le.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${le.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var Po=new cp().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");Po.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=dp(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(le.dim(`
567
572
  No webhooks registered. Add one with: agentx webhook add
568
- `));return}console.log();for(let n of t)h$(n)});Po.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${ns.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=Km(),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 Et({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 Et({type:"select",name:"source",message:"Source",choices:ns.map(p=>({title:`${p}${ra.has(p)?" \u2713 wired":""}`,value:p,description:Xm[p]}))})).source),!ns.includes(a))throw new Error(`Source must be one of: ${ns.join(", ")}`);if(!c&&d&&(i?c=((await Et({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Et({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 Et({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await Et({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await re(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(le.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(le.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(le.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});Po.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Et({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await re(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(le.green(`\u2713 removed webhook "${e}"`))});function Qm(e){return async o=>{let t=await re(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(le.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}Po.command("enable <id>").description("enable a webhook entry").action(Qm(!0));Po.command("disable <id>").description("disable a webhook entry").action(Qm(!1));var $i=new Vm().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");$i.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await re(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(le.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});$i.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await re(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(le.green(`\u2713 removed trigger ${o} from "${e}"`))});$i.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 re(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(le.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});Po.addCommand($i);Po.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=ns.map(t=>({source:t,wired:ra.has(t),hint:Xm[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?le.green("\u2713 wired"):le.dim("inbound-only");console.log(` ${le.cyan(t.source.padEnd(8))} ${n} ${le.dim(t.hint)}`)}console.log(),console.log(le.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(le.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as y$}from"commander";import de from"chalk";te();function fn(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(de.green(`
573
+ `));return}console.log();for(let n of t)L$(n)});Po.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${ss.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=dp(),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 At({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 At({type:"select",name:"source",message:"Source",choices:ss.map(p=>({title:`${p}${ma.has(p)?" \u2713 wired":""}`,value:p,description:lp[p]}))})).source),!ss.includes(a))throw new Error(`Source must be one of: ${ss.join(", ")}`);if(!c&&d&&(i?c=((await At({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await At({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 At({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await At({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await re(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(le.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(le.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(le.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});Po.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await At({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await re(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(le.green(`\u2713 removed webhook "${e}"`))});function gp(e){return async o=>{let t=await re(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(le.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}Po.command("enable <id>").description("enable a webhook entry").action(gp(!0));Po.command("disable <id>").description("disable a webhook entry").action(gp(!1));var bi=new cp().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");bi.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await re(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(le.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});bi.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await re(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(le.green(`\u2713 removed trigger ${o} from "${e}"`))});bi.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 re(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(le.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});Po.addCommand(bi);Po.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=ss.map(t=>({source:t,wired:ma.has(t),hint:lp[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?le.green("\u2713 wired"):le.dim("inbound-only");console.log(` ${le.cyan(t.source.padEnd(8))} ${n} ${le.dim(t.hint)}`)}console.log(),console.log(le.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(le.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as q$}from"commander";import de from"chalk";te();function hn(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(de.green(`
569
574
  \u2713 ${o}`)),t&&console.log(de.dim(` Backup: ${t}`)),console.log(de.dim(` Restart the daemon (or POST /reload) for the change to take effect.
570
- `))}function bi(){try{return T().business||{}}catch{return{}}}var hn=new y$().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");hn.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=bi();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(de.yellow(" business block not enabled (or missing).")),console.log(de.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(de.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(de.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?de.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?de.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${de.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(de.bold(` Projects (${n.length})`)),n.length===0)console.log(de.dim(" (empty)"));else for(let r of n){let a=r.pm?de.dim(` \xB7 pm=${r.pm}`):"",c=r.client?de.dim(` \xB7 client=${r.client}`):"";console.log(` ${de.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(de.bold(` Contact map (${s.length})`)),s.length===0)console.log(de.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(` ${de.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?de.dim(` (${r.displayName})`):""}`)}console.log()});var aa=hn.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");aa.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=bi(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(de.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${de.cyan(n)} ${s.role}${s.reportsTo?de.dim(` \u2192 ${s.reportsTo}`):""}`)});aa.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);fn(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}`:""})`))});aa.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{fn(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 ca=hn.command("project").description("manage business.projects \u2014 id, pm, client");ca.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=bi().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(de.dim(" no projects"));return}for(let n of t)console.log(` ${de.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});ca.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)=>{fn(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`})});ca.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{fn(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 la=hn.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");la.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=bi().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(de.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+"/":""}${de.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});la.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(de.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),fn(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`})});la.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=>{fn(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 w$}from"commander";import We from"chalk";te();var $$={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function da(e){let o=$$[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function ki(){let o=T().business?.standup?.plansDir||".agentx/plans";return new ql(o)}var yn=new w$().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");yn.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=da(e),n=ki(),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(`
571
- `):(console.error(We.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(We.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=tr(s);if(r.length){console.log(We.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(We.dim(` \u2022 ${a}`))}});yn.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=ki();if(e){let n=da(e),s=o.read(n);if(!s){console.log(We.dim(` No ${n} plan set.`));return}Zm(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(We.yellow(" No plan set at any tier.")),console.log(We.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(We.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Zm(t.tier,t.date,t.content)});yn.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=ki().list(parseInt(e.limit,10)||20);if(!t.length){console.log(We.dim(" No plans yet."));return}for(let n of t)console.log(` ${We.cyan(n.tier.padEnd(5))} ${We.bold(n.date.padEnd(11))} ${We.dim(n.path)}`)});yn.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=da(e),n=ki().read(o);if(!n){console.log(We.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(We.green(` \u2713 ${o} plan cleared (${n.path})`))});function Zm(e,o,t){console.log(We.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
572
- `))console.log(` ${s}`);console.log();let n=tr(t);n.length&&console.log(We.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as b$}from"commander";import K from"chalk";te();function k$(){try{return T().notifications||{}}catch{return{}}}function v$(){try{return T().channels?.ntfy}catch{return}}function x$(){try{return T().channels?.push}catch{return}}function wn(e){let{summary:o,backupPath:t}=so(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(K.green(`
575
+ `))}function ki(){try{return T().business||{}}catch{return{}}}var yn=new q$().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");yn.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=ki();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(de.yellow(" business block not enabled (or missing).")),console.log(de.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(de.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(de.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?de.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?de.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${de.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(de.bold(` Projects (${n.length})`)),n.length===0)console.log(de.dim(" (empty)"));else for(let r of n){let a=r.pm?de.dim(` \xB7 pm=${r.pm}`):"",c=r.client?de.dim(` \xB7 client=${r.client}`):"";console.log(` ${de.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(de.bold(` Contact map (${s.length})`)),s.length===0)console.log(de.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(` ${de.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?de.dim(` (${r.displayName})`):""}`)}console.log()});var pa=yn.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");pa.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=ki(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(de.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${de.cyan(n)} ${s.role}${s.reportsTo?de.dim(` \u2192 ${s.reportsTo}`):""}`)});pa.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);hn(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}`:""})`))});pa.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{hn(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 ua=yn.command("project").description("manage business.projects \u2014 id, pm, client");ua.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=ki().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(de.dim(" no projects"));return}for(let n of t)console.log(` ${de.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});ua.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)=>{hn(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`})});ua.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{hn(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 fa=yn.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");fa.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=ki().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(de.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+"/":""}${de.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});fa.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(de.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),hn(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`})});fa.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=>{hn(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 F$}from"commander";import We from"chalk";te();var U$={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function ha(e){let o=U$[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function vi(){let o=T().business?.standup?.plansDir||".agentx/plans";return new Gl(o)}var wn=new F$().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");wn.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=ha(e),n=vi(),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(`
576
+ `):(console.error(We.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(We.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=nr(s);if(r.length){console.log(We.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(We.dim(` \u2022 ${a}`))}});wn.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=vi();if(e){let n=ha(e),s=o.read(n);if(!s){console.log(We.dim(` No ${n} plan set.`));return}mp(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(We.yellow(" No plan set at any tier.")),console.log(We.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(We.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}mp(t.tier,t.date,t.content)});wn.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=vi().list(parseInt(e.limit,10)||20);if(!t.length){console.log(We.dim(" No plans yet."));return}for(let n of t)console.log(` ${We.cyan(n.tier.padEnd(5))} ${We.bold(n.date.padEnd(11))} ${We.dim(n.path)}`)});wn.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=ha(e),n=vi().read(o);if(!n){console.log(We.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(We.green(` \u2713 ${o} plan cleared (${n.path})`))});function mp(e,o,t){console.log(We.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
577
+ `))console.log(` ${s}`);console.log();let n=nr(t);n.length&&console.log(We.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as W$}from"commander";import K from"chalk";te();function B$(){try{return T().notifications||{}}catch{return{}}}function J$(){try{return T().channels?.ntfy}catch{return}}function H$(){try{return T().channels?.push}catch{return}}function $n(e){let{summary:o,backupPath:t}=so(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(K.green(`
573
578
  \u2713 ${o}`)),t&&console.log(K.dim(` Backup: ${t}`)),console.log(K.dim(` Restart the daemon (or POST /reload) for the change to take effect.
574
- `))}var To=new b$().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");To.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=k$();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 ${K.cyan(o.destination.channel+":"+o.destination.chatId)}${K.dim(c)}`)}else console.log(` destination ${K.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${K.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?K.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?K.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":K.dim("off")}`);let n=vs(o.local);if(console.log(` local.banner ${n.banner?"on":K.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:K.dim("off")}`),console.log(` local.icon ${n.icon??K.dim("AgentX logo")}`),n.banner){let c=await Jl();c.state!=="unsupported"&&(console.log(` local.helper ${c.state==="ready"?c.message:K.yellow(c.message)}`),c.fix&&console.log(` ${K.dim("Fix: "+c.fix)}`))}let s;try{s=T()}catch{s=void 0}console.log(` channel ${Es(s)} ${K.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=Hi(x$()),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":K.dim("off")} ${K.dim(r)}`);let a=ir(v$());console.log(` ntfy ${a.enabled?"on":K.dim("off")} ${K.dim(`${a.server} \xB7 topic ${a.topicSet?"set":"unset"} \xB7 token ${a.tokenSet?"set":"unset"}`)}`),console.log()});To.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){wn(o=>(delete o.destination,"notifications destination cleared"));return}wn(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})`:""}`))});To.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(K.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(K.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";wn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});To.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(K.red(" threshold must be a non-negative integer")),process.exit(1)),wn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});To.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(K.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(K.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{wn(n=>(n.local=Jc(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(K.dim(` Run agentx desktop install to put the new icon on the helper.
575
- `))}catch(n){console.log(K.red(` ${n?.message??n}`)),process.exit(1)}});To.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(K.red(` not a channel name: ${e}`)),process.exit(1)),wn(t=>(t.channel=o,`notifications.channel = ${o}`))});To.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(K.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=so(s=>{s.channels=s.channels||{},s.channels.push=Qc(s.channels.push,o);let i=Hi(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(K.green(`
579
+ `))}var To=new W$().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");To.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=B$();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 ${K.cyan(o.destination.channel+":"+o.destination.chatId)}${K.dim(c)}`)}else console.log(` destination ${K.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${K.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?K.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?K.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":K.dim("off")}`);let n=xs(o.local);if(console.log(` local.banner ${n.banner?"on":K.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:K.dim("off")}`),console.log(` local.icon ${n.icon??K.dim("AgentX logo")}`),n.banner){let c=await Kl();c.state!=="unsupported"&&(console.log(` local.helper ${c.state==="ready"?c.message:K.yellow(c.message)}`),c.fix&&console.log(` ${K.dim("Fix: "+c.fix)}`))}let s;try{s=T()}catch{s=void 0}console.log(` channel ${As(s)} ${K.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=Gi(H$()),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":K.dim("off")} ${K.dim(r)}`);let a=ar(J$());console.log(` ntfy ${a.enabled?"on":K.dim("off")} ${K.dim(`${a.server} \xB7 topic ${a.topicSet?"set":"unset"} \xB7 token ${a.tokenSet?"set":"unset"}`)}`),console.log()});To.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){$n(o=>(delete o.destination,"notifications destination cleared"));return}$n(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})`:""}`))});To.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(K.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(K.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";$n(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});To.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(K.red(" threshold must be a non-negative integer")),process.exit(1)),$n(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});To.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(K.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(K.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{$n(n=>(n.local=Kc(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(K.dim(` Run agentx desktop install to put the new icon on the helper.
580
+ `))}catch(n){console.log(K.red(` ${n?.message??n}`)),process.exit(1)}});To.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(K.red(` not a channel name: ${e}`)),process.exit(1)),$n(t=>(t.channel=o,`notifications.channel = ${o}`))});To.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(K.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=so(s=>{s.channels=s.channels||{},s.channels.push=il(s.channels.push,o);let i=Gi(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(K.green(`
576
581
  \u2713 ${t}`)),n&&console.log(K.dim(` Backup: ${n}`)),console.log(K.dim(` Restart the daemon for a channel change to take effect.
577
- `))}catch(t){console.log(K.red(` ${t?.message??t}`)),process.exit(1)}});To.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(K.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=so(s=>{s.channels=s.channels||{},s.channels.ntfy=sd(s.channels.ntfy,o);let i=ir(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(K.green(`
582
+ `))}catch(t){console.log(K.red(` ${t?.message??t}`)),process.exit(1)}});To.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(K.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=so(s=>{s.channels=s.channels||{},s.channels.ntfy=pd(s.channels.ntfy,o);let i=ar(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(K.green(`
578
583
  \u2713 ${t}`)),n&&console.log(K.dim(` Backup: ${n}`)),console.log(K.dim(` Restart the daemon for a channel change to take effect.
579
- `))}catch(t){console.log(K.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as S$}from"commander";import tt from"chalk";import{readdirSync as ga,statSync as ep,unlinkSync as E$,rmSync as A$,existsSync as op}from"fs";import{resolve as tp,join as np}from"path";var sp=[{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 ma(e,o){if(!op(e))return[];let t=[];for(let n of ga(e,{withFileTypes:!0})){let s=np(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...ma(s,!0))}return t}var xi=new S$().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");xi.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of sp){let t=tp(process.cwd(),o.dir),n=ma(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=ep(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(` ${tt.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${vi(s).padStart(10)} oldest=${r}`)}console.log(tt.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${vi(e).padStart(10)} total`)),console.log(),console.log(tt.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});xi.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(tt.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(tt.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?tt.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of sp){if(n&&r.dir!==n)continue;let a=tp(process.cwd(),r.dir),c=ma(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=ep(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{E$(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{ip(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${tt.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${vi(g)})`),s+=l,i+=g}console.log(),console.log(tt.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${vi(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function ip(e){if(op(e))for(let o of ga(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=np(e,o.name);ip(t);try{ga(t).length===0&&A$(t,{recursive:!1})}catch{}}}function vi(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 nt=new T$().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");nt.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new _t().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()});nt.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new _t().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()});nt.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=j$(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=tc.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 _t().save(s.data);console.log(U.green(`
584
+ `))}catch(t){console.log(K.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as G$}from"commander";import tt from"chalk";import{readdirSync as ya,statSync as pp,unlinkSync as z$,rmSync as Y$,existsSync as up}from"fs";import{resolve as fp,join as hp}from"path";var yp=[{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 wa(e,o){if(!up(e))return[];let t=[];for(let n of ya(e,{withFileTypes:!0})){let s=hp(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...wa(s,!0))}return t}var Si=new G$().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Si.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of yp){let t=fp(process.cwd(),o.dir),n=wa(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=pp(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(` ${tt.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${xi(s).padStart(10)} oldest=${r}`)}console.log(tt.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${xi(e).padStart(10)} total`)),console.log(),console.log(tt.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Si.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(tt.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(tt.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?tt.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of yp){if(n&&r.dir!==n)continue;let a=fp(process.cwd(),r.dir),c=wa(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=pp(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{z$(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{wp(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${tt.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${xi(g)})`),s+=l,i+=g}console.log(),console.log(tt.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${xi(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function wp(e){if(up(e))for(let o of ya(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=hp(e,o.name);wp(t);try{ya(t).length===0&&Y$(t,{recursive:!1})}catch{}}}function xi(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 V$}from"commander";import U from"chalk";var nt=new V$().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");nt.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new Dt().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()});nt.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new Dt().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()});nt.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=X$(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=lc.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 Dt().save(s.data);console.log(U.green(`
580
585
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
581
- `))});nt.command("remove <id>").alias("rm").description("delete an action").action(e=>{new _t().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});nt.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 _t().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 nc(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)}});nt.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 j$(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}te();import{Command as O$}from"commander";import ie from"chalk";var rp=new O$().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(ie.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(ie.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(ie.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(`
586
+ `))});nt.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Dt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});nt.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 Dt().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 dc(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)}});nt.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 X$(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}te();import{Command as K$}from"commander";import ie from"chalk";var $p=new K$().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(ie.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(ie.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(ie.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(`
582
587
 
583
- `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),C$(f)}}}catch(r){console.error(ie.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function C$(e){let o="message",t="";for(let i of e.split(`
584
- `))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?ie.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ie.cyan(n.phase?.padEnd(9)??"run"),r=ie.bold(n.workflowId??""),a=ie.dim((n.runId??"").slice(0,8)),c=n.nodeId?ie.yellow(n.nodeId):"",l=n.note?ie.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ie.magenta(`task.${n.phase}`.padEnd(14)),r=ie.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ie.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ie.cyan(a)} ${c}`);break}case"signal":{let i=ie.green("signal".padEnd(9)),r=ie.bold(n.name),a=ie.dim(`(${n.scope})`),c=n.workflowId?ie.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ie.blue("mesh".padEnd(9)),r=ie.bold(n.peer),a=n.healthy?ie.green("\u2713 healthy"):ie.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ie.dim(n.delta??"")}`);break}case"channel":{let i=ie.yellow("channel".padEnd(9)),r=n.direction==="in"?ie.cyan("\u2190"):ie.magenta("\u2192"),a=ie.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ie.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ie.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)}`)}}te();import{Command as I$}from"commander";import $n from"chalk";function N$(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 ap=new I$().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(N$(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error($n.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error($n.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($n.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log($n.dim(" no events"));return}for(let a of i)console.log(` ${Za(a)} ${$n.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log($n.dim(`
585
- ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as _$}from"commander";import ss from"chalk";import{spawn as D$}from"node:child_process";import{execFileSync as R$}from"node:child_process";function cp(e=()=>R$("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 lp=new _$().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(ss.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-VYMTUZKN.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:cp();if(n?.ok){let{fetchAgents:l}=await import("./client-VYMTUZKN.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(b=>b.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(b=>[b.id,{name:`AgentX ${b.name||b.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(ss.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:b=>console.error(ss.dim(b))});return}n&&!n.ok&&(console.error(ss.yellow(n.reason)),console.error(ss.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-4VWAQOVA.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 Z from"chalk";import{randomUUID as mp}from"crypto";import{createInterface as M$}from"node:readline/promises";import L$ from"ora";import Si from"chalk";function dp(e){console.error(),console.error(Si.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Si.dim(` ${e.why}`)),console.error(),console.error(` Use ${Si.cyan(e.instead)} instead.`),e.note&&console.error(Si.dim(` ${e.note}`)),console.error()}var gp={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 pp=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)=>{dp({what:"agentx chat",...gp});let t=rd({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${mp().slice(0,12)}`,r=[];try{r=await Ds(t)}catch(g){console.error(Z.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(Z.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(Z.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(Z.red(` unknown agent: @${n}`)),console.error(Z.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(Z.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-KOTGUDZH.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}U$(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(Z.dim(`
586
- bye`)),process.exit(0)});;){let g;try{g=(await a.question(Z.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(Z.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${mp().slice(0,12)}`,console.log(Z.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Ds(t);for(let y of p){let w=y.id===n?Z.green("\u25CF"):Z.dim("\u25CB");console.log(` ${w} @${y.id} ${Z.dim(y.tier)} ${y.model??""}`)}}catch(p){console.error(Z.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(Z.red(" usage: /agent <id>"));continue}try{if(!(await Ds(t)).find(w=>w.id===p)){console.log(Z.red(` unknown agent: @${p}`));continue}n=p,console.log(Z.dim(` now talking to @${n}`))}catch(y){console.error(Z.red(` failed to switch agent: ${y?.message||y}`))}continue}if(g.startsWith("/")){console.log(Z.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(Z.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=L$({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=q$(n);try{let p=await ad(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(Z.dim(" bye"));return}}});function q$(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${Z.green(`@${e}`)}
588
+ `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),Q$(f)}}}catch(r){console.error(ie.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Q$(e){let o="message",t="";for(let i of e.split(`
589
+ `))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?ie.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ie.cyan(n.phase?.padEnd(9)??"run"),r=ie.bold(n.workflowId??""),a=ie.dim((n.runId??"").slice(0,8)),c=n.nodeId?ie.yellow(n.nodeId):"",l=n.note?ie.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ie.magenta(`task.${n.phase}`.padEnd(14)),r=ie.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ie.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ie.cyan(a)} ${c}`);break}case"signal":{let i=ie.green("signal".padEnd(9)),r=ie.bold(n.name),a=ie.dim(`(${n.scope})`),c=n.workflowId?ie.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ie.blue("mesh".padEnd(9)),r=ie.bold(n.peer),a=n.healthy?ie.green("\u2713 healthy"):ie.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ie.dim(n.delta??"")}`);break}case"channel":{let i=ie.yellow("channel".padEnd(9)),r=n.direction==="in"?ie.cyan("\u2190"):ie.magenta("\u2192"),a=ie.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ie.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ie.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)}`)}}te();import{Command as Z$}from"commander";import bn from"chalk";function eb(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 bp=new Z$().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(eb(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(bn.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(bn.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(bn.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(bn.dim(" no events"));return}for(let a of i)console.log(` ${rc(a)} ${bn.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(bn.dim(`
590
+ ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as tb}from"commander";import is from"chalk";import{spawn as nb}from"node:child_process";import{execFileSync as ob}from"node:child_process";function kp(e=()=>ob("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 vp=new tb().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(is.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-O7SPKO5X.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:kp();if(n?.ok){let{fetchAgents:l}=await import("./client-O7SPKO5X.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(b=>b.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(b=>[b.id,{name:`AgentX ${b.name||b.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(is.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:nb,log:b=>console.error(is.dim(b))});return}n&&!n.ok&&(console.error(is.yellow(n.reason)),console.error(is.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-T4Q7SW6M.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 sb}from"commander";import Z from"chalk";import{randomUUID as Ep}from"crypto";import{createInterface as ib}from"node:readline/promises";import rb from"ora";import Ei from"chalk";function xp(e){console.error(),console.error(Ei.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Ei.dim(` ${e.why}`)),console.error(),console.error(` Use ${Ei.cyan(e.instead)} instead.`),e.note&&console.error(Ei.dim(` ${e.note}`)),console.error()}var Sp={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 Ap=new sb().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)=>{xp({what:"agentx chat",...Sp});let t=fd({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Ep().slice(0,12)}`,r=[];try{r=await Ps(t)}catch(g){console.error(Z.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(Z.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(Z.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(Z.red(` unknown agent: @${n}`)),console.error(Z.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(Z.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-BKUJUIDL.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}cb(t.baseUrl,n,i,s);let a=ib({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(Z.dim(`
591
+ bye`)),process.exit(0)});;){let g;try{g=(await a.question(Z.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(Z.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${Ep().slice(0,12)}`,console.log(Z.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Ps(t);for(let y of p){let w=y.id===n?Z.green("\u25CF"):Z.dim("\u25CB");console.log(` ${w} @${y.id} ${Z.dim(y.tier)} ${y.model??""}`)}}catch(p){console.error(Z.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(Z.red(" usage: /agent <id>"));continue}try{if(!(await Ps(t)).find(w=>w.id===p)){console.log(Z.red(` unknown agent: @${p}`));continue}n=p,console.log(Z.dim(` now talking to @${n}`))}catch(y){console.error(Z.red(` failed to switch agent: ${y?.message||y}`))}continue}if(g.startsWith("/")){console.log(Z.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(Z.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=rb({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=ab(n);try{let p=await hd(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(Z.dim(" bye"));return}}});function ab(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${Z.green(`@${e}`)}
587
592
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
588
593
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
589
594
  `&&(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(`
@@ -598,17 +603,17 @@ agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let H=await fetch(
598
603
  `))},finishError(r){o&&!t&&process.stdout.write(`
599
604
  `),process.stdout.write(Z.red(` \u2717 ${r}
600
605
 
601
- `))}}}function U$(e,o,t,n){console.log(),console.log(Z.bold(" agentx chat")),console.log(Z.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(Z.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as F$}from"commander";import oe from"chalk";import{readFileSync as W$}from"fs";import{existsSync as B$,readdirSync as J$}from"fs";import{resolve as H$}from"path";var Ei=["user","feedback","project","reference"],st=new F$().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");st.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(!Ei.includes(e.type)){console.error(oe.red(` --type must be one of: ${Ei.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await G$();else try{o=W$(e.file,"utf-8")}catch(s){console.error(oe.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(oe.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new It().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(oe.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});st.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 It().list(e.agent);if(e.type){if(!Ei.includes(e.type)){console.error(oe.red(` --type must be one of: ${Ei.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(oe.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(oe.bold(` ${s.type}`)),n=s.type),console.log(` ${oe.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(oe.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});st.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 It().get(o.agent,e);if(!n){console.error(oe.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(oe.bold(`${n.type}/${n.name}`)+oe.dim(` (${n.description})`)),console.log(oe.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});st.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new It().remove(o.agent,e)){console.error(oe.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(oe.green(` \u2713 memory "${e}" removed`))});st.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 It().indexMarkdown(e.agent);if(!t){console.log(oe.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var is=st.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function Ai(e){if(e)return[e];let o=H$(process.cwd(),".agentx/memory");return B$(o)?J$(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}is.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 Ct;for(let t of Ai(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${oe.bold(t)} ${n||oe.dim("(none)")}`)}});is.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Ct,t=0;for(let n of Ai(e.agent))for(let s of o.held(n))t++,console.log(` ${oe.bold(n)} ${oe.cyan(s.id)} ${oe.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(oe.dim(" nothing held"))});for(let e of["approve","reject"])is.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 Ct().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(oe.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(oe.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});is.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 Ct,t=0;for(let n of Ai(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${oe.bold(n)} ${s}`),t+=s}console.log(e.apply?oe.green(` \u2713 deleted ${t} fact(s) containing credentials`):oe.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});is.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 Ct,n=0;for(let s of Ai(e.agent)){let i=o(t,s,{apply:!!e.apply});if(i.flagged.length!==0){n+=i.flagged.length,console.log(` ${oe.bold(s)} ${i.flagged.length}${i.backup?oe.dim(` (backup: ${i.backup})`):""}`);for(let r of i.flagged.slice(0,10))console.log(oe.dim(` ${r.id} [${r.volatility}] ${r.content.slice(0,100)}`))}}console.log(e.apply?oe.green(` \u2713 flagged ${n} fact(s) as unverified`):oe.dim(` ${n} fact(s) state billing, account, outage or deploy state with no source. Run with --apply to flag them.`))});async function G$(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Wp();import pa from"chalk";import{Command as z$}from"commander";import{resolve as Y$}from"path";var up=new z$().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(Y$(e.cwd)),e.stdio!==!1?await Sc():(jo.error("Only stdio transport is currently supported."),jo.info(`Usage: ${pa.green("agentx serve --stdio")} or configure in your MCP client.`),jo.break(),jo.info("Add to Claude Code:"),jo.info(pa.dim(" claude mcp add agentx -- npx agentx serve --stdio")),jo.break(),jo.info("Add to Cursor/MCP config:"),jo.info(pa.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Wl(o)}});import{Command as nb}from"commander";import ge from"chalk";import{spawn as bp}from"child_process";import{mkdirSync as sb,writeFileSync as Oi,readFileSync as ib,readdirSync as rb,rmSync as kp,openSync as vp,existsSync as Ti}from"fs";import{resolve as ab,join as Be}from"path";import{randomBytes as cb}from"crypto";var fp={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"}]};te();import{existsSync as V$,readFileSync as X$}from"fs";import{cpus as K$,loadavg as Q$}from"os";import{resolve as Z$}from"path";var hp="AGENTX_DEMO_STARTUP_TIMEOUT",eb=60,ob=300;function tb(e,o){let t=Math.max(1,e/Math.max(1,o));return Math.min(ob,Math.ceil(eb*t))}function yp(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 wp(e){let o=Z$(e,"agentx.json");if(!V$(o))return;let t;try{t=JSON.parse(X$(o,"utf8"))}catch{return}let n=Pa.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 $p(e){let o=yp(e.flag,"--startup-timeout");if(o!==void 0)return{seconds:o,source:"--startup-timeout"};let t=yp(e.env,hp);if(t!==void 0)return{seconds:t,source:hp};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??Q$()[0],s=e.cpuCount??K$().length;return{seconds:tb(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var xp="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",lb="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function db(e,o){return[{dir:Be(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(fp,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:Be(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:Be(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 gb(e,o,t){let n=Be(e.dir,"workspaces",e.agentId);sb(n,{recursive:!0}),Oi(Be(n,"CLAUDE.md"),`# ${e.agentName}
606
+ `))}}}function cb(e,o,t,n){console.log(),console.log(Z.bold(" agentx chat")),console.log(Z.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(Z.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as lb}from"commander";import oe from"chalk";import{readFileSync as db}from"fs";import{existsSync as gb,readdirSync as mb}from"fs";import{resolve as pb}from"path";var Ai=["user","feedback","project","reference"],st=new lb().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");st.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(!Ai.includes(e.type)){console.error(oe.red(` --type must be one of: ${Ai.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await ub();else try{o=db(e.file,"utf-8")}catch(s){console.error(oe.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(oe.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Nt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(oe.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});st.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 Nt().list(e.agent);if(e.type){if(!Ai.includes(e.type)){console.error(oe.red(` --type must be one of: ${Ai.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(oe.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(oe.bold(` ${s.type}`)),n=s.type),console.log(` ${oe.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(oe.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});st.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 Nt().get(o.agent,e);if(!n){console.error(oe.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(oe.bold(`${n.type}/${n.name}`)+oe.dim(` (${n.description})`)),console.log(oe.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});st.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Nt().remove(o.agent,e)){console.error(oe.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(oe.green(` \u2713 memory "${e}" removed`))});st.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 Nt().indexMarkdown(e.agent);if(!t){console.log(oe.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var rs=st.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function Ti(e){if(e)return[e];let o=pb(process.cwd(),".agentx/memory");return gb(o)?mb(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}rs.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 It;for(let t of Ti(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${oe.bold(t)} ${n||oe.dim("(none)")}`)}});rs.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new It,t=0;for(let n of Ti(e.agent))for(let s of o.held(n))t++,console.log(` ${oe.bold(n)} ${oe.cyan(s.id)} ${oe.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(oe.dim(" nothing held"))});for(let e of["approve","reject"])rs.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 It().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(oe.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(oe.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});rs.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 It,t=0;for(let n of Ti(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${oe.bold(n)} ${s}`),t+=s}console.log(e.apply?oe.green(` \u2713 deleted ${t} fact(s) containing credentials`):oe.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});rs.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 It,n=0;for(let s of Ti(e.agent)){let i=o(t,s,{apply:!!e.apply});if(i.flagged.length!==0){n+=i.flagged.length,console.log(` ${oe.bold(s)} ${i.flagged.length}${i.backup?oe.dim(` (backup: ${i.backup})`):""}`);for(let r of i.flagged.slice(0,10))console.log(oe.dim(` ${r.id} [${r.volatility}] ${r.content.slice(0,100)}`))}}console.log(e.apply?oe.green(` \u2713 flagged ${n} fact(s) as unverified`):oe.dim(` ${n} fact(s) state billing, account, outage or deploy state with no source. Run with --apply to flag them.`))});async function ub(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}ou();import $a from"chalk";import{Command as fb}from"commander";import{resolve as hb}from"path";var Tp=new fb().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(hb(e.cwd)),e.stdio!==!1?await Ic():(jo.error("Only stdio transport is currently supported."),jo.info(`Usage: ${$a.green("agentx serve --stdio")} or configure in your MCP client.`),jo.break(),jo.info("Add to Claude Code:"),jo.info($a.dim(" claude mcp add agentx -- npx agentx serve --stdio")),jo.break(),jo.info("Add to Cursor/MCP config:"),jo.info($a.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Vl(o)}});import{Command as Eb}from"commander";import ge from"chalk";import{spawn as Rp}from"child_process";import{mkdirSync as Ab,writeFileSync as Ci,readFileSync as Tb,readdirSync as jb,rmSync as _p,openSync as Dp,existsSync as ji}from"fs";import{resolve as Ob,join as Be}from"path";import{randomBytes as Cb}from"crypto";var jp={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"}]};te();import{existsSync as yb,readFileSync as wb}from"fs";import{cpus as $b,loadavg as bb}from"os";import{resolve as kb}from"path";var Op="AGENTX_DEMO_STARTUP_TIMEOUT",vb=60,xb=300;function Sb(e,o){let t=Math.max(1,e/Math.max(1,o));return Math.min(xb,Math.ceil(vb*t))}function Cp(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 Ip(e){let o=kb(e,"agentx.json");if(!yb(o))return;let t;try{t=JSON.parse(wb(o,"utf8"))}catch{return}let n=Ba.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 Np(e){let o=Cp(e.flag,"--startup-timeout");if(o!==void 0)return{seconds:o,source:"--startup-timeout"};let t=Cp(e.env,Op);if(t!==void 0)return{seconds:t,source:Op};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??bb()[0],s=e.cpuCount??$b().length;return{seconds:Sb(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var Pp="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Ib="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Nb(e,o){return[{dir:Be(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(jp,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:Be(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:Be(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 Rb(e,o,t){let n=Be(e.dir,"workspaces",e.agentId);Ab(n,{recursive:!0}),Ci(Be(n,"CLAUDE.md"),`# ${e.agentName}
602
607
 
603
608
  ${e.persona}
604
- `),Oi(Be(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}};Oi(Be(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function ua(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 fa(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function ha(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 ji(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
609
+ `),Ci(Be(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}};Ci(Be(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function ba(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 ka(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function va(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 Oi(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
605
610
  `).join(`
606
- `)}`)}var Sp=new nb().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=ab(process.cwd(),".agentx-demo"),n;try{n=$p({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:wp(process.cwd())})}catch(y){console.error(ge.red(y.message)),process.exit(1)}let s=n.seconds*1e3,i=db(t,o),r=Be(t,"mesh-token"),a=!!e.reuse&&Ti(r)&&Ti(Be(i[0].dir,"agentx.json")),c=a?ib(r,"utf8").trim():cb(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!Ti(d))&&(console.error(ge.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if(Ti(t))for(let y of rb(t))kp(Be(t,y),{recursive:!0,force:!0});for(let y of i)gb(y,i,c);Oi(r,c+`
607
- `,{mode:384})}console.log(),console.log(ge.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ge.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ge.dim(" Run `agentx setup` to wire real agents.\n")),console.log(ge.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{kp(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=vp(Be($.dir,"daemon.log"),"a"),S=bp(process.execPath,[d,"daemon","start","-c",Be($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:Be($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(ge.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${Be($.dir,"daemon.log")})`))}let y=$=>ua(`${$.name} /health`,async()=>(await fa(`http://127.0.0.1:${$.port}/health`)).ok,s);await y(i[0]);let w=i[0].port+10;{let $=vp(Be(i[0].dir,"board.log"),"a"),E=bp(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(ge.green(" \u2713 three daemons up")),await ua("dashboard /live",async()=>(await fa(`http://127.0.0.1:${w}/live`)).ok,s),console.log(ge.green(" \u2713 dashboard up")),await ua("mesh discovery (laptop sees both peers)",async()=>((await(await fa(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,s),console.log(ge.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let b=`http://127.0.0.1:${w}/live`;console.log(),console.log(` Dashboard: ${ge.cyan(b)} (all three nodes via the mesh)`),console.log(ge.dim(` Daemon APIs: ${i.map($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1&&dt(b);let k=async()=>{console.log(),console.log(ge.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),ji("You \u2192 @cx (laptop-paris)",xp,ge.cyan);let $=await ha(i[0].port,"/task",{agent:"cx",message:xp});ji("@cx (laptop-paris)",$.content||"(no content)",ge.green),console.log(),console.log(ge.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await ha(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:lb}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";ji("@builder (vps-nyc)",S,ge.yellow);let v=await ha(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});ji("@cx (laptop-paris)",v.content||"(no content)",ge.green),console.log(),console.log(ge.dim(` Inspect the run: ${b} \xB7 ledger rows on each node record every dispatch`)),console.log(ge.dim(` Worth your time? A star helps others find it: ${ge.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(ge.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await k(),e.once){console.log(),console.log(ge.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(ge.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{k().catch($=>console.error(ge.red(` Replay failed: ${$.message}`)))}),process.stdin.resume()}catch(y){console.error(),console.error(ge.red(` Demo failed: ${y.message}`)),console.error(ge.dim(` Node logs: ${i.map(w=>Be(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as mb}from"commander";import{randomUUID as pb}from"crypto";import{readFileSync as ub}from"fs";import{resolve as fb}from"path";te();var Ep=new mb().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").option("--channel <name>","channel name the task runs under, as a channel adapter would set it","exec").option("--chat-id <id>","chat id for the session (default: a fresh one), so repeated runs share a history").option("--profile <full|lean>","session profile for this run's channel, overriding session.profileByChannel").action(async(e,o)=>{let t=(e??ub(0,"utf8")).trim();t||ya("no task given (pass it as an argument or on stdin)");let n=T(o.config?fb(o.config):void 0),s=n.agents[o.agent];s||ya(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`),o.profile!==void 0&&o.profile!=="full"&&o.profile!=="lean"&&ya(`--profile must be full or lean, not "${o.profile}"`),o.profile&&(n.session.profileByChannel={...n.session.profileByChannel,[o.channel]:o.profile});let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Ya(o.agent,s,l,i)}let r=new pc(n,i);try{let l=new fl(n);l.build(),r.setLandscape(l)}catch(l){i(`no landscape: ${l?.message??l}`)}let 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:o.channel,chatId:o.chatId||`exec-${pb()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,costUsd:c.costUsd,billedModel:c.billedModel,durationMs:Date.now()-a})+`
611
+ `)}`)}var Mp=new Eb().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=Ob(process.cwd(),".agentx-demo"),n;try{n=Np({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:Ip(process.cwd())})}catch(y){console.error(ge.red(y.message)),process.exit(1)}let s=n.seconds*1e3,i=Nb(t,o),r=Be(t,"mesh-token"),a=!!e.reuse&&ji(r)&&ji(Be(i[0].dir,"agentx.json")),c=a?Tb(r,"utf8").trim():Cb(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!ji(d))&&(console.error(ge.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if(ji(t))for(let y of jb(t))_p(Be(t,y),{recursive:!0,force:!0});for(let y of i)Rb(y,i,c);Ci(r,c+`
612
+ `,{mode:384})}console.log(),console.log(ge.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ge.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ge.dim(" Run `agentx setup` to wire real agents.\n")),console.log(ge.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{_p(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=Dp(Be($.dir,"daemon.log"),"a"),S=Rp(process.execPath,[d,"daemon","start","-c",Be($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:Be($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(ge.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${Be($.dir,"daemon.log")})`))}let y=$=>ba(`${$.name} /health`,async()=>(await ka(`http://127.0.0.1:${$.port}/health`)).ok,s);await y(i[0]);let w=i[0].port+10;{let $=Dp(Be(i[0].dir,"board.log"),"a"),E=Rp(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(ge.green(" \u2713 three daemons up")),await ba("dashboard /live",async()=>(await ka(`http://127.0.0.1:${w}/live`)).ok,s),console.log(ge.green(" \u2713 dashboard up")),await ba("mesh discovery (laptop sees both peers)",async()=>((await(await ka(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,s),console.log(ge.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let b=`http://127.0.0.1:${w}/live`;console.log(),console.log(` Dashboard: ${ge.cyan(b)} (all three nodes via the mesh)`),console.log(ge.dim(` Daemon APIs: ${i.map($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1&&dt(b);let k=async()=>{console.log(),console.log(ge.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Oi("You \u2192 @cx (laptop-paris)",Pp,ge.cyan);let $=await va(i[0].port,"/task",{agent:"cx",message:Pp});Oi("@cx (laptop-paris)",$.content||"(no content)",ge.green),console.log(),console.log(ge.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await va(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Ib}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";Oi("@builder (vps-nyc)",S,ge.yellow);let v=await va(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});Oi("@cx (laptop-paris)",v.content||"(no content)",ge.green),console.log(),console.log(ge.dim(` Inspect the run: ${b} \xB7 ledger rows on each node record every dispatch`)),console.log(ge.dim(` Worth your time? A star helps others find it: ${ge.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(ge.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await k(),e.once){console.log(),console.log(ge.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(ge.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{k().catch($=>console.error(ge.red(` Replay failed: ${$.message}`)))}),process.stdin.resume()}catch(y){console.error(),console.error(ge.red(` Demo failed: ${y.message}`)),console.error(ge.dim(` Node logs: ${i.map(w=>Be(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as _b}from"commander";import{randomUUID as Db}from"crypto";import{readFileSync as Pb}from"fs";import{resolve as Mb}from"path";te();var Lp=new _b().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").option("--channel <name>","channel name the task runs under, as a channel adapter would set it","exec").option("--chat-id <id>","chat id for the session (default: a fresh one), so repeated runs share a history").option("--profile <full|lean>","session profile for this run's channel, overriding session.profileByChannel").action(async(e,o)=>{let t=(e??Pb(0,"utf8")).trim();t||xa("no task given (pass it as an argument or on stdin)");let n=T(o.config?Mb(o.config):void 0),s=n.agents[o.agent];s||xa(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`),o.profile!==void 0&&o.profile!=="full"&&o.profile!=="lean"&&xa(`--profile must be full or lean, not "${o.profile}"`),o.profile&&(n.session.profileByChannel={...n.session.profileByChannel,[o.channel]:o.profile});let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";oc(o.agent,s,l,i)}let r=new bc(n,i);try{let l=new vl(n);l.build(),r.setLandscape(l)}catch(l){i(`no landscape: ${l?.message??l}`)}let 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:o.channel,chatId:o.chatId||`exec-${Db()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,costUsd:c.costUsd,billedModel:c.billedModel,durationMs:Date.now()-a})+`
608
613
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
609
- `),process.exit(c.error?1:0)});function ya(e){console.error(`agentx exec: ${e}`),process.exit(1)}te();import{Command as yb}from"commander";import De from"chalk";import{Command as hb}from"commander";import _e from"chalk";te();ps();var At=new hb("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function rs(e){let o="",t=await re(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(_e.red(`\u2717 ${t.error}`)),process.exit(1)),console.log(_e.green(`\u2713 ${o}`)),t.reloaded&&console.log(_e.dim(" daemon hot-reloaded"))}function Tp(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];At.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?_e.green("on"):_e.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${o?_e.green("set in this shell"):_e.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(_e.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?_e.green("\u25CF"):_e.dim("\u25CB")} ${_e.bold(t.id)} \u2192 ${t.agent}${n}${t.autoAck?" \xB7 autoAck":""}`),t.chats.length&&console.log(_e.dim(` chats: ${t.chats.join(", ")}`)),t.senders.length&&console.log(_e.dim(` senders: ${t.senders.join(", ")}`))}console.log()});At.command("on").description("turn triage on").action(()=>rs(e=>(e.enabled=!0,"WhatsApp triage is on")));At.command("off").description("turn triage off").action(()=>rs(e=>(e.enabled=!1,"WhatsApp triage is off")));At.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let o=qo();o||(console.error(_e.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let t=new Tl(o).recent(Math.max(1,Number(e.limit)||20));if(t.length===0){console.log(_e.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?_e.red(n.error):`${_e.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${_e.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?_e.dim(` draft whatsapp:${n.draftId}`):""}`)}});var wa=At.command("rule").description("add, remove, enable or disable a watch rule");wa.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)=>rs((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}`}));wa.command("remove <id>").description("delete a watch rule").action(e=>rs(o=>(Tp(o,e),o.rules=o.rules.filter(t=>t.id!==e),`removed watch rule "${e}"`)));for(let[e,o]of[["enable",!0],["disable",!1]])wa.command(`${e} <id>`).description(`${e} a watch rule`).action(t=>rs(n=>(Tp(n,t).enabled=o,`watch rule "${t}" ${o?"enabled":"disabled"}`)));var Mo=new yb().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Mo.addCommand(At);Mo.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 as("/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(De.dim(" no chats cached yet"));return}console.log(),console.log(De.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?De.cyan("group"):De.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${De.dim(n.jid.padEnd(40))} ${De.dim(i)}`)}console.log()}catch(o){bn(o)}});Mo.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 as("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(De.dim(" no contacts cached yet"));return}console.log(),console.log(De.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} ${De.dim(i)} ${De.dim(n.jid)}`)}console.log()}catch(o){bn(o)}});Mo.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 ba("/whatsapp/ingest",o);$a(t,!!e.dryRun)}catch(o){bn(o)}});Mo.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 ba("/whatsapp/ingest",t);$a(n,!!o.dryRun)}catch(t){bn(t)}});Mo.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 ba("/whatsapp/ingest",t);$a(n,!!o.dryRun)}catch(t){bn(t)}});Mo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await as("/whatsapp/state"),o=await as("/whatsapp/chats"),t=await as("/whatsapp/contacts");console.log(),console.log(De.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){bn(e)}});function $a(e,o){if(console.log(),console.log(De.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(De.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(De.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(De.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(De.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(De.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function jp(){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 as(e){let o=await fetch(`${jp()}${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 ba(e,o){let t=await fetch(`${jp()}${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 bn(e){console.error(De.red(` ${e.message||e}`)),process.exit(1)}te();import{Command as wb}from"commander";import ue from"chalk";import{existsSync as $b,mkdirSync as Op,writeFileSync as cs}from"fs";import{join as kn,resolve as bb}from"path";var ls=new wb().name("plugin").description("manage agentx plugins (Move B)");ls.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(ue.dim(" No plugins configured.")),console.log(ue.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ue.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ue.cyan(t)}`);console.log(),console.log(ue.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ue.red(` ${e.message}`)),process.exitCode=1}});ls.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(ue.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=bb(o.cwd,t);$b(n)&&!o.force&&(console.log(ue.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Op(n,{recursive:!0}),Op(kn(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;cs(kn(n,"package.json"),Sb(e,s)),cs(kn(n,"tsconfig.json"),Eb()),cs(kn(n,"src/index.ts"),Ab(e)),cs(kn(n,"README.md"),Tb(e,s)),cs(kn(n,".gitignore"),jb()),console.log(),console.log(ue.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ue.bold(" Next steps:")),console.log(ue.dim(` cd ${t}`)),console.log(ue.dim(" pnpm install")),console.log(ue.dim(" pnpm build")),console.log(ue.dim(" pnpm link --global # for local testing")),console.log(ue.dim(" # then in your agentx project:")),console.log(ue.dim(` pnpm link --global ${e}`)),console.log(ue.dim(` agentx config set plugins[0] "${e}"`)),console.log(ue.dim(" agentx plugin doctor")),console.log()});ls.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(ue.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await kb(n);s.kind==="ok"?console.log(` ${ue.green("\u2713")} ${ue.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ue.red("\u2717")} ${ue.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ue.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ue.red(` ${e.message}`)),process.exitCode=1}});async function kb(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=vb(o);if(!xb(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=rl.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 vb(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 xb(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Sb(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)+`
610
- `}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)+`
611
- `}function Ab(e){return`// ${e} \u2014 AgentX plugin
614
+ `),process.exit(c.error?1:0)});function xa(e){console.error(`agentx exec: ${e}`),process.exit(1)}te();import{Command as qb}from"commander";import De from"chalk";import{Command as Lb}from"commander";import _e from"chalk";te();us();var Tt=new Lb("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function as(e){let o="",t=await re(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(_e.red(`\u2717 ${t.error}`)),process.exit(1)),console.log(_e.green(`\u2713 ${o}`)),t.reloaded&&console.log(_e.dim(" daemon hot-reloaded"))}function Fp(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 qp=(e,o=[])=>[...o,e];Tt.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?_e.green("on"):_e.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${o?_e.green("set in this shell"):_e.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(_e.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?_e.green("\u25CF"):_e.dim("\u25CB")} ${_e.bold(t.id)} \u2192 ${t.agent}${n}${t.autoAck?" \xB7 autoAck":""}`),t.chats.length&&console.log(_e.dim(` chats: ${t.chats.join(", ")}`)),t.senders.length&&console.log(_e.dim(` senders: ${t.senders.join(", ")}`))}console.log()});Tt.command("on").description("turn triage on").action(()=>as(e=>(e.enabled=!0,"WhatsApp triage is on")));Tt.command("off").description("turn triage off").action(()=>as(e=>(e.enabled=!1,"WhatsApp triage is off")));Tt.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let o=qo();o||(console.error(_e.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let t=new _l(o).recent(Math.max(1,Number(e.limit)||20));if(t.length===0){console.log(_e.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?_e.red(n.error):`${_e.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${_e.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?_e.dim(` draft whatsapp:${n.draftId}`):""}`)}});var Sa=Tt.command("rule").description("add, remove, enable or disable a watch rule");Sa.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)",qp).option("--sender <jid>","only messages from this person (repeatable)",qp).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)=>as((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}`}));Sa.command("remove <id>").description("delete a watch rule").action(e=>as(o=>(Fp(o,e),o.rules=o.rules.filter(t=>t.id!==e),`removed watch rule "${e}"`)));for(let[e,o]of[["enable",!0],["disable",!1]])Sa.command(`${e} <id>`).description(`${e} a watch rule`).action(t=>as(n=>(Fp(n,t).enabled=o,`watch rule "${t}" ${o?"enabled":"disabled"}`)));var Mo=new qb().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Mo.addCommand(Tt);Mo.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 cs("/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(De.dim(" no chats cached yet"));return}console.log(),console.log(De.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?De.cyan("group"):De.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${De.dim(n.jid.padEnd(40))} ${De.dim(i)}`)}console.log()}catch(o){kn(o)}});Mo.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 cs("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(De.dim(" no contacts cached yet"));return}console.log(),console.log(De.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} ${De.dim(i)} ${De.dim(n.jid)}`)}console.log()}catch(o){kn(o)}});Mo.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 Aa("/whatsapp/ingest",o);Ea(t,!!e.dryRun)}catch(o){kn(o)}});Mo.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 Aa("/whatsapp/ingest",t);Ea(n,!!o.dryRun)}catch(t){kn(t)}});Mo.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 Aa("/whatsapp/ingest",t);Ea(n,!!o.dryRun)}catch(t){kn(t)}});Mo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await cs("/whatsapp/state"),o=await cs("/whatsapp/chats"),t=await cs("/whatsapp/contacts");console.log(),console.log(De.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){kn(e)}});function Ea(e,o){if(console.log(),console.log(De.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(De.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(De.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(De.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(De.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(De.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Up(){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 cs(e){let o=await fetch(`${Up()}${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 Aa(e,o){let t=await fetch(`${Up()}${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 kn(e){console.error(De.red(` ${e.message||e}`)),process.exit(1)}te();import{Command as Fb}from"commander";import ue from"chalk";import{existsSync as Ub,mkdirSync as Wp,writeFileSync as ls}from"fs";import{join as vn,resolve as Wb}from"path";var ds=new Fb().name("plugin").description("manage agentx plugins (Move B)");ds.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(ue.dim(" No plugins configured.")),console.log(ue.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ue.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ue.cyan(t)}`);console.log(),console.log(ue.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ue.red(` ${e.message}`)),process.exitCode=1}});ds.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(ue.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=Wb(o.cwd,t);Ub(n)&&!o.force&&(console.log(ue.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Wp(n,{recursive:!0}),Wp(vn(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;ls(vn(n,"package.json"),Gb(e,s)),ls(vn(n,"tsconfig.json"),zb()),ls(vn(n,"src/index.ts"),Yb(e)),ls(vn(n,"README.md"),Vb(e,s)),ls(vn(n,".gitignore"),Xb()),console.log(),console.log(ue.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ue.bold(" Next steps:")),console.log(ue.dim(` cd ${t}`)),console.log(ue.dim(" pnpm install")),console.log(ue.dim(" pnpm build")),console.log(ue.dim(" pnpm link --global # for local testing")),console.log(ue.dim(" # then in your agentx project:")),console.log(ue.dim(` pnpm link --global ${e}`)),console.log(ue.dim(` agentx config set plugins[0] "${e}"`)),console.log(ue.dim(" agentx plugin doctor")),console.log()});ds.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(ue.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Bb(n);s.kind==="ok"?console.log(` ${ue.green("\u2713")} ${ue.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ue.red("\u2717")} ${ue.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ue.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ue.red(` ${e.message}`)),process.exitCode=1}});async function Bb(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Jb(o);if(!Hb(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=pl.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 Jb(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 Hb(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Gb(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)+`
615
+ `}function zb(){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)+`
616
+ `}function Yb(e){return`// ${e} \u2014 AgentX plugin
612
617
  //
613
618
  // A plugin's default export is { manifest, setup }. The daemon calls
614
619
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -644,7 +649,7 @@ const plugin = {
644
649
  }
645
650
 
646
651
  export default plugin
647
- `}function Tb(e,o){return`# ${e}
652
+ `}function Vb(e,o){return`# ${e}
648
653
 
649
654
  ${o}
650
655
 
@@ -671,24 +676,24 @@ agentx plugin doctor
671
676
  \`\`\`
672
677
 
673
678
  Restart the daemon to activate.
674
- `}function jb(){return`node_modules/
679
+ `}function Xb(){return`node_modules/
675
680
  dist/
676
681
  *.log
677
682
  .env
678
- `}import{Command as Ob}from"commander";import Pe from"chalk";import{writeFileSync as Cb,mkdirSync as Ib,existsSync as Ci,readFileSync as Cp,appendFileSync as Ip}from"fs";import{resolve as vn,dirname as _p}from"path";import{homedir as va}from"os";var Dp=new Ob().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-V2JEVJAD.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=_b(t);break;case"bash":s=qb(t);break;case"fish":s=Ub(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?vn(String(e.output)):Nb(n);Ib(_p(i),{recursive:!0}),Cb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Rb(n,i,!!e.yes)});function Nb(e){let o=va();switch(e){case"zsh":return vn(o,".zsh","completions","_agentx");case"bash":return vn(o,".bash_completion.d","agentx.bash");case"fish":return vn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Rb(e,o,t){if(e==="zsh"){let n=vn(va(),".zshrc"),s=_p(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ci(n)?Cp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ci(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Ip(n,g.join(`
683
+ `}import{Command as Kb}from"commander";import Pe from"chalk";import{writeFileSync as Qb,mkdirSync as Zb,existsSync as Ii,readFileSync as Bp,appendFileSync as Jp}from"fs";import{resolve as xn,dirname as zp}from"path";import{homedir as ja}from"os";var Yp=new Kb().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-EZLJIVQX.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tk(t);break;case"bash":s=ak(t);break;case"fish":s=ck(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?xn(String(e.output)):ek(n);Zb(zp(i),{recursive:!0}),Qb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),ok(n,i,!!e.yes)});function ek(e){let o=ja();switch(e){case"zsh":return xn(o,".zsh","completions","_agentx");case"bash":return xn(o,".bash_completion.d","agentx.bash");case"fish":return xn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function ok(e,o,t){if(e==="zsh"){let n=xn(ja(),".zshrc"),s=zp(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ii(n)?Bp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ii(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Jp(n,g.join(`
679
684
  `)+`
680
- `),console.log(Pe.green("\u2713 Patched ~/.zshrc")),console.log(Pe.dim("Reload your shell: exec zsh"));return}console.log(Pe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Pe.cyan(` ${i}`)),l&&console.log(Pe.cyan(` ${r}`)),console.log(),console.log(Pe.dim("Then reload: exec zsh")),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=vn(va(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ci(n)?Cp(n,"utf-8"):"").includes(o)){console.log(Pe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ci(n)){Ip(n,`
685
+ `),console.log(Pe.green("\u2713 Patched ~/.zshrc")),console.log(Pe.dim("Reload your shell: exec zsh"));return}console.log(Pe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Pe.cyan(` ${i}`)),l&&console.log(Pe.cyan(` ${r}`)),console.log(),console.log(Pe.dim("Then reload: exec zsh")),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=xn(ja(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ii(n)?Bp(n,"utf-8"):"").includes(o)){console.log(Pe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ii(n)){Jp(n,`
681
686
  # agentx completion
682
687
  ${s}
683
- `),console.log(Pe.green("\u2713 Patched ~/.bashrc")),console.log(Pe.dim("Reload your shell: exec bash"));return}console.log(Pe.dim("Add this to ~/.bashrc:")),console.log(Pe.cyan(` ${s}`)),console.log(),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Pe.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ze(e){return e._name||e.name()||""}function it(e){return e.commands.filter(o=>{let t=Ze(o);return!(!t||t==="help")})}function ds(e){return e.options.filter(o=>!o.hidden)}function _b(e){let o=[];return o.push("#compdef agentx"),o.push(""),Pp(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
684
- `)}function Np(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Pp(e,o,t){let n=it(e),i=ds(e).map(Mb).filter(c=>!!c),r=Np(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(Lb).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=Np([...o,Ze(c)]);t.push(` (${Ze(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Pp(c,[...o,Ze(c)],t)}function Db(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 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 Lb(e){let o=Pb(e.description()||"");return`'${Ze(e)}[${o}]'`}function qb(e){let o=it(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(Ze).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=it(n).map(Ze),i=Rp(n);if(t.push(` ${Ze(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 it(n)){let a=Rp(r);t.push(` ${Ze(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(`
685
- `)}function Rp(e){let o=[];for(let t of ds(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Ub(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 it(e)){let n=xa(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ze(t)}" -d "${n}"`)}o.push("");for(let t of ds(e)){let n=ka(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of it(e)){let n=Ze(t);o.push(`# ${n}`);for(let s of ds(t)){let i=ka(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of it(t)){let i=xa(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${it(t).map(Ze).join(" ")}" -a "${Ze(s)}" -d "${i}"`);for(let r of ds(s)){let a=ka(r,[`__fish_seen_subcommand_from ${Ze(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
686
- `)}function xa(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ka(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=xa(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 Wb}from"commander";import Sn from"chalk";import{readFile as Bb}from"node:fs/promises";var xn="anis-marrouchi/agentx",Sa=`https://raw.githubusercontent.com/${xn}/main/contrib/models.json`,Ni=`https://github.com/${xn}/issues/new/choose`,Lp=`https://github.com/${xn}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,Mp=8e3,Ii={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 Ea(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 Aa(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: ${Ni}`].join(`
687
- `)}function Fb(e){return`---
688
- _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function qp(e,o){let t=Ii[e.category];if(!t)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(Ii).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}
689
-
690
- ${Fb({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${xn}/issues/new?${a.toString()}`;if(c.length>Mp)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${Mp}). Shorten it, or paste it into the web form.`);return c}async function Up(e,o=fetch){let t=`repo:${xn} 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/${xn}/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 Ta(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 gs=new Wb().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(Sn.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${Ni}`),console.log(" 2. Let your agent help: install the skill with"),console.log(Sn.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: ${Lp}`),console.log(` Categories: ${Object.keys(Ii).join(", ")}`),console.log()});gs.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",Sa).action(async(e,o)=>{try{let t=await Ta(o.models);if(Ea(e,t)){console.log(Sn.green(` "${e}" is on the recommended list.`));return}console.log(Aa(e,t)),process.exitCode=1}catch(t){console.error(Sn.red(` ${t.message}`)),console.error(` You can always write the issue yourself: ${Ni}`),process.exitCode=1}});gs.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 Up(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}
691
- ${t.url}`)}catch(o){console.error(Sn.red(` ${o.message}`)),process.exitCode=1}});gs.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",Sa).action(async(e,o)=>{try{let t=await Ta(o.models);if(!Ea(o.model,t)){console.log(Aa(o.model,t)),process.exitCode=1;return}let n=e==="-"?await Jb():await Bb(e,"utf8"),s=JSON.parse(n),{version:i}=await ws(),r=qp({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(Sn.red(` ${t.message}`)),process.exitCode=1}});async function Jb(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function vI(){let e=await ws(),o=new Hb().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=td(n);nd(s)&&od("cli",s)});for(let t of[Rd,Nd,ln,Ft,Jt,co,Hl,gt,Js,No,_o,rn,Em,et,Bs,lp,Ko,ng,sg,pg,Yn,Sg,jg,og,Ig,Ng,Vg,Zg,em,Ao,kt,up,qn,Go,Dp,gs])o.addCommand(t);for(let t of Fp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Fp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Gb(t,74," "),""].join(`
692
- `)}),o}var Fp=[ne,mn,st,$o,Wn,tn,Qe,Po,ot,bt,hn,yn,Vo,ze,Yt,li,rp,ap,Io,io,cd,pt,ls,br,nt,oo,Gt,kr,xi,To,Mo,Sp,Ep,pp];function Gb(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(`
693
- `)}export{vI as buildProgram};
694
- //# sourceMappingURL=program-V2JEVJAD.js.map
688
+ `),console.log(Pe.green("\u2713 Patched ~/.bashrc")),console.log(Pe.dim("Reload your shell: exec bash"));return}console.log(Pe.dim("Add this to ~/.bashrc:")),console.log(Pe.cyan(` ${s}`)),console.log(),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Pe.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ze(e){return e._name||e.name()||""}function it(e){return e.commands.filter(o=>{let t=Ze(o);return!(!t||t==="help")})}function gs(e){return e.options.filter(o=>!o.hidden)}function tk(e){let o=[];return o.push("#compdef agentx"),o.push(""),Vp(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
689
+ `)}function Hp(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Vp(e,o,t){let n=it(e),i=gs(e).map(ik).filter(c=>!!c),r=Hp(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(rk).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=Hp([...o,Ze(c)]);t.push(` (${Ze(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Vp(c,[...o,Ze(c)],t)}function nk(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function sk(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function ik(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=nk(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function rk(e){let o=sk(e.description()||"");return`'${Ze(e)}[${o}]'`}function ak(e){let o=it(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(Ze).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=it(n).map(Ze),i=Gp(n);if(t.push(` ${Ze(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 it(n)){let a=Gp(r);t.push(` ${Ze(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(`
690
+ `)}function Gp(e){let o=[];for(let t of gs(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function ck(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 it(e)){let n=Oa(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ze(t)}" -d "${n}"`)}o.push("");for(let t of gs(e)){let n=Ta(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of it(e)){let n=Ze(t);o.push(`# ${n}`);for(let s of gs(t)){let i=Ta(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of it(t)){let i=Oa(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${it(t).map(Ze).join(" ")}" -a "${Ze(s)}" -d "${i}"`);for(let r of gs(s)){let a=Ta(r,[`__fish_seen_subcommand_from ${Ze(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
691
+ `)}function Oa(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ta(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Oa(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 dk}from"commander";import En from"chalk";import{readFile as gk}from"node:fs/promises";var Sn="anis-marrouchi/agentx",Ca=`https://raw.githubusercontent.com/${Sn}/main/contrib/models.json`,Ri=`https://github.com/${Sn}/issues/new/choose`,Kp=`https://github.com/${Sn}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,Xp=8e3,Ni={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 Ia(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 Na(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: ${Ri}`].join(`
692
+ `)}function lk(e){return`---
693
+ _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function Qp(e,o){let t=Ni[e.category];if(!t)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(Ni).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}
694
+
695
+ ${lk({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${Sn}/issues/new?${a.toString()}`;if(c.length>Xp)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${Xp}). Shorten it, or paste it into the web form.`);return c}async function Zp(e,o=fetch){let t=`repo:${Sn} 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/${Sn}/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 Ra(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 ms=new dk().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(En.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${Ri}`),console.log(" 2. Let your agent help: install the skill with"),console.log(En.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(Ni).join(", ")}`),console.log()});ms.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",Ca).action(async(e,o)=>{try{let t=await Ra(o.models);if(Ia(e,t)){console.log(En.green(` "${e}" is on the recommended list.`));return}console.log(Na(e,t)),process.exitCode=1}catch(t){console.error(En.red(` ${t.message}`)),console.error(` You can always write the issue yourself: ${Ri}`),process.exitCode=1}});ms.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 Zp(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}
696
+ ${t.url}`)}catch(o){console.error(En.red(` ${o.message}`)),process.exitCode=1}});ms.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",Ca).action(async(e,o)=>{try{let t=await Ra(o.models);if(!Ia(o.model,t)){console.log(Na(o.model,t)),process.exitCode=1;return}let n=e==="-"?await mk():await gk(e,"utf8"),s=JSON.parse(n),{version:i}=await $s(),r=Qp({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(En.red(` ${t.message}`)),process.exitCode=1}});async function mk(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function zI(){let e=await $s(),o=new pk().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=gd(n);md(s)&&dd("cli",s)});for(let t of[Wd,Ud,dn,Wt,Ht,co,Ql,gt,Hs,No,_o,an,Lm,et,Js,vp,Ko,mg,pg,vg,Vn,Rg,Mg,dg,Fg,Ug,sm,cm,lm,$o,vt,Tp,Fn,Go,Yp,ms])o.addCommand(t);for(let t of eu)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=eu.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,uk(t,74," "),""].join(`
697
+ `)}),o}var eu=[ne,pn,st,bo,Bn,nn,Qe,Po,ot,kt,yn,wn,Vo,ze,Vt,di,$p,bp,Io,io,yd,pt,ds,vr,nt,oo,zt,xr,Si,To,Mo,Mp,Lp,Ap];function uk(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(`
698
+ `)}export{zI as buildProgram};
699
+ //# sourceMappingURL=program-EZLJIVQX.js.map