agentix-cli 0.67.0 → 0.68.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 (104) hide show
  1. package/README.md +11 -1
  2. package/dist/{App-B6WGWI3A.js → App-MMWB4O72.js} +2 -2
  3. package/dist/{ChatApp-BHRANF7Z.js → ChatApp-VCHZLQ57.js} +2 -2
  4. package/dist/{agent-LKL3XATA.js → agent-HM7GNNUR.js} +2 -2
  5. package/dist/{board-dashboard-ZE2A3ARS.js → board-dashboard-LEUIFDNJ.js} +184 -183
  6. package/dist/board-dashboard-LEUIFDNJ.js.map +1 -0
  7. package/dist/{chunk-P4GOKVK2.js → chunk-7R334NQ5.js} +2 -2
  8. package/dist/{chunk-6H3U3CII.js → chunk-ANGX6XPA.js} +2 -2
  9. package/dist/{chunk-EA7H3EUX.js → chunk-APKAW7LU.js} +2 -2
  10. package/dist/{chunk-N42YWYIR.js → chunk-APKKQGTG.js} +2 -2
  11. package/dist/{chunk-3DNBE7WD.js → chunk-AQYST6P6.js} +213 -206
  12. package/dist/chunk-AQYST6P6.js.map +1 -0
  13. package/dist/{chunk-UHUYGEXK.js → chunk-CW63GAH5.js} +47 -47
  14. package/dist/chunk-CW63GAH5.js.map +1 -0
  15. package/dist/{chunk-WMDDQVCI.js → chunk-DXOLLHVZ.js} +2 -2
  16. package/dist/{chunk-LQ5J6COO.js → chunk-FGRD3JAX.js} +2 -2
  17. package/dist/{chunk-WGWNVLVW.js → chunk-FZSEHYYU.js} +2 -2
  18. package/dist/{chunk-5WMHW4A6.js → chunk-G3SOCQII.js} +2 -2
  19. package/dist/{chunk-5QP56S4O.js → chunk-G5JUY265.js} +2 -2
  20. package/dist/{chunk-BHE5TJSN.js → chunk-JHWBCDD2.js} +2 -2
  21. package/dist/{chunk-AZBOYKQA.js → chunk-L52X3YGH.js} +2 -2
  22. package/dist/{chunk-2ZKDZ4FM.js → chunk-LPWPFEIE.js} +2 -2
  23. package/dist/{chunk-OVF37EXJ.js → chunk-N5NPJ6DJ.js} +2 -2
  24. package/dist/{chunk-OVF37EXJ.js.map → chunk-N5NPJ6DJ.js.map} +1 -1
  25. package/dist/{chunk-I2SD4XZ6.js → chunk-NEC4RXFT.js} +2 -2
  26. package/dist/{chunk-A5COMJRC.js → chunk-QHD473UI.js} +15 -15
  27. package/dist/chunk-QHD473UI.js.map +1 -0
  28. package/dist/{chunk-XT3E5MLX.js → chunk-RX5VVHT4.js} +2 -2
  29. package/dist/{chunk-PTB2TPOC.js → chunk-TX7MWUC4.js} +2 -2
  30. package/dist/{chunk-PRHIW6SQ.js → chunk-WDRLN7F2.js} +152 -147
  31. package/dist/chunk-WDRLN7F2.js.map +1 -0
  32. package/dist/{chunk-F2LML4IL.js → chunk-YQT4ZKY5.js} +2 -2
  33. package/dist/cli.js +1 -1
  34. package/dist/client-SWODYWKD.js +2 -0
  35. package/dist/{config-EXNBBAZG.js → config-VV4X7PEK.js} +2 -2
  36. package/dist/config-mutator-BOE7SMT5.js +2 -0
  37. package/dist/doctor-XIS4TMBI.js +2 -0
  38. package/dist/index.d.ts +106 -0
  39. package/dist/index.js +1 -1
  40. package/dist/program-KWSQLVSV.js +2 -0
  41. package/dist/{promote-KPEOVZ5V.js → promote-FDEKCVAE.js} +2 -2
  42. package/dist/query-PJG52OHP.js +2 -0
  43. package/dist/{registry-EUO2D6JT.js → registry-6XJMNXY6.js} +2 -2
  44. package/dist/{request-planner-PLBDCYKI.js → request-planner-KQLWWR3U.js} +2 -2
  45. package/dist/{review-candidates-LEO2N65G.js → review-candidates-A6CLXAFS.js} +2 -2
  46. package/dist/{routing-POORZC7A.js → routing-5G22WTPR.js} +2 -2
  47. package/dist/schedule-tool-ZVKBZOVG.js +2 -0
  48. package/dist/scheduler-5NBO3J2G.js +2 -0
  49. package/dist/{seat-PBFG5R7D.js → seat-W3ZTOJUT.js} +2 -2
  50. package/dist/{select-WORPEXHN.js → select-VPOWFRSN.js} +2 -2
  51. package/dist/{set-enabled-HGQWVDUD.js → set-enabled-C5RFPCAL.js} +2 -2
  52. package/dist/{tool-T2BIWDXP.js → tool-ZENVUVBO.js} +2 -2
  53. package/dist/wiki-ZM6BEOFX.js +2 -0
  54. package/package.json +1 -1
  55. package/dist/board-dashboard-ZE2A3ARS.js.map +0 -1
  56. package/dist/chunk-3DNBE7WD.js.map +0 -1
  57. package/dist/chunk-A5COMJRC.js.map +0 -1
  58. package/dist/chunk-PRHIW6SQ.js.map +0 -1
  59. package/dist/chunk-UHUYGEXK.js.map +0 -1
  60. package/dist/client-YIBETZDJ.js +0 -2
  61. package/dist/config-mutator-MFNZNWCZ.js +0 -2
  62. package/dist/doctor-IITNYJU5.js +0 -2
  63. package/dist/program-ZRGI76RT.js +0 -2
  64. package/dist/query-WRWFAW5G.js +0 -2
  65. package/dist/schedule-tool-ZI4XBEN6.js +0 -2
  66. package/dist/scheduler-VPPKD4FY.js +0 -2
  67. package/dist/wiki-KTDNYDOD.js +0 -2
  68. /package/dist/{App-B6WGWI3A.js.map → App-MMWB4O72.js.map} +0 -0
  69. /package/dist/{ChatApp-BHRANF7Z.js.map → ChatApp-VCHZLQ57.js.map} +0 -0
  70. /package/dist/{agent-LKL3XATA.js.map → agent-HM7GNNUR.js.map} +0 -0
  71. /package/dist/{chunk-P4GOKVK2.js.map → chunk-7R334NQ5.js.map} +0 -0
  72. /package/dist/{chunk-6H3U3CII.js.map → chunk-ANGX6XPA.js.map} +0 -0
  73. /package/dist/{chunk-EA7H3EUX.js.map → chunk-APKAW7LU.js.map} +0 -0
  74. /package/dist/{chunk-N42YWYIR.js.map → chunk-APKKQGTG.js.map} +0 -0
  75. /package/dist/{chunk-WMDDQVCI.js.map → chunk-DXOLLHVZ.js.map} +0 -0
  76. /package/dist/{chunk-LQ5J6COO.js.map → chunk-FGRD3JAX.js.map} +0 -0
  77. /package/dist/{chunk-WGWNVLVW.js.map → chunk-FZSEHYYU.js.map} +0 -0
  78. /package/dist/{chunk-5WMHW4A6.js.map → chunk-G3SOCQII.js.map} +0 -0
  79. /package/dist/{chunk-5QP56S4O.js.map → chunk-G5JUY265.js.map} +0 -0
  80. /package/dist/{chunk-BHE5TJSN.js.map → chunk-JHWBCDD2.js.map} +0 -0
  81. /package/dist/{chunk-AZBOYKQA.js.map → chunk-L52X3YGH.js.map} +0 -0
  82. /package/dist/{chunk-2ZKDZ4FM.js.map → chunk-LPWPFEIE.js.map} +0 -0
  83. /package/dist/{chunk-I2SD4XZ6.js.map → chunk-NEC4RXFT.js.map} +0 -0
  84. /package/dist/{chunk-XT3E5MLX.js.map → chunk-RX5VVHT4.js.map} +0 -0
  85. /package/dist/{chunk-PTB2TPOC.js.map → chunk-TX7MWUC4.js.map} +0 -0
  86. /package/dist/{chunk-F2LML4IL.js.map → chunk-YQT4ZKY5.js.map} +0 -0
  87. /package/dist/{client-YIBETZDJ.js.map → client-SWODYWKD.js.map} +0 -0
  88. /package/dist/{config-EXNBBAZG.js.map → config-VV4X7PEK.js.map} +0 -0
  89. /package/dist/{config-mutator-MFNZNWCZ.js.map → config-mutator-BOE7SMT5.js.map} +0 -0
  90. /package/dist/{doctor-IITNYJU5.js.map → doctor-XIS4TMBI.js.map} +0 -0
  91. /package/dist/{program-ZRGI76RT.js.map → program-KWSQLVSV.js.map} +0 -0
  92. /package/dist/{promote-KPEOVZ5V.js.map → promote-FDEKCVAE.js.map} +0 -0
  93. /package/dist/{query-WRWFAW5G.js.map → query-PJG52OHP.js.map} +0 -0
  94. /package/dist/{registry-EUO2D6JT.js.map → registry-6XJMNXY6.js.map} +0 -0
  95. /package/dist/{request-planner-PLBDCYKI.js.map → request-planner-KQLWWR3U.js.map} +0 -0
  96. /package/dist/{review-candidates-LEO2N65G.js.map → review-candidates-A6CLXAFS.js.map} +0 -0
  97. /package/dist/{routing-POORZC7A.js.map → routing-5G22WTPR.js.map} +0 -0
  98. /package/dist/{schedule-tool-ZI4XBEN6.js.map → schedule-tool-ZVKBZOVG.js.map} +0 -0
  99. /package/dist/{scheduler-VPPKD4FY.js.map → scheduler-5NBO3J2G.js.map} +0 -0
  100. /package/dist/{seat-PBFG5R7D.js.map → seat-W3ZTOJUT.js.map} +0 -0
  101. /package/dist/{select-WORPEXHN.js.map → select-VPOWFRSN.js.map} +0 -0
  102. /package/dist/{set-enabled-HGQWVDUD.js.map → set-enabled-C5RFPCAL.js.map} +0 -0
  103. /package/dist/{tool-T2BIWDXP.js.map → tool-ZENVUVBO.js.map} +0 -0
  104. /package/dist/{wiki-KTDNYDOD.js.map → wiki-ZM6BEOFX.js.map} +0 -0
@@ -1,42 +1,42 @@
1
- import{a as Nc,b as Hn,g as Rc}from"./chunk-5WMHW4A6.js";import{a as ao,b as bc,f as $c,g as kc,h as vc,i as Jn,j as Ec,k as Ac,l as ii,m as jc,o as Cc}from"./chunk-WMDDQVCI.js";import{a as Tc,c as Oc,d as Ic}from"./chunk-Z3IP66SL.js";import{a as xc,c as Sc}from"./chunk-N42YWYIR.js";import{a as Gs,b as Xr}from"./chunk-RKPAVWXF.js";import{a as pt}from"./chunk-GV7S5BAX.js";import{e as qr}from"./chunk-GSX4NK2N.js";import{c as Wr}from"./chunk-SZDACK6O.js";import{$ as yc,A as Vs,B as Ya,C as Va,D as Ka,E as Xa,F as Qa,G as Za,H as sc,I as ic,J as ft,K as Un,L as Zs,M as rc,N as ac,O as cc,P as lc,Q as ht,R as yt,S as dc,T as gc,U as Ne,V as qn,W as en,X as ei,Y as mc,Z as fc,_ as ni,a as ia,aa as Wn,b as ra,ba as wt,ca as Bn,da as si,ea as wc,h as da,i as ga,j as Xt,k as Rn,l as ua,m as fa,n as ha,o as ya,p as Ia,q as ja,r as Mn,s as Ys,t as Da,u as Ua,v as Ba,w as Ja,x as Ha,y as Ga,z as za}from"./chunk-3DNBE7WD.js";import{A as La,B as Fa,Ma as ro,N as Qt,Oa as hc,P as Ks,Q as Ln,R as ec,ba as Eo,ca as oc,da as Xs,fa as Qs,ha as tc,ia as nc,ja as Zt,m as So,na as Fn,q as Pa,t as Ma,va as pc,wa as oi,xa as uc,ya as ti}from"./chunk-A5COMJRC.js";import{a as aa,d as ca,e as la}from"./chunk-5QP56S4O.js";import{a as _n,b as Dn,c as wa,d as ba,e as $a,g as ka,h as va,j as xa,k as Sa,l as Ea,m as Aa,p as Pn,r as Ta,s as Oa}from"./chunk-BYJ3A55Y.js";import{a as zs,e as Qr,f as Zr,h as ea,i as oa,k as ta,l as na,m as sa}from"./chunk-I2SD4XZ6.js";import{a as ma,p as pa}from"./chunk-XT3E5MLX.js";import{a as Ca,b as Na,c as Ra,d as _a}from"./chunk-2D3RYIDU.js";import{a as qa,b as Wa}from"./chunk-L53FTKEP.js";import{B as xo,H as Vr,S as Kr,h as Dr,q as Pr,v as Bs,w as Fr}from"./chunk-UHUYGEXK.js";import{b as Vt,c as gt,d as Cn,e as Nn,f as mt,g as Ur,h as Ho,i as Kt}from"./chunk-6H3U3CII.js";import{a as _r}from"./chunk-N6EWZGIX.js";import{e as Gr,f as Hs,k as zr}from"./chunk-WP6KLXTP.js";import{b as dt}from"./chunk-DP7RTNDM.js";import{a as Mr,k as Hr}from"./chunk-BHE5TJSN.js";import{b as ye,c as Oe,d as ut,e as Yr}from"./chunk-EA7H3EUX.js";import{j as Lr}from"./chunk-X5C5W3E4.js";import{f as Br,g as Jr,h as Js}from"./chunk-76Z4VHDX.js";import{h as Rr}from"./chunk-DWADWDMU.js";import{a as Ws}from"./chunk-AZBOYKQA.js";import{b as vo,d as jn}from"./chunk-WGWNVLVW.js";import{b as lt,d as Nr}from"./chunk-2GIDVZ4H.js";import{a as qs,b as yr,c as Dg,d as On,e as wr,f as Ar,g as Lg,h as Tr,i as Fg,m as ct,n as Ir,o as jr,s as Cr,v as io,w as Yt}from"./chunk-PTB2TPOC.js";import{a as fo,b as at,e as xr,f as zt}from"./chunk-72SZI2UW.js";import{a as Or,b as Ug}from"./chunk-FX3D7YON.js";import{a as uo,b as _g}from"./chunk-7I7IEX4S.js";import{m as br,n as $r,p as kr,q as Pg,v as vr,w as j,x as In,z as ae}from"./chunk-OVF37EXJ.js";import{g as Sr,k as Er,l as Mg}from"./chunk-RGDKHYY2.js";import{Command as qg}from"commander";var _c=new qg().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 ra({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()});ae();import{Command as Wg}from"commander";import{execFileSync as Ke}from"node:child_process";import{cpSync as Dc,existsSync as ci,mkdirSync as ri,mkdtempSync as Bg,readdirSync as Jg,rmSync as Pc,writeFileSync as Mc}from"node:fs";import{dirname as Lc,join as _e}from"node:path";import{homedir as Gn,release as Hg,tmpdir as Gg}from"node:os";import{setTimeout as zg}from"node:timers/promises";function zn(){let e=wa(process.platform,process.arch,Hg());if(e)throw new Error(e)}function Yn(){let e=_e(Gn(),"Library/LaunchAgents"),o=[];try{o=Jg(e).filter(ka)}catch{}let t=o.flatMap(n=>{let s=_e(e,n);try{return[{file:s,plist:Ke("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return va(e,t)}function on(e){return`gui/${process.getuid()}/${e.label}`}async function ai(e){try{Ke("launchctl",["bootout",on(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{Ke("launchctl",["print",on(e)],{stdio:"pipe"})}catch{return}await zg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Fc(e){if(!ci(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{Ke("launchctl",["print",on(e)],{stdio:"pipe"})}catch{o=!1}o||Ke("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Ke("launchctl",["kickstart",on(e)],{stdio:"pipe"})}function Yg(){let e=Aa();if(e&&ci(_e(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 bt=new Wg("desktop").description("install and control the macOS desktop assistant");bt.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=>{zn();let o=j(),t=ba(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=Yg(),r=_e(Gn(),"Applications"),{keep:a,remove:c}=Yn();if(console.log(`Desktop assistant \u2192 ${_e(r,_n)}
2
- Computer-use helper \u2192 ${_e(r,Dn)}
1
+ import{a as qc,b as Vn,g as Wc}from"./chunk-G3SOCQII.js";import{a as ao,b as Oc,f as jc,g as Ic,h as Cc,i as Yn,j as _c,k as Dc,l as gi,m as Fc,o as Uc}from"./chunk-DXOLLHVZ.js";import{a as Pc,c as Mc,d as Lc}from"./chunk-Z3IP66SL.js";import{a as Rc,c as Nc}from"./chunk-APKKQGTG.js";import{a as Qs,b as aa}from"./chunk-RKPAVWXF.js";import{a as pt}from"./chunk-GV7S5BAX.js";import{e as Xr}from"./chunk-GSX4NK2N.js";import{c as Qr}from"./chunk-SZDACK6O.js";import{$ as Ac,A as oi,B as nc,C as sc,D as ic,E as rc,F as ac,G as cc,H as pc,I as uc,J as ft,K as Jn,L as ii,M as fc,N as hc,O as yc,P as wc,Q as ht,R as yt,S as bc,T as $c,U as Re,V as Hn,W as tn,X as ri,Y as kc,Z as Sc,_ as li,a as fa,aa as Gn,b as ha,ba as wt,ca as zn,da as di,ea as Tc,h as Pn,i as $a,j as Zt,k as Mn,l as xa,m as Sa,n as Ea,o as Aa,p as La,q as Fa,r as qn,s as ei,t as Ja,u as Va,v as Qa,w as Za,x as ec,y as oc,z as tc}from"./chunk-AQYST6P6.js";import{A as za,B as Ya,Ma as ro,N as en,Oa as Ec,P as ti,Q as Wn,R as lc,ba as Eo,ca as dc,da as ni,fa as si,ha as gc,ia as mc,ja as on,m as So,na as Bn,q as Ha,t as Ga,va as vc,wa as ai,xa as xc,ya as ci}from"./chunk-QHD473UI.js";import{a as ya,d as wa,e as ba}from"./chunk-G5JUY265.js";import{a as Ln,b as Fn,c as Ta,d as Oa,e as ja,g as Ia,h as Ca,j as Ra,k as Na,l as _a,m as Da,p as Un,r as Pa,s as Ma}from"./chunk-BYJ3A55Y.js";import{a as Zs,e as ca,f as la,h as da,i as ga,k as ma,l as pa,m as ua}from"./chunk-NEC4RXFT.js";import{a as ka,p as va}from"./chunk-RX5VVHT4.js";import{a as Ua,b as qa,c as Wa,d as Ba}from"./chunk-2D3RYIDU.js";import{a as Ka,b as Xa}from"./chunk-L53FTKEP.js";import{B as xo,H as ia,S as ra,h as Hr,q as Gr,v as Vs,w as Vr}from"./chunk-CW63GAH5.js";import{b as Xt,c as gt,d as _n,e as Dn,f as mt,g as Kr,h as Ho,i as Qt}from"./chunk-ANGX6XPA.js";import{a as Jr}from"./chunk-N6EWZGIX.js";import{e as ta,f as Xs,k as na}from"./chunk-WP6KLXTP.js";import{b as dt}from"./chunk-DP7RTNDM.js";import{a as zr,k as oa}from"./chunk-JHWBCDD2.js";import{b as ye,c as Oe,d as ut,e as sa}from"./chunk-APKAW7LU.js";import{j as Yr}from"./chunk-X5C5W3E4.js";import{f as Zr,g as ea,h as Ks}from"./chunk-76Z4VHDX.js";import{h as Br}from"./chunk-DWADWDMU.js";import{a as Ys}from"./chunk-L52X3YGH.js";import{b as vo,d as Nn}from"./chunk-FZSEHYYU.js";import{b as lt,d as Wr}from"./chunk-2GIDVZ4H.js";import{a as zs,b as Tr,c as Yg,d as Cn,e as Or,f as Pr,g as Xg,h as Mr,i as Qg,m as ct,n as Fr,o as Ur,s as qr,v as io,w as Kt}from"./chunk-TX7MWUC4.js";import{a as fo,b as at,e as Nr,f as Vt}from"./chunk-72SZI2UW.js";import{a as Lr,b as Zg}from"./chunk-FX3D7YON.js";import{a as uo,b as zg}from"./chunk-7I7IEX4S.js";import{m as jr,n as Ir,p as Cr,q as Vg,v as Rr,w as I,x as Rn,z as ae}from"./chunk-N5NPJ6DJ.js";import{g as _r,k as Dr,l as Kg}from"./chunk-RGDKHYY2.js";import{Command as em}from"commander";var Bc=new em().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 ha({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()});ae();import{Command as om}from"commander";import{execFileSync as Ke}from"node:child_process";import{cpSync as Jc,existsSync as ui,mkdirSync as mi,mkdtempSync as tm,readdirSync as nm,rmSync as Hc,writeFileSync as Gc}from"node:fs";import{dirname as zc,join as _e}from"node:path";import{homedir as Kn,release as sm,tmpdir as im}from"node:os";import{setTimeout as rm}from"node:timers/promises";function Xn(){let e=Ta(process.platform,process.arch,sm());if(e)throw new Error(e)}function Qn(){let e=_e(Kn(),"Library/LaunchAgents"),o=[];try{o=nm(e).filter(Ia)}catch{}let t=o.flatMap(n=>{let s=_e(e,n);try{return[{file:s,plist:Ke("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ca(e,t)}function nn(e){return`gui/${process.getuid()}/${e.label}`}async function pi(e){try{Ke("launchctl",["bootout",nn(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{Ke("launchctl",["print",nn(e)],{stdio:"pipe"})}catch{return}await rm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yc(e){if(!ui(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{Ke("launchctl",["print",nn(e)],{stdio:"pipe"})}catch{o=!1}o||Ke("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Ke("launchctl",["kickstart",nn(e)],{stdio:"pipe"})}function am(){let e=Da();if(e&&ui(_e(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 bt=new om("desktop").description("install and control the macOS desktop assistant");bt.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=>{Xn();let o=I(),t=Oa(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=am(),r=_e(Kn(),"Applications"),{keep:a,remove:c}=Qn();if(console.log(`Desktop assistant \u2192 ${_e(r,Ln)}
2
+ Computer-use helper \u2192 ${_e(r,Fn)}
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{Ke("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=Ke("/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=Bg(_e(Gg(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Dc(_e(i,"apps",p),_e(g,p),{recursive:!0,filter:y=>!y.split("/").includes("build")});let w=p==="mac-helper"?Sa(o.notifications.local.icon):[];Ke("/bin/bash",[_e(g,p,"build.sh"),...w],{stdio:"inherit"})}let d=_e(Gn(),"Library/Logs/agentx-desktop.err.log"),u=xa({label:a.label,executable:_e(r,_n,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:Ea(Gn()),cli:_e(i,"dist/cli.js"),node:process.execPath,log:d,path:$a(l,process.env.AGENTX_VOICE_PATH)}),f=_e(g,"desktop.plist");Mc(f,u,{mode:384}),Ke("plutil",["-lint",f],{stdio:"pipe"}),await ai(a);for(let p of c)p.label!==a.label&&await ai(p),Pc(p.file,{force:!0});ri(r,{recursive:!0});for(let[p,w,y]of[["mac-voice","AgentX Voice.app",_n],["mac-helper",Dn,Dn]])Dc(_e(g,p,"build",w),_e(r,y),{recursive:!0});ri(Lc(a.file),{recursive:!0}),ri(Lc(d),{recursive:!0}),Mc(a.file,u,{mode:384}),Fc(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{Ke("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=Ke("/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=tm(_e(im(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Jc(_e(i,"apps",p),_e(g,p),{recursive:!0,filter:y=>!y.split("/").includes("build")});let w=p==="mac-helper"?Na(o.notifications.local.icon):[];Ke("/bin/bash",[_e(g,p,"build.sh"),...w],{stdio:"inherit"})}let d=_e(Kn(),"Library/Logs/agentx-desktop.err.log"),u=Ra({label:a.label,executable:_e(r,Ln,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:_a(Kn()),cli:_e(i,"dist/cli.js"),node:process.execPath,log:d,path:ja(l,process.env.AGENTX_VOICE_PATH)}),f=_e(g,"desktop.plist");Gc(f,u,{mode:384}),Ke("plutil",["-lint",f],{stdio:"pipe"}),await pi(a);for(let p of c)p.label!==a.label&&await pi(p),Hc(p.file,{force:!0});mi(r,{recursive:!0});for(let[p,w,y]of[["mac-voice","AgentX Voice.app",Ln],["mac-helper",Fn,Fn]])Jc(_e(g,p,"build",w),_e(r,y),{recursive:!0});mi(zc(a.file),{recursive:!0}),mi(zc(d),{recursive:!0}),Gc(a.file,u,{mode:384}),Yc(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{Pc(g,{recursive:!0,force:!0})}});bt.command("start").description("start the installed desktop assistant").action(()=>{zn(),Fc(Yn().keep),console.log("Desktop assistant started.")});bt.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{zn(),await ai(Yn().keep),console.log("Desktop assistant stopped.")});bt.command("status").description("show the desktop login service status").action(()=>{zn();let{keep:e}=Yn();try{console.log(Ke("launchctl",["print",on(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(ci(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as em}from"commander";import{open as om}from"fs/promises";import{existsSync as Xn,mkdirSync as Vg,readFileSync as Qn,writeFileSync as Uc}from"fs";import{homedir as Kg}from"os";import{dirname as Xg,resolve as li}from"path";var di="/attach/",qc="/guard/check";function Wc(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 Vn(e,o,t){let n={hooks:[{type:"command",command:Wc(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function Qg(e){return{SessionStart:[Vn("/attach/session-start",e,"")],UserPromptSubmit:[Vn("/attach/prompt",e)],Stop:[Vn("/attach/stop",e)],SessionEnd:[Vn("/attach/session-end",e)]}}function Zg(e){let o=Wc("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Kn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function tn(){return li(Kg(),".claude/settings.json")}function Go(e=process.cwd()){for(let o of[e,li(e,"..")]){let t=li(o,"agentx.json");if(Xn(t))try{let n=JSON.parse(Qn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Bc(e,o={}){let t=o.path??tn(),n=o.withGuard!==!1,s={};if(Xn(t))try{s=JSON.parse(Qn(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(Qg(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!Kn(f,di)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!Kn(d,qc)):[];r.PreToolUse=[...g,...Zg(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(Vg(Xg(t),{recursive:!0}),Uc(t,`${JSON.stringify(s,null,2)}
9
- `)),{path:t,changed:l,events:a,guardInstalled:c}}function Jc(e={}){let o=e.path??tn();if(!Xn(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Qn(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"?qc:di;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!Kn(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&&Uc(o,`${JSON.stringify(t,null,2)}
10
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function nn(e=tn()){if(!Xn(e))return!1;try{return!!JSON.parse(Qn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Kn(t,di))}catch{return!1}}var Zn=new em("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Hc=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Go()}`;async function Gc(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)}`)}Zn.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",Hc).action(async e=>{try{await Gc(e.url,"register",ca.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}});Zn.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",Hc).action(async e=>{try{let o=await om(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 Gc(e.url,"ended",la.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 Qy}from"commander";import{Command as dm}from"commander";ae();import T from"chalk";import{existsSync as gm,readFileSync as mm}from"fs";ae();import{Command as tm}from"commander";import oe from"chalk";import{spawn as Yc}from"child_process";import{existsSync as nm,readFileSync as sm,unlinkSync as im}from"fs";import{resolve as gi}from"path";var mi=e=>new Promise(o=>setTimeout(o,e));function pi(e){try{return process.kill(e,0),!0}catch{return!1}}async function $t(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function rm(e){let o=await $t(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await $t(`${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 am(e){for(let o of[gi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(sm(o,"utf-8").trim(),10);if(Number.isFinite(t)&&pi(t))return t}catch{}return null}function cm(e){return new Promise(o=>{let t=Yc(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var Vc=new tm("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let o=j(e.config),[t,n]=o.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s}`,r=await $t(`${i}/health`);r||(console.log(oe.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(oe.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await $t(`${i}/daemon/restart`),c=a?.pid??Ya(s)??am(process.cwd()),l=a?.service??(c?Ga(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=Ja(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?za(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${oe.bold(r.node?.name||r.node?.id||i)}${c?oe.dim(` (PID ${c})`):""}`),console.log(` Run by: ${Ha(l)}`),f.ok||(console.log(oe.red(` ${f.reason}`)),console.log(oe.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(oe.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(oe.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(oe.dim(" Would run:"));for(let v of f.steps)console.log(oe.dim(` ${zc(v,c)}`));console.log();return}if(e.whenIdle){let v=Number(e.timeout),A=Math.max(1,Number(e.interval)||5);(!Number.isFinite(v)||v<0)&&(console.log(oe.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await Ba({read:()=>rm(i),intervalMs:A*1e3,timeoutMs:v*6e4,onCheck:$=>{$!==S&&$!==null&&$>0&&console.log(oe.dim(` Waiting: ${$} task(s) running...`)),S=$}});if(x.outcome==="unreachable"&&(console.log(oe.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(oe.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let $=x.inflight??"some";e.abortOnTimeout&&(console.log(oe.yellow(` Still ${$} task(s) running after ${v} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(oe.yellow(` Still ${$} task(s) running after ${v} min. Restarting anyway:`)),console.log(oe.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(oe.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=gi(g,".agentx");try{Wa(p,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let w=Date.now(),y=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(oe.dim(" Restarting..."));for(let v of f.steps){if(await lm(v,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:y,service:l})||v.kind==="exec"&&v.mayFail)continue;let S=v===f.steps[0];try{S&&im(gi(p,qa))}catch{}console.log(oe.red(` Step failed: ${zc(v,c)}`)),console.log(S?oe.dim(` The daemon is still running. Restart it with: ${f.manual}`):oe.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,b=Date.now();for(;Date.now()-b<k;){let v=await $t(`${i}/health`);if(v&&typeof v.uptime=="number"&&v.uptime*1e3<=Date.now()-w+2e3){let A=await $t(`${i}/daemon/restart`);console.log(oe.green(` Daemon is back${A?.pid?` (PID ${A.pid})`:""} after ${Math.round((Date.now()-w)/1e3)}s.`)),console.log();return}await mi(1e3)}console.log(oe.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(oe.dim(` Start it with: ${f.manual}`)),console.log(oe.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function zc(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 lm(e,o){switch(e.kind){case"exec":return await cm(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(;pi(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(oe.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await mi(500);return pi(o.pid)?(console.log(oe.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(;Vs(o.service)&&Date.now()-t<3e4;)await mi(500);return!Vs(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!nm(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=Yc(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function pm(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 Xe=new dm().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Xe.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(f))&&(console.error(T.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(T.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let p=[f,"daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(T.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${w}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(T.dim(` tail -n 40 ${w}`))}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 pm(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{um(i(process.cwd(),".env"))}catch{}await new si(e.config).start()});function um(e){if(!gm(e))return;let o=mm(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}}Xe.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-ZAF7RW25.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(;Kc(a)&&Date.now()-l<c;)!g&&Date.now()-l>3e3&&(console.log(T.dim(` Waiting for in-flight tasks to finish (up to ${Math.round(c/6e4)} min)...`)),g=!0),await new Promise(d=>setTimeout(d,500));if(Kc(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(T.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(T.green("Daemon stopped"))}catch{console.log(T.yellow("No daemon process found"))}});Xe.addCommand(Vc);Xe.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=j(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(T.bold(` ${r.node.name}`)+T.dim(` (${r.node.id})`)),console.log(T.green(" Status: running")+T.dim(` \u2014 uptime ${fm(r.uptime)}`)),console.log(),console.log(T.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?T.yellow(` [${c.active} active]`):"",g=c.errors>0?T.red(` (${c.errors} errors)`):"";console.log(` ${T.cyan(c.name)} ${T.dim(`(${c.tier})`)}${l}${g}`),console.log(T.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(T.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?T.green("\u25CF"):T.dim("\u25CB"),g=c.nextRun?T.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(T.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?T.green("\u25CF"):T.red("\u25CF"),g=c.skills?.length?T.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${T.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let t=j(e.config),n=In(t);if(console.log(),console.log(T.bold(` ${t.node.name}`)+T.dim(` (${t.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(T.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(T.red(` ${t.message}`))}}});Xe.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(T.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Xe.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(j(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(T.dim(` Connecting to ${n}...`)),console.log(T.dim(` Press Ctrl+C to stop
8
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Hc(g,{recursive:!0,force:!0})}});bt.command("start").description("start the installed desktop assistant").action(()=>{Xn(),Yc(Qn().keep),console.log("Desktop assistant started.")});bt.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{Xn(),await pi(Qn().keep),console.log("Desktop assistant stopped.")});bt.command("status").description("show the desktop login service status").action(()=>{Xn();let{keep:e}=Qn();try{console.log(Ke("launchctl",["print",nn(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(ui(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as pm}from"commander";import{open as um}from"fs/promises";import{existsSync as os,mkdirSync as cm,readFileSync as ts,writeFileSync as Vc}from"fs";import{homedir as lm}from"os";import{dirname as dm,resolve as fi}from"path";var hi="/attach/",Kc="/guard/check";function Xc(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 Zn(e,o,t){let n={hooks:[{type:"command",command:Xc(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function gm(e){return{SessionStart:[Zn("/attach/session-start",e,"")],UserPromptSubmit:[Zn("/attach/prompt",e)],Stop:[Zn("/attach/stop",e)],SessionEnd:[Zn("/attach/session-end",e)]}}function mm(e){let o=Xc("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function es(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function sn(){return fi(lm(),".claude/settings.json")}function Go(e=process.cwd()){for(let o of[e,fi(e,"..")]){let t=fi(o,"agentx.json");if(os(t))try{let n=JSON.parse(ts(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Qc(e,o={}){let t=o.path??sn(),n=o.withGuard!==!1,s={};if(os(t))try{s=JSON.parse(ts(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(gm(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!es(f,hi)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!es(d,Kc)):[];r.PreToolUse=[...g,...mm(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(cm(dm(t),{recursive:!0}),Vc(t,`${JSON.stringify(s,null,2)}
9
+ `)),{path:t,changed:l,events:a,guardInstalled:c}}function Zc(e={}){let o=e.path??sn();if(!os(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(ts(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"?Kc:hi;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!es(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&&Vc(o,`${JSON.stringify(t,null,2)}
10
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function rn(e=sn()){if(!os(e))return!1;try{return!!JSON.parse(ts(e,"utf-8"))?.hooks?.Stop?.some?.(t=>es(t,hi))}catch{return!1}}var ns=new pm("monitor").description("Register external CLI sessions and report ended runs to the briefing"),el=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Go()}`;async function ol(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)}`)}ns.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",el).action(async e=>{try{await ol(e.url,"register",wa.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}});ns.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",el).action(async e=>{try{let o=await um(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 ol(e.url,"ended",ba.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 fw}from"commander";import{Command as xm}from"commander";ae();import T from"chalk";import{existsSync as Sm,readFileSync as Em}from"fs";ae();import{Command as fm}from"commander";import oe from"chalk";import{spawn as nl}from"child_process";import{existsSync as hm,readFileSync as ym,unlinkSync as wm}from"fs";import{resolve as yi}from"path";var wi=e=>new Promise(o=>setTimeout(o,e));function bi(e){try{return process.kill(e,0),!0}catch{return!1}}async function $t(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function bm(e){let o=await $t(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await $t(`${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 $m(e){for(let o of[yi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(ym(o,"utf-8").trim(),10);if(Number.isFinite(t)&&bi(t))return t}catch{}return null}function km(e){return new Promise(o=>{let t=nl(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var sl=new fm("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=I(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 $t(`${i}/health`);r||(console.log(oe.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(oe.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await $t(`${i}/daemon/restart`),c=a?.pid??nc(s)??$m(process.cwd()),l=a?.service??(c?oc(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=Za(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?tc(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${oe.bold(r.node?.name||r.node?.id||i)}${c?oe.dim(` (PID ${c})`):""}`),console.log(` Run by: ${ec(l)}`),f.ok||(console.log(oe.red(` ${f.reason}`)),console.log(oe.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(oe.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(oe.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(oe.dim(" Would run:"));for(let v of f.steps)console.log(oe.dim(` ${tl(v,c)}`));console.log();return}if(e.whenIdle){let v=Number(e.timeout),A=Math.max(1,Number(e.interval)||5);(!Number.isFinite(v)||v<0)&&(console.log(oe.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await Qa({read:()=>bm(i),intervalMs:A*1e3,timeoutMs:v*6e4,onCheck:$=>{$!==S&&$!==null&&$>0&&console.log(oe.dim(` Waiting: ${$} task(s) running...`)),S=$}});if(x.outcome==="unreachable"&&(console.log(oe.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(oe.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let $=x.inflight??"some";e.abortOnTimeout&&(console.log(oe.yellow(` Still ${$} task(s) running after ${v} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(oe.yellow(` Still ${$} task(s) running after ${v} min. Restarting anyway:`)),console.log(oe.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(oe.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=yi(g,".agentx");try{Xa(p,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let w=Date.now(),y=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(oe.dim(" Restarting..."));for(let v of f.steps){if(await vm(v,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:y,service:l})||v.kind==="exec"&&v.mayFail)continue;let S=v===f.steps[0];try{S&&wm(yi(p,Ka))}catch{}console.log(oe.red(` Step failed: ${tl(v,c)}`)),console.log(S?oe.dim(` The daemon is still running. Restart it with: ${f.manual}`):oe.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,b=Date.now();for(;Date.now()-b<k;){let v=await $t(`${i}/health`);if(v&&typeof v.uptime=="number"&&v.uptime*1e3<=Date.now()-w+2e3){let A=await $t(`${i}/daemon/restart`);console.log(oe.green(` Daemon is back${A?.pid?` (PID ${A.pid})`:""} after ${Math.round((Date.now()-w)/1e3)}s.`)),console.log();return}await wi(1e3)}console.log(oe.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(oe.dim(` Start it with: ${f.manual}`)),console.log(oe.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function tl(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 vm(e,o){switch(e.kind){case"exec":return await km(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(;bi(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(oe.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await wi(500);return bi(o.pid)?(console.log(oe.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(;oi(o.service)&&Date.now()-t<3e4;)await wi(500);return!oi(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!hm(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=nl(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function Am(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 Xe=new xm().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Xe.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),{openSync:g,writeFileSync:d,existsSync:u}=await import("fs"),f=process.argv[1];(!f||!u(f))&&(console.error(T.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${f||"?"}).`)),console.error(T.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let p=[f,"daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=g(w,"a")}catch(b){console.error(T.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${w}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(T.dim(` tail -n 40 ${w}`))}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 Am(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Tm(i(process.cwd(),".env"))}catch{}await new di(e.config).start()});function Tm(e){if(!Sm(e))return;let o=Em(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}}Xe.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-ZAF7RW25.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(;il(a)&&Date.now()-l<c;)!g&&Date.now()-l>3e3&&(console.log(T.dim(` Waiting for in-flight tasks to finish (up to ${Math.round(c/6e4)} min)...`)),g=!0),await new Promise(d=>setTimeout(d,500));if(il(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(T.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(T.green("Daemon stopped"))}catch{console.log(T.yellow("No daemon process found"))}});Xe.addCommand(sl);Xe.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=I(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(T.bold(` ${r.node.name}`)+T.dim(` (${r.node.id})`)),console.log(T.green(" Status: running")+T.dim(` \u2014 uptime ${Om(r.uptime)}`)),console.log(),console.log(T.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?T.yellow(` [${c.active} active]`):"",g=c.errors>0?T.red(` (${c.errors} errors)`):"";console.log(` ${T.cyan(c.name)} ${T.dim(`(${c.tier})`)}${l}${g}`),console.log(T.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(T.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?T.green("\u25CF"):T.dim("\u25CB"),g=c.nextRun?T.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(T.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?T.green("\u25CF"):T.red("\u25CF"),g=c.skills?.length?T.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${T.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let t=I(e.config),n=Rn(t);if(console.log(),console.log(T.bold(` ${t.node.name}`)+T.dim(` (${t.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(T.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(T.red(` ${t.message}`))}}});Xe.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(T.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Xe.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(I(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(T.dim(` Connecting to ${n}...`)),console.log(T.dim(` Press Ctrl+C to stop
13
13
  `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(T.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let g=a.split(`
14
- `);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let u=JSON.parse(d.slice(6)),f=new Date(u.time).toLocaleTimeString(),p=u.message?.replace(/^\[agentx\]\s*/,"")||"";p.includes("executing")?console.log(`${T.dim(f)} ${T.cyan("\u25B6")} ${p}`):p.includes("completed")?console.log(`${T.dim(f)} ${T.green("\u2713")} ${p}`):p.includes("error")||p.includes("Error")?console.log(`${T.dim(f)} ${T.red("\u2717")} ${p}`):p.includes("Routing")?console.log(`${T.dim(f)} ${T.yellow("\u2192")} ${p}`):p.includes("mention")?console.log(`${T.dim(f)} ${T.magenta("@")} ${p}`):p.includes("Skipping")?console.log(`${T.dim(f)} ${T.dim("\u2298")} ${T.dim(p)}`):console.log(`${T.dim(f)} ${p}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(T.red(` Connection failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Diagnostic order:")),console.log(T.dim(" 1) agentx daemon status # is the daemon up?")),console.log(T.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(T.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(T.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(T.dim(" to see the error in the foreground."))}});Xe.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=j(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(T.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(T.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(T.dim(`
15
- (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(T.red(` Failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Try: agentx daemon status"))}});Xe.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(T.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Tests passed"))}catch{console.log(T.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(T.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(T.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(T.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),o.restart){console.log(T.dim(" Restarting remote daemon once no task is running..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} -t ${o.user}@${e} "cd ${o.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(T.green(" Remote daemon restarted"))}}catch(i){console.log(T.red(` Deploy failed: ${i.message}`))}});Xe.action(async e=>{await new si(e.config).start()});function fm(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 Kc(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as hm}from"commander";import Qe from"chalk";import{existsSync as sn,readFileSync as ym,writeFileSync as Xc,mkdirSync as Qc}from"fs";import{hostname as Zc}from"os";import{resolve as kt}from"path";var el=new hm().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=kt(o,"agentx.json"),n=kt(o,".env"),s=kt(o,".agentx/sessions");if(console.log(),console.log(Qe.bold(" agentx init")),console.log(),sn(t)&&!e.force){console.log(Qe.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[kt(o,"agentx.example.json"),kt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(sn(c)){r=ym(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Zc().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Zc(),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)),Xc(t,r),console.log(Qe.green(" \u2713 Created agentx.json")),sn(n)||(Xc(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
- `)),console.log(Qe.green(" \u2713 Created .env template"))),sn(s)||(Qc(s,{recursive:!0}),console.log(Qe.green(" \u2713 Created .agentx/sessions/")));let a=kt(o,".claude");sn(a)||(Qc(a,{recursive:!0}),console.log(Qe.green(" \u2713 Created .claude/"))),console.log(),console.log(Qe.bold(" Next steps:")),console.log(` 1. Edit ${Qe.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Qe.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Qe.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Qe.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as wm}from"commander";import zo from"chalk";import{spawn as tl}from"child_process";import{existsSync as bm}from"fs";import{dirname as $m,resolve as km}from"path";import{fileURLToPath as vm}from"url";ae();var nl=new wm().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=bc(),t=e.port?parseInt(e.port,10):xm(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(zo.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(zo.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(zo.bold(` Opening ${n}`)),console.log(),await Em(n).catch(()=>!1))console.log(zo.dim(" Dashboard is already running.")),e.open!==!1&&ol(n);else{console.log(zo.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Sm(),r=tl(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&ol(n),await new Promise(a=>r.on("exit",()=>a()))}});function xm(){try{return j().dashboard.port||4202}catch{return 4202}}function Sm(){let e=km($m(vm(import.meta.url)),"cli.js");return bm(e)?e:process.argv[1]||e}async function Em(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function ol(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=tl(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(zo.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(zo.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Am}from"commander";import Ie from"chalk";var rn=new Am().name("token").description("scoped API tokens for external access (mesh peers, integrations)");rn.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 So,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(Ie.bold(" Token created.")),console.log(),console.log(` id: ${Ie.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ie.dim("never")}`),console.log(),console.log(Ie.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ie.green.bold(s)}`),console.log(),console.log(Ie.dim(" Use it via the Authorization header:")),console.log(Ie.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});rn.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new So().list();if(e.length===0){console.log(Ie.dim(`
14
+ `);a=g.pop()||"";for(let d of g)if(d.startsWith("data: "))try{let u=JSON.parse(d.slice(6)),f=new Date(u.time).toLocaleTimeString(),p=u.message?.replace(/^\[agentx\]\s*/,"")||"";p.includes("executing")?console.log(`${T.dim(f)} ${T.cyan("\u25B6")} ${p}`):p.includes("completed")?console.log(`${T.dim(f)} ${T.green("\u2713")} ${p}`):p.includes("error")||p.includes("Error")?console.log(`${T.dim(f)} ${T.red("\u2717")} ${p}`):p.includes("Routing")?console.log(`${T.dim(f)} ${T.yellow("\u2192")} ${p}`):p.includes("mention")?console.log(`${T.dim(f)} ${T.magenta("@")} ${p}`):p.includes("Skipping")?console.log(`${T.dim(f)} ${T.dim("\u2298")} ${T.dim(p)}`):console.log(`${T.dim(f)} ${p}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(T.red(` Connection failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Diagnostic order:")),console.log(T.dim(" 1) agentx daemon status # is the daemon up?")),console.log(T.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(T.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(T.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(T.dim(" to see the error in the foreground."))}});Xe.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=I(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(T.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(T.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(T.dim(`
15
+ (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(T.red(` Failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Try: agentx daemon status"))}});Xe.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(T.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Tests passed"))}catch{console.log(T.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(T.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(T.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(T.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),o.restart){console.log(T.dim(" Restarting remote daemon once no task is running..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} -t ${o.user}@${e} "cd ${o.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(T.green(" Remote daemon restarted"))}}catch(i){console.log(T.red(` Deploy failed: ${i.message}`))}});Xe.action(async e=>{await new di(e.config).start()});function Om(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 il(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as jm}from"commander";import Qe from"chalk";import{existsSync as an,readFileSync as Im,writeFileSync as rl,mkdirSync as al}from"fs";import{hostname as cl}from"os";import{resolve as kt}from"path";var ll=new jm().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=kt(o,"agentx.json"),n=kt(o,".env"),s=kt(o,".agentx/sessions");if(console.log(),console.log(Qe.bold(" agentx init")),console.log(),an(t)&&!e.force){console.log(Qe.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[kt(o,"agentx.example.json"),kt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(an(c)){r=Im(c,"utf-8");break}r||(r=JSON.stringify({node:{id:cl().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:cl(),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)),rl(t,r),console.log(Qe.green(" \u2713 Created agentx.json")),an(n)||(rl(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
+ `)),console.log(Qe.green(" \u2713 Created .env template"))),an(s)||(al(s,{recursive:!0}),console.log(Qe.green(" \u2713 Created .agentx/sessions/")));let a=kt(o,".claude");an(a)||(al(a,{recursive:!0}),console.log(Qe.green(" \u2713 Created .claude/"))),console.log(),console.log(Qe.bold(" Next steps:")),console.log(` 1. Edit ${Qe.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Qe.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Qe.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Qe.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Cm}from"commander";import zo from"chalk";import{spawn as gl}from"child_process";import{existsSync as Rm}from"fs";import{dirname as Nm,resolve as _m}from"path";import{fileURLToPath as Dm}from"url";ae();var ml=new Cm().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=Oc(),t=e.port?parseInt(e.port,10):Pm(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(zo.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(zo.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(zo.bold(` Opening ${n}`)),console.log(),await Lm(n).catch(()=>!1))console.log(zo.dim(" Dashboard is already running.")),e.open!==!1&&dl(n);else{console.log(zo.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Mm(),r=gl(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&dl(n),await new Promise(a=>r.on("exit",()=>a()))}});function Pm(){try{return I().dashboard.port||4202}catch{return 4202}}function Mm(){let e=_m(Nm(Dm(import.meta.url)),"cli.js");return Rm(e)?e:process.argv[1]||e}async function Lm(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function dl(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=gl(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(zo.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(zo.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Fm}from"commander";import je from"chalk";var cn=new Fm().name("token").description("scoped API tokens for external access (mesh peers, integrations)");cn.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 So,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(je.bold(" Token created.")),console.log(),console.log(` id: ${je.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||je.dim("never")}`),console.log(),console.log(je.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${je.green.bold(s)}`),console.log(),console.log(je.dim(" Use it via the Authorization header:")),console.log(je.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(je.red(` ${o.message}`)),process.exit(1)}});cn.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new So().list();if(e.length===0){console.log(je.dim(`
17
17
  No tokens issued.
18
- `));return}console.log();for(let o of e){let t=o.revokedAt?Ie.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Ie.red("expired"):Ie.green("active");console.log(` ${Ie.cyan(o.id)} ${t} ${o.name}`),console.log(Ie.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Ie.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ie.red(` ${e.message}`)),process.exit(1)}});rn.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new So().revoke(e);o||(console.log(Ie.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ie.green(`
18
+ `));return}console.log();for(let o of e){let t=o.revokedAt?je.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?je.red("expired"):je.green("active");console.log(` ${je.cyan(o.id)} ${t} ${o.name}`),console.log(je.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(je.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(je.red(` ${e.message}`)),process.exit(1)}});cn.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new So().revoke(e);o||(console.log(je.red(` Token ${e} not found.`)),process.exit(1)),console.log(je.green(`
19
19
  \u2713 Revoked ${e} (${o.name})
20
- `))}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});import{Command as Tm}from"commander";import Se from"chalk";import{execFileSync as il}from"child_process";import{existsSync as sl}from"fs";ae();var vt=new Tm().name("app").description("pair phones with the AgentX phone app and manage paired devices");vt.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=Cm(Nm(),ui());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",` tailscale serve --bg --set-path /app http://127.0.0.1:${ui()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${ui()}/api/app`].join(`
21
- `));let t=(e.url?String(e.url):Im()).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 So().create({name:String(e.name),scopes:["app"]}),{code:i}=new vc().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 Om({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!sl("agentx.json")&&!sl(".agentx/config.json")&&console.log(Se.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(Se.red(` ${o.message}`)),process.exit(1)}});vt.command("devices").description("list paired phones").action(()=>{let e=new So().list().filter(o=>o.scopes.includes("app"));if(e.length===0){console.log(Se.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let o of e){let t=o.revokedAt?Se.red("revoked"):Se.green("active");console.log(` ${Se.cyan(o.id)} ${t} ${o.name}`),console.log(Se.dim(` paired: ${o.createdAt}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()});vt.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new So,t=o.list().find(n=>n.id===e&&n.scopes.includes("app"));t||(console.log(Se.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),o.revoke(e),console.log(Se.green(`
20
+ `))}catch(o){console.log(je.red(` ${o.message}`)),process.exit(1)}});import{Command as Um}from"commander";import Se from"chalk";import{execFileSync as ul}from"child_process";import{existsSync as pl}from"fs";ae();var vt=new Um().name("app").description("pair phones with the AgentX phone app and manage paired devices");vt.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=Jm(Hm(),$i());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",` tailscale serve --bg --set-path /app http://127.0.0.1:${$i()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${$i()}/api/app`].join(`
21
+ `));let t=(e.url?String(e.url):Wm()).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 So().create({name:String(e.name),scopes:["app"]}),{code:i}=new Cc().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 qm({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!pl("agentx.json")&&!pl(".agentx/config.json")&&console.log(Se.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(Se.red(` ${o.message}`)),process.exit(1)}});vt.command("devices").description("list paired phones").action(()=>{let e=new So().list().filter(o=>o.scopes.includes("app"));if(e.length===0){console.log(Se.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let o of e){let t=o.revokedAt?Se.red("revoked"):Se.green("active");console.log(` ${Se.cyan(o.id)} ${t} ${o.name}`),console.log(Se.dim(` paired: ${o.createdAt}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()});vt.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new So,t=o.list().find(n=>n.id===e&&n.scopes.includes("app"));t||(console.log(Se.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),o.revoke(e),console.log(Se.green(`
22
22
  \u2713 Unpaired ${e} (${t.name})
23
- `))});vt.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=Ca;try{o=j().channels.push.keysFile}catch{}let t=Na(o),n=Ra(t);if(n&&!e.force){console.log(Se.green(`
23
+ `))});vt.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=Ua;try{o=I().channels.push.keysFile}catch{}let t=qa(o),n=Wa(t);if(n&&!e.force){console.log(Se.green(`
24
24
  \u2713 Keys already exist in ${t} (created ${n.createdAt}).`)),console.log(Se.dim(` Replacing them cuts off every phone; pass --force if you really mean to.
25
- `));return}let{default:s}=await import("web-push");_a(t,s.generateVAPIDKeys()),console.log(Se.green(`
25
+ `));return}let{default:s}=await import("web-push");Ba(t,s.generateVAPIDKeys()),console.log(Se.green(`
26
26
  \u2713 Saved new push keys to ${t}`)),console.log(Se.dim(" Keep this file private. It is readable only by you, and agentx.json never contains it.")),n&&console.log(Se.yellow(" \u26A0 Old keys replaced: open Alerts on each phone and turn notifications on again.")),console.log(Se.dim(` Restart the daemon so it picks up the keys.
27
- `))});function Om(e){let o=Math.round($c/6e4),t=[` Pairing code: ${Se.bold.cyan(kc(e.code))}`,Se.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 ${Se.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Se.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(Se.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function Im(){let e;try{e=JSON.parse(il("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 jm=new Set(["/app","/api/app"]);function Cm(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&&!jm.has(g)&&n.push(`${i}${a}`)}return n}function Nm(){try{return JSON.parse(il("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function ui(){try{return j().dashboard.port||4202}catch{return 4202}}ae();import{Command as lo}from"commander";import h from"chalk";import Re from"prompts";import{readFileSync as To,writeFileSync as xt,existsSync as fe,mkdirSync as co,cpSync as fi,readdirSync as yi}from"fs";import{resolve as H,join as Ao,dirname as Rm}from"path";import{fileURLToPath as _m}from"url";function ce(){let e=H(process.cwd(),"agentx.json");if(!fe(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(To(e,"utf-8"))}function Fe(e){return ye(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 Yo=new lo().name("agent").description("manage agents \u2014 add, list, remove");Yo.command("list").alias("ls").description("list configured agents").action(()=>{let e=ce();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()});Yo.command("add").description("add a new agent interactively").action(async()=>{let e=ce(),o=await Re([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:H(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Ao(o.workspace,o.id);co(H(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Rm(_m(import.meta.url)),"../wiki/SKILL.md"),c=fe(r)?r:a;fe(c)&&(co(H(t,".claude/skills/wiki"),{recursive:!0}),fi(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Fe(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()});Yo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ce();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Fe(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Yo.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=ce(),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 Fe(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 an=new lo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");an.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ce().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 qm(e){let o=Math.round(jc/6e4),t=[` Pairing code: ${Se.bold.cyan(Ic(e.code))}`,Se.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 ${Se.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Se.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(Se.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function Wm(){let e;try{e=JSON.parse(ul("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 Bm=new Set(["/app","/api/app"]);function Jm(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&&!Bm.has(g)&&n.push(`${i}${a}`)}return n}function Hm(){try{return JSON.parse(ul("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function $i(){try{return I().dashboard.port||4202}catch{return 4202}}ae();import{Command as lo}from"commander";import h from"chalk";import Ne from"prompts";import{readFileSync as To,writeFileSync as xt,existsSync as fe,mkdirSync as co,cpSync as ki,readdirSync as xi}from"fs";import{resolve as H,join as Ao,dirname as Gm}from"path";import{fileURLToPath as zm}from"url";function ce(){let e=H(process.cwd(),"agentx.json");if(!fe(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(To(e,"utf-8"))}function Fe(e){return ye(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 Yo=new lo().name("agent").description("manage agents \u2014 add, list, remove");Yo.command("list").alias("ls").description("list configured agents").action(()=>{let e=ce();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()});Yo.command("add").description("add a new agent interactively").action(async()=>{let e=ce(),o=await Ne([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:H(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Ao(o.workspace,o.id);co(H(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Gm(zm(import.meta.url)),"../wiki/SKILL.md"),c=fe(r)?r:a;fe(c)&&(co(H(t,".claude/skills/wiki"),{recursive:!0}),ki(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Fe(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()});Yo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ce();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Fe(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Yo.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=ce(),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 Fe(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 ln=new lo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");ln.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ce().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()});an.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=ce();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-EXNBBAZG.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Re({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 Re({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 Re({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 Re({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 Re({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 Re({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,...w]=f.split("=");p&&(g[p.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(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 Fe(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`))});an.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ce(),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 Fe(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});an.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ce().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)});Yo.addCommand(an);var es=new lo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");es.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ce();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()});es.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ce(),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 Re({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 Re([{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 Fe(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Re([{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 Re([{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 Fe(e),co(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Re([{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 Re([{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 Fe(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 St=new lo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");St.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ce();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()});St.command("add").description("add a cron job").action(async()=>{let e=ce(),o=Object.keys(e.agents||{}),t=await Re([{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 Fe(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});St.command("enable <id>").description("enable a cron job").action(async e=>{let o=ce();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 Fe(o),console.log(h.green(` Cron "${e}" enabled`))});St.command("disable <id>").description("disable a cron job").action(async e=>{let o=ce();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Fe(o),console.log(h.green(` Cron "${e}" disabled`))});var Vo=new lo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Vo.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ce();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()});Vo.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ce(),o=await Re([{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 Fe(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});Vo.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ce();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Fe(o),console.log(h.green(` Peer "${e}" removed`)))});Vo.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=ce();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 Fe(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});Vo.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=j().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var Ko=new lo().name("skill").description("manage skills \u2014 add to agent(s), list");Ko.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=ce(),n=H(e);if(!fe(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=fe(Ao(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 Re({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);co(c,{recursive:!0}),fe(Ao(n,"SKILL.md"))?fi(n,c,{recursive:!0}):n.endsWith(".md")&&fi(n,Ao(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Ko.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ce();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=fe(n)?yi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ko.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>fe(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=To(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=j()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!fe(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=H(v,".claude/skills",e),S=H(A,"SKILL.md");if(!fe(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(co(A,{recursive:!0}),xt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let x=To(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||xt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${u}, ${y} update ${f}, ${p} already current, ${w} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ko.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ce().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=ce();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}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)});Ko.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=ce(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-WORPEXHN.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(`
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()});ln.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=ce();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-VV4X7PEK.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ne({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Ne({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Ne({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await Ne({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Ne({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Ne({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,...w]=f.split("=");p&&(g[p.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(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 Fe(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`))});ln.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ce(),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 Fe(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});ln.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ce().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)});Yo.addCommand(ln);var ss=new lo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");ss.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ce();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()});ss.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ce(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Ne({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Ne([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Fe(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ne([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Fe(e),co(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ne([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await Ne([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Fe(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 St=new lo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");St.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ce();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()});St.command("add").description("add a cron job").action(async()=>{let e=ce(),o=Object.keys(e.agents||{}),t=await Ne([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Fe(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});St.command("enable <id>").description("enable a cron job").action(async e=>{let o=ce();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 Fe(o),console.log(h.green(` Cron "${e}" enabled`))});St.command("disable <id>").description("disable a cron job").action(async e=>{let o=ce();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Fe(o),console.log(h.green(` Cron "${e}" disabled`))});var Vo=new lo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Vo.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ce();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()});Vo.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=ce(),o=await Ne([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Fe(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});Vo.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=ce();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Fe(o),console.log(h.green(` Peer "${e}" removed`)))});Vo.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=ce();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 Fe(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});Vo.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=I().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 Ko=new lo().name("skill").description("manage skills \u2014 add to agent(s), list");Ko.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=ce(),n=H(e);if(!fe(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=fe(Ao(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Ne({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);co(c,{recursive:!0}),fe(Ao(n,"SKILL.md"))?ki(n,c,{recursive:!0}):n.endsWith(".md")&&ki(n,Ao(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Ko.command("list").alias("ls").description("list skills per agent").action(()=>{let e=ce();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=fe(n)?xi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Ko.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>fe(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=To(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=I()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,w=0;for(let[k,b]of d){let v=b.workspace;if(!v||!fe(v)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let A=H(v,".claude/skills",e),S=H(A,"SKILL.md");if(!fe(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(co(A,{recursive:!0}),xt(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let x=To(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let N=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||xt(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${N} \u2192 v${c}`)}`),f++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${u}, ${y} update ${f}, ${p} already current, ${w} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Ko.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-EVHZ2R73.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=ce().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=ce();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}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)});Ko.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=ce(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-EVHZ2R73.js"),{pickSkillForTask:a}=await import("./select-VPOWFRSN.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(`
31
31
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
32
- (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var cn=new lo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");cn.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=H(o.cwd),n=H(t,"references/example"),s=H(t,"references/recipes/example.yaml");fe(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(t,".agentx/references",e),r=H(t,".agentx/references/recipes");co(i,{recursive:!0}),co(r,{recursive:!0});let a=yi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Ao(i,d);if(fe(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=To(Ao(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);xt(u,p),console.log(h.green(` + ${u}`)),c++}let g=Ao(r,`${e}.yaml`);if(fe(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(fe(s)){let d=To(s,"utf-8").replaceAll("example.",`${e}.`);xt(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()});cn.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-EVHZ2R73.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(o.referencesCwd||o.cwd),u=H(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
32
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var dn=new lo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");dn.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=H(o.cwd),n=H(t,"references/example"),s=H(t,"references/recipes/example.yaml");fe(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(t,".agentx/references",e),r=H(t,".agentx/references/recipes");co(i,{recursive:!0}),co(r,{recursive:!0});let a=xi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Ao(i,d);if(fe(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=To(Ao(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);xt(u,p),console.log(h.green(` + ${u}`)),c++}let g=Ao(r,`${e}.yaml`);if(fe(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(fe(s)){let d=To(s,"utf-8").replaceAll("example.",`${e}.`);xt(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()});dn.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-EVHZ2R73.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(o.referencesCwd||o.cwd),u=H(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[w,y]of Object.entries(g))console.log(h.cyan(`
33
33
  --- ${w} ---`)),console.log(y.split(`
34
34
  `).slice(0,30).map(k=>` ${k}`).join(`
35
35
  `)),y.split(`
36
36
  `).length>30&&console.log(h.dim(` \u2026 (${y.split(`
37
- `).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}co(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(g)){let k=Ao(u,w);if(fe(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}xt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});cn.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(H(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var wi=new lo().name("hook").description("manage hooks \u2014 add to agent workspace");wi.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ce().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=H(t.workspace,".claude/settings.json"),s=fe(n)?JSON.parse(To(n,"utf-8")):{},i=await Re([{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),co(H(t.workspace,".claude"),{recursive:!0}),xt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var bi=new lo().name("migrate").description("import configuration from OpenClaw or other tools");bi.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&fe(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(To(n,"utf-8")),i=fe(H(process.cwd(),"agentx.json"))?ce():{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"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===p)||w.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){co(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-42ARC42I.js");y(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 y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let u=H(n,"../cron/jobs.json");if(fe(u)){let f=JSON.parse(To(u,"utf-8")),p=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
37
+ `).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}co(u,{recursive:!0});let f=0,p=0;for(let[w,y]of Object.entries(g)){let k=Ao(u,w);if(fe(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}xt(k,y),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});dn.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(H(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Si=new lo().name("hook").description("manage hooks \u2014 add to agent workspace");Si.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ce().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=H(t.workspace,".claude/settings.json"),s=fe(n)?JSON.parse(To(n,"utf-8")):{},i=await Ne([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),co(H(t.workspace,".claude"),{recursive:!0}),xt(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Ei=new lo().name("migrate").description("import configuration from OpenClaw or other tools");Ei.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&fe(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(To(n,"utf-8")),i=fe(H(process.cwd(),"agentx.json"))?ce():{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"),w=f.groupChat?.mentionPatterns||[];if(w.some(y=>y===p)||w.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){co(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-42ARC42I.js");y(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 y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let u=H(n,"../cron/jobs.json");if(fe(u)){let f=JSON.parse(To(u,"utf-8")),p=0;for(let w of f.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
38
38
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Fe(i),console.log(h.green(`
39
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Oo=new lo().name("config").description("validate and inspect configuration");Oo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=j(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=In(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=fe(H(r,".claude")),c=fe(H(r,"CLAUDE.md")),l=fe(H(r,".claude/settings.json")),g=fe(H(r,".claude/skills"))?yi(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Oo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=j(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Dm(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 hi(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Oo.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-MFNZNWCZ.js"),{expandEnvVars:r}=await import("./config-EXNBBAZG.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(hi(g))});Oo.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-MFNZNWCZ.js"),r=Dm(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: ${hi(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${hi(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})`)))});Oo.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-MFNZNWCZ.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.")))});Oo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=j(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Pm}from"commander";import Io from"chalk";import{resolve as jo}from"path";import{existsSync as Mm}from"fs";var ho=new Pm().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Xo(e){let o=jo(e,".agentx/db.sqlite");Mm(o)||(console.log(Io.red(` No SQLite at ${o}`)),console.log(Io.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=_r({path:o});return t||(console.log(Io.red(` Could not open ${o}`)),console.log(Io.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Qo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Io.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])))}ho.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=Xo(jo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
39
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Oo=new lo().name("config").description("validate and inspect configuration");Oo.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=I(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=Rn(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=fe(H(r,".claude")),c=fe(H(r,"CLAUDE.md")),l=fe(H(r,".claude/settings.json")),g=fe(H(r,".claude/skills"))?xi(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Oo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=I(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Ym(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 vi(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Oo.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-BOE7SMT5.js"),{expandEnvVars:r}=await import("./config-VV4X7PEK.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(vi(g))});Oo.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-BOE7SMT5.js"),r=Ym(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: ${vi(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${vi(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})`)))});Oo.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-BOE7SMT5.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.")))});Oo.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=I(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Vm}from"commander";import jo from"chalk";import{resolve as Io}from"path";import{existsSync as Km}from"fs";var ho=new Vm().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Xo(e){let o=Io(e,".agentx/db.sqlite");Km(o)||(console.log(jo.red(` No SQLite at ${o}`)),console.log(jo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=Jr({path:o});return t||(console.log(jo.red(` Could not open ${o}`)),console.log(jo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function Qo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(jo.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])))}ho.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=Xo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
40
40
  SELECT agent_id, channel, status, duration_ms,
41
41
  input_tokens, output_tokens,
42
42
  substr(message_preview, 1, 60) AS message,
@@ -45,7 +45,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
45
45
  ${t.length?"WHERE "+t.join(" AND "):""}
46
46
  ORDER BY started_at DESC
47
47
  LIMIT @limit
48
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Qo(i,!!e.json)});ho.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=Xo(jo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
48
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Qo(i,!!e.json)});ho.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=Xo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
49
49
  SELECT agent_id, reason, COUNT(*) AS n,
50
50
  ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
51
51
  MAX(last_turn_input_tokens) AS max_input_tokens
@@ -59,14 +59,14 @@ The AgentX daemon and a speech transcription backend must also be available. Run
59
59
  ${s}
60
60
  ORDER BY rotated_at DESC
61
61
  LIMIT @limit
62
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Qo(r,!!e.json)});ho.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=Xo(jo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
62
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Qo(r,!!e.json)});ho.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=Xo(Io(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
63
63
  SELECT day, agent_id, model, tasks,
64
64
  input_tokens AS in_tok, output_tokens AS out_tok,
65
65
  cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
66
66
  FROM usage_daily
67
67
  ${t.length?"WHERE "+t.join(" AND "):""}
68
68
  ORDER BY day DESC, agent_id
69
- `,i=o.prepare(s).all(n);Qo(i,!!e.json)});ho.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=Xo(jo(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
69
+ `,i=o.prepare(s).all(n);Qo(i,!!e.json)});ho.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=Xo(Io(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
70
70
  SELECT channel, kind, deciding_stage, COUNT(*) AS n
71
71
  FROM route_traces
72
72
  ${s}
@@ -79,7 +79,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
79
79
  ${s}
80
80
  ORDER BY at DESC
81
81
  LIMIT @limit
82
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Qo(r,!!e.json)});ho.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Xo(jo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
82
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});Qo(r,!!e.json)});ho.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=Xo(Io(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
83
83
  SELECT agent_id, channel, duration_ms,
84
84
  substr(error, 1, 120) AS error,
85
85
  started_at
@@ -87,12 +87,12 @@ The AgentX daemon and a speech transcription backend must also be available. Run
87
87
  WHERE ${t.join(" AND ")}
88
88
  ORDER BY started_at DESC
89
89
  LIMIT @limit
90
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Qo(i,!!e.json)});ho.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Xo(jo(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Qo(n,!!e.json)});ho.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=Xo(jo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Io.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Io.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Qo(n,!!o.json)}catch(n){console.log(Io.red(` ${n.message}`)),process.exit(1)}});import{Command as Um}from"commander";import z from"chalk";import{mkdtempSync as qm}from"fs";import{tmpdir as Wm}from"os";import{resolve as al,join as cl}from"path";import{existsSync as Bm}from"fs";import Jm from"better-sqlite3";function rl(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=Lm(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=Hr(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:Fm(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Lm(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Fm(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 Co=new Um().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Et(e){let o=al(e.cwd??process.cwd()),t=al(o,e.path??".agentx/intent/ledger.sqlite");Bm(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Jm(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Zo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function Hm(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 os(e){if(!e)return;let o=Hm(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Co.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=Et(e),t=os(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(`
90
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});Qo(i,!!e.json)});ho.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Xo(Io(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}));Qo(n,!!e.json)});ho.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=Xo(Io(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(jo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(jo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();Qo(n,!!o.json)}catch(n){console.log(jo.red(` ${n.message}`)),process.exit(1)}});import{Command as Zm}from"commander";import z from"chalk";import{mkdtempSync as ep}from"fs";import{tmpdir as op}from"os";import{resolve as hl,join as yl}from"path";import{existsSync as tp}from"fs";import np from"better-sqlite3";function fl(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=Xm(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=oa(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:Qm(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Xm(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Qm(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 Co=new Zm().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Et(e){let o=hl(e.cwd??process.cwd()),t=hl(o,e.path??".agentx/intent/ledger.sqlite");tp(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new np(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Zo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function sp(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 is(e){if(!e)return;let o=sp(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Co.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=Et(e),t=is(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(`
91
91
  SELECT COUNT(*) as n FROM intent_decisions d
92
92
  LEFT JOIN intent_resolutions r
93
93
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
94
94
  WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
95
- `).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(z.bold("Events by source")),Zo(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),Zo(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),Zo(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});Co.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=Et(e),t=os(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(`
95
+ `).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(z.bold("Events by source")),Zo(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),Zo(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),Zo(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});Co.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=Et(e),t=is(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(`
96
96
  SELECT
97
97
  datetime(ts/1000, 'unixepoch') AS at,
98
98
  source,
@@ -122,7 +122,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
122
122
  WHERE ${t.join(" AND ")}
123
123
  ORDER BY d.decided_at DESC
124
124
  LIMIT @limit
125
- `).all(n);Zo(s,!!e.json)});Co.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=Et(e),t=os(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(`
125
+ `).all(n);Zo(s,!!e.json)});Co.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=Et(e),t=is(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(`
126
126
  SELECT
127
127
  datetime(ts/1000, 'unixepoch') AS at,
128
128
  source,
@@ -142,7 +142,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
142
142
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
143
143
  WHERE d.event_id IN (${a})
144
144
  ORDER BY d.decided_at ASC
145
- `).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(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.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(` ${z.dim(u)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let p of f){let w=p.outcome==="dispatched"?z.green(p.outcome):p.outcome==="dropped"?z.dim(p.outcome):z.yellow(p.outcome),y=p.agent_id?z.cyan(p.agent_id):z.dim("-"),k=p.reason?z.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(p.decided_by)} \u2192 ${w} ${y}${k}`),p.resolution_status){let b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),v=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(v)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});Co.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=Et(e),t=os(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(`
145
+ `).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(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.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(` ${z.dim(u)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let p of f){let w=p.outcome==="dispatched"?z.green(p.outcome):p.outcome==="dropped"?z.dim(p.outcome):z.yellow(p.outcome),y=p.agent_id?z.cyan(p.agent_id):z.dim("-"),k=p.reason?z.dim(` \u2014 ${p.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(p.decided_by)} \u2192 ${w} ${y}${k}`),p.resolution_status){let b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),v=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(v)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});Co.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=Et(e),t=is(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(`
146
146
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
147
147
  FROM intent_events
148
148
  ${n.length?"WHERE "+n.join(" AND "):""}
@@ -156,7 +156,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
156
156
  SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
157
157
  FROM intent_resolutions
158
158
  WHERE decision_event_id IN (${c})
159
- `).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=qm(cl(Wm(),"agentx-ledger-replay-")),f=new Mr({path:cl(u,"target.sqlite")});try{let p=rl(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(z.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${p.divergences.length} divergences`)),Zo(p.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});wr();Mg();Lg();Fg();Dg();Ir();zt();import{Command as Gm}from"commander";import q from"chalk";import{existsSync as ll}from"fs";import{resolve as $i}from"path";import zm from"better-sqlite3";var We=new Gm().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Ze=".agentx/decisions/decisions.sqlite";function Ym(e){return $i($i(e.cwd??process.cwd()),e.path??Ze)}function mo(e,o=!1){let t=Ym(e);ll(t)||(console.log(q.red(` No decision store at ${t}`)),console.log(q.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 On({path:t,readonly:!o})}catch(n){console.log(q.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(q.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function go(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(q.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(q.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function ki(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 vi(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:ki(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}We.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",Ze).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=mo(e),t=ki(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
159
+ `).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=ep(yl(op(),"agentx-ledger-replay-")),f=new zr({path:yl(u,"target.sqlite")});try{let p=fl(f,r,g,d);if(e.json){console.log(JSON.stringify(p,null,2));return}console.log(z.bold(`Replayed ${p.eventsCount} events, ${p.decisionsCount} decisions, ${d.length} resolutions`)),p.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${p.divergences.length} divergences`)),Zo(p.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{f.close()}});Or();Kg();Xg();Qg();Yg();Fr();Vt();import{Command as ip}from"commander";import q from"chalk";import{existsSync as wl}from"fs";import{resolve as Ai}from"path";import rp from"better-sqlite3";var We=new ip().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Ze=".agentx/decisions/decisions.sqlite";function ap(e){return Ai(Ai(e.cwd??process.cwd()),e.path??Ze)}function mo(e,o=!1){let t=ap(e);wl(t)||(console.log(q.red(` No decision store at ${t}`)),console.log(q.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 Cn({path:t,readonly:!o})}catch(n){console.log(q.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(q.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function go(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(q.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(q.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function Ti(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 Oi(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Ti(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}We.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",Ze).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=mo(e),t=Ti(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
160
160
  COUNT(*) AS calls,
161
161
  SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
162
162
  SUM(retries) AS retries,
@@ -171,11 +171,11 @@ The AgentX daemon and a speech transcription backend must also be available. Run
171
171
  ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(q.bold(`
172
172
  policy`)),go(s,!1),console.log(q.dim(`
173
173
  explored=1 means the policy wanted to skip and the expensive path ran anyway.
174
- Those are the only rows in the skip region that can ever be graded.`))),o.close()});We.command("calls").description("recent calls").option("--path <file>","store path",Ze).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=mo(e),t=["ts >= ?"],n=[ki(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,
174
+ Those are the only rows in the skip region that can ever be graded.`))),o.close()});We.command("calls").description("recent calls").option("--path <file>","store path",Ze).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=mo(e),t=["ts >= ?"],n=[Ti(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,
175
175
  structure_mode AS structure, latency_ms AS ms, retries, truncated, error
176
176
  FROM decision_calls WHERE ${t.join(" AND ")}
177
- ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));go(s,e.json),o.close()});We.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",Ze).option("--json").action((e,o)=>{let t=mo(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(q.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}go(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()});We.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",Ze).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=mo(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(q.green(` labeled ${e}.${o} = ${t}`)),s.close()});We.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",Ze).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=mo(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));go(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});We.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",Ze).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=mo(e,!0),t=$i(process.cwd(),e.db);ll(t)||(console.log(q.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new zm(t,{readonly:!0});try{let s=aa(n,o);console.log(q.green(` wrote ${s} label(s)`)),s===0&&console.log(q.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
178
- label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});We.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",Ze).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=mo(e),t=o.gradedRows(vi(e)),n=Er(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(q.bold(`
177
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));go(s,e.json),o.close()});We.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",Ze).option("--json").action((e,o)=>{let t=mo(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(q.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}go(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()});We.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",Ze).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=mo(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(q.green(` labeled ${e}.${o} = ${t}`)),s.close()});We.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",Ze).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=mo(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));go(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});We.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",Ze).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=mo(e,!0),t=Ai(process.cwd(),e.db);wl(t)||(console.log(q.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new rp(t,{readonly:!0});try{let s=ya(n,o);console.log(q.green(` wrote ${s} label(s)`)),s===0&&console.log(q.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
178
+ label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});We.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",Ze).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=mo(e),t=o.gradedRows(Oi(e)),n=Dr(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(q.bold(`
179
179
  ${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(q.yellow(`
180
180
  Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(q.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(q.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
181
181
  accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+q.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${q.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${q.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${q.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
@@ -183,21 +183,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
183
183
  skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(q.yellow(` Nothing in the skip region has been graded. Everything below describes
184
184
  only the decisions this policy chose NOT to skip \u2014 it cannot tell you
185
185
  what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(q.bold(`
186
- reliability (equal-width bins)`)),go(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()});We.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",Ze).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=mo(e),t=o.gradedRows(vi(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Ar(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(q.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(q.bold(`
186
+ reliability (equal-width bins)`)),go(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()});We.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",Ze).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=mo(e),t=o.gradedRows(Oi(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Pr(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(q.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(q.bold(`
187
187
  ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(q.dim(` Cross-validated, because more parameters always fit training data better.
188
188
  `)),go(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(q.green(`
189
189
  Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(q.dim(" that need different corrections."))):s.best==="temperature"?console.log(q.dim(`
190
190
  One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(q.dim(`
191
- Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});We.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",Ze).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=mo(e),t=o.gradedRows({...vi(e),labeledOnly:!0}),n=Sr(t,Number(e.steps));if(n.length===0){console.log(q.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}go(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()});We.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",Ze).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=>{ct();let o=mo(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
191
+ Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});We.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",Ze).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=mo(e),t=o.gradedRows({...Oi(e),labeledOnly:!0}),n=_r(t,Number(e.steps));if(n.length===0){console.log(q.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}go(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()});We.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",Ze).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=>{ct();let o=mo(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
192
192
  WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
193
193
  ${e.call?"AND id = ?":""}
194
- ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(q.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(q.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 Tr(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(q.bold(`
194
+ ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(q.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(q.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 Mr(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(q.bold(`
195
195
  ${e.seat} on ${i.backend} (${i.model})`)),console.log(q.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
196
196
  `)),go(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?q.red("NO"):"yes"})),!1),console.log(`
197
197
  mean stdev ${i.meanStdev.toFixed(4)}`),console.log(q.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(q.red(`
198
198
  Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(q.dim(` not merely by how much. Usually a compound question: one name, several questions.
199
199
  Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(q.green(`
200
- Every question held its decision across all samples.`)),console.log(q.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()});We.command("backends").description("registered decision backends and what they claim").action(()=>{ct();let e=yr().map(o=>{let t=qs(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});go(e,!1),console.log(q.dim(`
200
+ Every question held its decision across all samples.`)),console.log(q.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()});We.command("backends").description("registered decision backends and what they claim").action(()=>{ct();let e=Tr().map(o=>{let t=zs(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});go(e,!1),console.log(q.dim(`
201
201
  source where the numbers come from. "verbalized" means the model wrote them
202
202
  into its answer; "logits" means they were read off its next-token
203
203
  distribution. Logits are the model's actual posterior \u2014 verbalized
@@ -205,22 +205,22 @@ The AgentX daemon and a speech transcription backend must also be available. Run
205
205
  calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
206
206
  traffic. Reading real logits does not buy this: a posterior can be
207
207
  confidently wrong. It comes from a recalibrator fitted on your own
208
- labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});We.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=>{ct();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=at(s,"Which option fits this state?")}e.noul&&(o.verdict=fo(String(e.noul))),Object.keys(o).length===0&&(console.log(q.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await qs(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Zm}from"commander";import O from"chalk";import{resolve as hl}from"path";import{existsSync as ep}from"fs";import op from"better-sqlite3";var dl=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],Vm=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function ml(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...Vm,...dl,"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(`
208
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});We.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=>{ct();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=at(s,"Which option fits this state?")}e.noul&&(o.verdict=fo(String(e.noul))),Object.keys(o).length===0&&(console.log(q.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await zs(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as mp}from"commander";import O from"chalk";import{resolve as El}from"path";import{existsSync as pp}from"fs";import up from"better-sqlite3";var bl=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],cp=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function kl(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...cp,...bl,"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(`
209
209
  SELECT ${s} FROM task_traces WHERE ${a} ORDER BY started_at
210
210
  `).all(...r),l=new Map,g=e.prepare(`
211
211
  SELECT task_id, action FROM task_trace_steps
212
212
  WHERE name = 'tool_use' AND action IS NOT NULL
213
213
  AND task_id IN (SELECT task_id FROM task_traces WHERE ${a})
214
214
  ORDER BY task_id, seq
215
- `).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=ga({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:[]}),w=dl.map(y=>d[y]).filter(y=>typeof y=="number");return{taskId:u,agentId:f,cluster:p,startedAt:d.started_at,ok:d.status==="ok",tokens:w.length>0?w.reduce((y,k)=>y+k,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:Gr(d.injected_context)}})}function xi(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function Si(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 gl(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:Si(e.map(o=>o.tokens)),medianTurns:Si(e.map(o=>o.turns)),medianDurationMs:Si(e.map(o=>o.durationMs))}}function pl(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 xi(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(xi));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=>xi(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:gl(u),after:gl(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import No from"chalk";function Km(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function Xm(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function Qm(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function Ei(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 ul(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 ${Km(o.medianTokens)}${t?Ei(t.medianTokens,o.medianTokens):""}`,`turns ${Qm(o.medianTurns)}${t?Ei(t.medianTurns,o.medianTurns):""}`,`time ${Xm(o.medianDurationMs)}${t?Ei(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function fl(e,o){if(e.length===0)return[No.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),No.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(`${No.bold(s.agentId)} ${No.cyan(s.cluster)}`),n=i),t.push(` ${No.yellow(s.lesson)} ${No.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(No.dim(ul("before",s.before))),t.push(ul("after",s.after,s.before))}return t.push(""),t.push(No.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var At=new Zm().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function ns(e){let o=hl(e.cwd??process.cwd()),t=hl(o,e.path??".agentx/db.sqlite");ep(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 op(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 tp(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 yl(e){if(!e)return;let o=tp(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 np(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 Ai(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}At.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=ns(e),t=zr(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:yl(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=Ai(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(np(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});At.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=ns(o),n=Hs(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}sp(n.task,n.steps)});function sp(e,o){let t=Ai(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?Ai(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(`
215
+ `).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=$a({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:[]}),w=bl.map(y=>d[y]).filter(y=>typeof y=="number");return{taskId:u,agentId:f,cluster:p,startedAt:d.started_at,ok:d.status==="ok",tokens:w.length>0?w.reduce((y,k)=>y+k,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:ta(d.injected_context)}})}function ji(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function Ii(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 $l(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:Ii(e.map(o=>o.tokens)),medianTurns:Ii(e.map(o=>o.turns)),medianDurationMs:Ii(e.map(o=>o.durationMs))}}function vl(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 ji(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(ji));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=>ji(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:$l(u),after:$l(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Ro from"chalk";function lp(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function dp(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function gp(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function Ci(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 xl(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 ${lp(o.medianTokens)}${t?Ci(t.medianTokens,o.medianTokens):""}`,`turns ${gp(o.medianTurns)}${t?Ci(t.medianTurns,o.medianTurns):""}`,`time ${dp(o.medianDurationMs)}${t?Ci(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function Sl(e,o){if(e.length===0)return[Ro.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Ro.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(`${Ro.bold(s.agentId)} ${Ro.cyan(s.cluster)}`),n=i),t.push(` ${Ro.yellow(s.lesson)} ${Ro.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Ro.dim(xl("before",s.before))),t.push(xl("after",s.after,s.before))}return t.push(""),t.push(Ro.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var At=new mp().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function as(e){let o=El(e.cwd??process.cwd()),t=El(o,e.path??".agentx/db.sqlite");pp(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 up(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 fp(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 Al(e){if(!e)return;let o=fp(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 hp(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 Ri(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}At.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=as(e),t=na(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Al(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=Ri(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(hp(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});At.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=as(o),n=Xs(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}yp(n.task,n.steps)});function yp(e,o){let t=Ri(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?Ri(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(`
216
216
  `).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2192")} ${a}`).join(`
217
217
  `)),n.inputSummary.split(`
218
218
  `).length>8&&console.log(` ${O.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
219
219
  `).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2190")} ${a}`).join(`
220
220
  `)),n.outputSummary.split(`
221
- `).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}At.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=ns(e),t=Math.max(1,parseInt(e.min,10)||2),n=ml(o,{since:yl(e.since),agentId:e.agent}),s=pl(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of fl(s,{minSamples:t}))console.log(i)});At.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=ns(o),n=Hs(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(),ts(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?ts(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(),ts(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(),ts(d.content??"(empty reply)"),d.error&&console.log(O.red(`
222
- error: ${d.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function ts(e){let o=e.split(`
223
- `),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 cp}from"commander";import pe from"chalk";import{existsSync as lp,mkdirSync as dp,writeFileSync as gp}from"fs";import{resolve as $l,join as bl,dirname as mp}from"path";var ip=`# AgentX destructive-action guardrails \u2014 global policy
221
+ `).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}At.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=as(e),t=Math.max(1,parseInt(e.min,10)||2),n=kl(o,{since:Al(e.since),agentId:e.agent}),s=vl(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of Sl(s,{minSamples:t}))console.log(i)});At.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=as(o),n=Xs(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(),rs(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?rs(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(),rs(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(),rs(d.content??"(empty reply)"),d.error&&console.log(O.red(`
222
+ error: ${d.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function rs(e){let o=e.split(`
223
+ `),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 kp}from"commander";import pe from"chalk";import{existsSync as vp,mkdirSync as xp,writeFileSync as Sp}from"fs";import{resolve as jl,join as Ol,dirname as Ep}from"path";var wp=`# AgentX destructive-action guardrails \u2014 global policy
224
224
  #
225
225
  # This file + environments/*.yaml + agents/<id>.yaml are deep-merged
226
226
  # (most specific wins). The built-in catalog (prisma / rm -rf / docker /
@@ -246,7 +246,7 @@ defaults:
246
246
  # action: escalate
247
247
  # severity: high
248
248
  rules: []
249
- `,rp=`# Production protected resources.
249
+ `,bp=`# Production protected resources.
250
250
  #
251
251
  # The catalog rules reference \`target_in: production\`, so DECLARING this set is
252
252
  # what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
@@ -268,7 +268,7 @@ protected_resources:
268
268
 
269
269
  # Production-only rules beyond the catalog:
270
270
  rules: []
271
- `,ap=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
271
+ `,$p=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
272
272
  # this agent (the filename names it). coder agents never touch production.
273
273
  rules:
274
274
  - id: coder-no-prod
@@ -277,7 +277,7 @@ rules:
277
277
  action: deny
278
278
  severity: critical
279
279
  message: "coder-agent is not permitted to run commands against production."
280
- `,wl=[{relPath:"policy.yaml",content:ip},{relPath:"environments/production.yaml",content:rp},{relPath:"agents/coder-agent.yaml",content:ap}];var Ro=new cp().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Ti(e){return e==="deny"?pe.red:e==="escalate"||e==="ask"?pe.yellow:e==="warn"?pe.magenta:pe.green}function ss(e){return e.root?$l(e.root):Za()}Ro.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 Qa({root:ss(e),agentId:e.agent,env:e.env}),process.exit(0)});Ro.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=ss(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Xa({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}pp(s,i,r)});function pp(e,o,t){let n=Ti(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":pe.dim(" (no rule matched)")}`),console.log(` enforced as ${Ti(e.effectiveAction)(e.effectiveAction)} ${pe.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${pe.cyan(e.ruleId)}${e.severity?pe.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${pe.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${pe.dim(`evaluated in ${t}ms`)}`),console.log()}Ro.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=Dr({root:ss(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(pe.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=Ti(t.verdict),i=t.effective_action!==t.verdict?pe.dim(`->${t.effective_action}`):"";console.log(` ${pe.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${pe.cyan((t.agent_id??"?").padEnd(16))} ${pe.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(pe.dim(` target: ${t.resolved_target}`))}});Ro.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=bl($l(e.root),Va),t=0;for(let n of wl){let s=bl(o,n.relPath);if(lp(s)&&!e.force){console.log(pe.dim(` skip (exists) ${n.relPath}`));continue}dp(mp(s),{recursive:!0}),gp(s,n.content),console.log(pe.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${pe.cyan(o)}`),console.log(pe.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(pe.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Ro.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(pe.green(` daemon reloaded (${e.url})`)):console.log(pe.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(pe.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Ro.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=Ka(ss(e),e.agent);console.log(JSON.stringify(o,null,2))});Yt();import{Command as up}from"commander";import{execFile as fp}from"child_process";import{promisify as hp}from"util";import{existsSync as yp}from"fs";import eo from"chalk";zt();var dn="ui-element";function is(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:ln(t.tried,80),screenChanged:t.changed,note:t.note?ln(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:kl(t.role),label:ln(t.label,120),value:t.value?ln(t.value,80):null,enabled:t.enabled}))}}function rs(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${kl(t.role)}: ${ln(n,80)}`}return{target:at(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:fo("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 as(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 kl(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function ln(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var vl=hp(fp),xl=new up().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{yp(Ne)||(console.log(eo.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await qn({max:Number(o.max)||40})}catch(d){console.log(eo.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(eo.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=en(t,n[0].id);d&&(console.log(eo.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+eo.bold(n[0].label)),await vl(Ne,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await io(dn,is({request:e,app:t.app,window:t.window,candidates:n}),rs(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(eo.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${dn}.mode`)),process.exit(1));let i=as(s.answers,n),r=en(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(eo.yellow(` nothing on screen matches "${e}"`)+eo.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(` ${eo.green("\u2192")} ${eo.bold(g)} `+eo.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await vl(Ne,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Fp}from"commander";import Be from"chalk";import{readFileSync as Sl}from"fs";import{homedir as wp}from"os";import{join as bp}from"path";var El=12e5,$p="https://openrouter.ai/api/v1/chat/completions",kp=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function vp(e={kind:"window"},o=El,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return wt(e,{},n);try{return await wt(e,{untilStable:!0},n)}catch(s){if(s instanceof yc)return wt(e,{},n);throw s}}var xp=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
280
+ `,Tl=[{relPath:"policy.yaml",content:wp},{relPath:"environments/production.yaml",content:bp},{relPath:"agents/coder-agent.yaml",content:$p}];var No=new kp().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Ni(e){return e==="deny"?pe.red:e==="escalate"||e==="ask"?pe.yellow:e==="warn"?pe.magenta:pe.green}function cs(e){return e.root?jl(e.root):cc()}No.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 ac({root:cs(e),agentId:e.agent,env:e.env}),process.exit(0)});No.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=cs(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=rc({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}Ap(s,i,r)});function Ap(e,o,t){let n=Ni(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":pe.dim(" (no rule matched)")}`),console.log(` enforced as ${Ni(e.effectiveAction)(e.effectiveAction)} ${pe.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${pe.cyan(e.ruleId)}${e.severity?pe.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${pe.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${pe.dim(`evaluated in ${t}ms`)}`),console.log()}No.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=Hr({root:cs(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(pe.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=Ni(t.verdict),i=t.effective_action!==t.verdict?pe.dim(`->${t.effective_action}`):"";console.log(` ${pe.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${pe.cyan((t.agent_id??"?").padEnd(16))} ${pe.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(pe.dim(` target: ${t.resolved_target}`))}});No.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=Ol(jl(e.root),sc),t=0;for(let n of Tl){let s=Ol(o,n.relPath);if(vp(s)&&!e.force){console.log(pe.dim(` skip (exists) ${n.relPath}`));continue}xp(Ep(s),{recursive:!0}),Sp(s,n.content),console.log(pe.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${pe.cyan(o)}`),console.log(pe.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(pe.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});No.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(pe.green(` daemon reloaded (${e.url})`)):console.log(pe.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(pe.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});No.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=ic(cs(e),e.agent);console.log(JSON.stringify(o,null,2))});Kt();import{Command as Tp}from"commander";import{execFile as Op}from"child_process";import{promisify as jp}from"util";import{existsSync as Ip}from"fs";import eo from"chalk";Vt();var mn="ui-element";function ls(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:gn(t.tried,80),screenChanged:t.changed,note:t.note?gn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Il(t.role),label:gn(t.label,120),value:t.value?gn(t.value,80):null,enabled:t.enabled}))}}function ds(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Il(t.role)}: ${gn(n,80)}`}return{target:at(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:fo("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 gs(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 Il(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function gn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var Cl=jp(Op),Rl=new Tp().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{Ip(Re)||(console.log(eo.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await Hn({max:Number(o.max)||40})}catch(d){console.log(eo.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(eo.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=tn(t,n[0].id);d&&(console.log(eo.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+eo.bold(n[0].label)),await Cl(Re,["point","--x",String(d.x),"--y",String(d.y),"--w",String(d.width),"--h",String(d.height),"--label",n[0].label]));return}let s=await io(mn,ls({request:e,app:t.app,window:t.window,candidates:n}),ds(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(eo.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${mn}.mode`)),process.exit(1));let i=gs(s.answers,n),r=tn(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(eo.yellow(` nothing on screen matches "${e}"`)+eo.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(` ${eo.green("\u2192")} ${eo.bold(g)} `+eo.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Cl(Re,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Qp}from"commander";import Be from"chalk";import{readFileSync as Nl}from"fs";import{homedir as Cp}from"os";import{join as Rp}from"path";var _l=12e5,Np="https://openrouter.ai/api/v1/chat/completions",_p=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Dp(e={kind:"window"},o=_l,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return wt(e,{},n);try{return await wt(e,{untilStable:!0},n)}catch(s){if(s instanceof Ac)return wt(e,{},n);throw s}}var Pp=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
281
281
 
282
282
  Report only what is visible in this image.
283
283
 
@@ -285,13 +285,13 @@ The failure that matters: an application that performs an action is on screen, a
285
285
 
286
286
  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.
287
287
 
288
- 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 Sp(e,o,t,n){let s=Ap();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=Sl(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
288
+ 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 Mp(e,o,t,n){let s=Fp();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=Nl(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
289
289
 
290
- The image is the region ${Ep(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:xp,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($p,{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 cs(e,o={}){let t=Date.now(),n=await vp(o.region??{kind:"window"},o.maxPixels??El,{settle:o.settle,screen:o.screen}),s=await Sp(e,n,o.model??kp,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 Ep(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 Ap(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(gn!==void 0)return gn??void 0;try{let e=Sl(bp(wp(),".agentx","openrouter-key.txt"),"utf-8").trim();gn=e.length>0?e:null}catch{gn=null}return gn??void 0}import{execFile as Tp}from"child_process";import{promisify as Op}from"util";var Ip=Op(Tp),jp=["screencapture"],Cp=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Tl(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Np()),t}async function Np(){let e=await Al(jp);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 Al(Cp);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 Al(e){let o=[];for(let t of e)try{let{stdout:n}=await Ip("pgrep",["-x",t]),s=n.trim().split(`
291
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Yt();zt();var Ol="screen-state",Il={observable:fo("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:fo("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 jl(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 Cl(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Rp=.6,_p=.7,Dp=.3;async function mn(e,o={}){let[t,n]=await Promise.all([cs(e,o),Tl(e).catch(()=>[])]),s=o.observableFloor??Rp,i=await io(Ol,jl({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Lp(t),treeNote:o.treeNote,probes:n}),Il,{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:Mp(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=Cl(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 (${ls(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=_p?"confirmed":a<=Dp?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Pp(c,a,t),sighting:t,probes:n}}function Pp(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${ls(o)}). ${n}`:e==="refuted"?`Not true (${ls(1-o)} it is false). ${n}`:`Inconclusive (${ls(o)}, between the thresholds). ${n}`}function Mp(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 Lp(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 ls=e=>`${Math.round(e*100)}%`;var Nl=new Fp().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(Be.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 mn(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?ro():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"?Be.green("\u2713"):s.outcome==="refuted"?Be.red("\u2717"):Be.yellow("?");console.log(` ${i} ${Be.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Be.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Be.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 cs(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?ro():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Be.bold(n.observation)}`),n.evidence&&console.log(Be.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Up(n.reading)}`),console.log(Be.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Be.red(` ${n?.message??n}`)),process.exit(1)}});function Up(e){return e==="yes"?Be.green(e):e==="no"?Be.red(e):Be.yellow(e)}import{Command as qp}from"commander";import oo from"chalk";import{spawn as Wp}from"child_process";function _o(e){console.log(oo.red(` ${e}`)),process.exit(1)}function Rl(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?oo.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(oo.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function Bp(e){return new Promise(o=>{let t=Wp(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var pn=new qp("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");pn.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=ro(o.config),n;try{n=Wn(o.region,t)}catch(r){_o(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&_o("--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 Bn(()=>Bp(e),n,{out:o.out,untilStable:r},i);c||(console.log(oo.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),Rl(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}Rl(await wt(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){_o(r?.message??String(r))}});pn.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:${Go()}`).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||_o(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(oo.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${oo.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){_o(`could not reach the daemon: ${n?.message??n}`)}});pn.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&&_o(`--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)||_o("--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=ro(e.config);console.log(`
290
+ The image is the region ${Lp(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Pp,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(Np,{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 ms(e,o={}){let t=Date.now(),n=await Dp(o.region??{kind:"window"},o.maxPixels??_l,{settle:o.settle,screen:o.screen}),s=await Mp(e,n,o.model??_p,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 Lp(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 pn;function Fp(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(pn!==void 0)return pn??void 0;try{let e=Nl(Rp(Cp(),".agentx","openrouter-key.txt"),"utf-8").trim();pn=e.length>0?e:null}catch{pn=null}return pn??void 0}import{execFile as Up}from"child_process";import{promisify as qp}from"util";var Wp=qp(Up),Bp=["screencapture"],Jp=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Pl(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Hp()),t}async function Hp(){let e=await Dl(Bp);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 Dl(Jp);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 Dl(e){let o=[];for(let t of e)try{let{stdout:n}=await Wp("pgrep",["-x",t]),s=n.trim().split(`
291
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}Kt();Vt();var Ml="screen-state",Ll={observable:fo("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:fo("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 Fl(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 Ul(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Gp=.6,zp=.7,Yp=.3;async function un(e,o={}){let[t,n]=await Promise.all([ms(e,o),Pl(e).catch(()=>[])]),s=o.observableFloor??Gp,i=await io(Ml,Fl({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Xp(t),treeNote:o.treeNote,probes:n}),Ll,{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:Kp(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=Ul(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 (${ps(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=zp?"confirmed":a<=Yp?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Vp(c,a,t),sighting:t,probes:n}}function Vp(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${ps(o)}). ${n}`:e==="refuted"?`Not true (${ps(1-o)} it is false). ${n}`:`Inconclusive (${ps(o)}, between the thresholds). ${n}`}function Kp(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 Xp(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 ps=e=>`${Math.round(e*100)}%`;var ql=new Qp().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(Be.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 un(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?ro():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"?Be.green("\u2713"):s.outcome==="refuted"?Be.red("\u2717"):Be.yellow("?");console.log(` ${i} ${Be.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Be.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Be.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 ms(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?ro():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Be.bold(n.observation)}`),n.evidence&&console.log(Be.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Zp(n.reading)}`),console.log(Be.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Be.red(` ${n?.message??n}`)),process.exit(1)}});function Zp(e){return e==="yes"?Be.green(e):e==="no"?Be.red(e):Be.yellow(e)}import{Command as eu}from"commander";import oo from"chalk";import{spawn as ou}from"child_process";function _o(e){console.log(oo.red(` ${e}`)),process.exit(1)}function Wl(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?oo.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(oo.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function tu(e){return new Promise(o=>{let t=ou(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var fn=new eu("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");fn.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=ro(o.config),n;try{n=Gn(o.region,t)}catch(r){_o(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&_o("--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 zn(()=>tu(e),n,{out:o.out,untilStable:r},i);c||(console.log(oo.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),Wl(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}Wl(await wt(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){_o(r?.message??String(r))}});fn.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:${Go()}`).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||_o(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(oo.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${oo.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){_o(`could not reach the daemon: ${n?.message??n}`)}});fn.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&&_o(`--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)||_o("--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=ro(e.config);console.log(`
292
292
  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(" "):oo.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":oo.dim("off")} ${oo.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
293
- `);return}try{let{summary:s,backupPath:i}=ao(r=>{let a=hc(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(oo.green(`
294
- \u2713 ${s}`)),i&&console.log(oo.dim(` Backup: ${i}`)),console.log()}catch(s){_o(s?.message??String(s))}});Yt();import{Command as Gp}from"commander";import{execFile as ql}from"child_process";import{promisify as zp}from"util";import{existsSync as Yp,readFileSync as Vp,writeFileSync as Wl,mkdirSync as Kp}from"fs";import{homedir as Xp}from"os";import{join as Qp,dirname as Zp}from"path";import De from"chalk";zt();var Oi="paste-transform";function _l(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Dl(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:fo("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:at(o,"What shape should this paste arrive in?")}}function Pl(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 Jp=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"]),Hp=e=>/^https?:\/\/\S+$/i.test(e.trim()),Ii=[{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(`
293
+ `);return}try{let{summary:s,backupPath:i}=ao(r=>{let a=Ec(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(oo.green(`
294
+ \u2713 ${s}`)),i&&console.log(oo.dim(` Backup: ${i}`)),console.log()}catch(s){_o(s?.message??String(s))}});Kt();import{Command as iu}from"commander";import{execFile as Kl}from"child_process";import{promisify as ru}from"util";import{existsSync as au,readFileSync as cu,writeFileSync as Xl,mkdirSync as lu}from"fs";import{homedir as du}from"os";import{join as gu,dirname as mu}from"path";import De from"chalk";Vt();var _i="paste-transform";function Bl(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Jl(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:fo("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:at(o,"What shape should this paste arrive in?")}}function Hl(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 nu=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"]),su=e=>/^https?:\/\/\S+$/i.test(e.trim()),Di=[{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(`
295
295
  `);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(`
296
296
  `).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
297
297
 
@@ -299,26 +299,26 @@ The image is the region ${Ep(o)}.`},{type:"image_url",image_url:{url:`data:image
299
299
  `).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
300
300
  `)}},{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(`
301
301
  `);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
302
- `)}},{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(!Hp(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Jp.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(`
302
+ `)}},{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(!su(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])nu.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(`
303
303
  `)||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,`
304
- `).trim();return o===e?null:o}}];function Ml(e){let o=[];for(let t of Ii){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Ll(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
304
+ `).trim();return o===e?null:o}}];function Gl(e){let o=[];for(let t of Di){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function zl(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
305
305
  \u2026[${e.length-o} more characters]\u2026
306
- ${e.slice(-n)}`}function Fl(e){let o=e.trim();return o.includes(`
307
- `)||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 ji=zp(ql),Bl=new Gp().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 (${Ii.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=ou();c===null&&(console.log(De.yellow(" nothing to undo")),process.exit(2)),await Hl(c),console.log(` ${De.green("\u2192")} clipboard restored`);return}let o=await tu();if(o||(console.log(De.yellow(" clipboard is empty")),process.exit(2)),Fl(o)){Jl(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Ml(o),n=await nu();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(De.red(` "${e.as}" does not apply to this clipboard`)),console.log(De.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Tt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Tt(e,"asIs",o,o,"nothing else applies",0);return}let s=await io(Oi,_l({preview:Ll(o),length:o.length,lineCount:o.split(`
308
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Dl(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Tt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${Oi}.mode`,0);return}let i=Pl(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Tt(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 Tt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Tt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Tt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(eu(n),await Hl(t)),Jl(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await ji(Ne,["key","--name","v","--mod","command"]).catch(a=>{console.log(De.red(` could not paste: ${a?.message??a}`))})}function Jl(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${De.dim("\u2192")} ${De.bold("unchanged")} ${De.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${De.green("\u2192")} ${De.bold(o.applied)} ${De.dim(`\xB7 ${o.reason}`)}`),console.log(De.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(De.dim(Ul(o.original))),console.log(De.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Ul(o.result)),!e.apply&&!e.paste&&console.log(De.dim(`
309
- (dry run \u2014 pass --apply to write it back)`))}var Ul=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
306
+ ${e.slice(-n)}`}function Yl(e){let o=e.trim();return o.includes(`
307
+ `)||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 Pi=ru(Kl),Ql=new iu().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 (${Di.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=uu();c===null&&(console.log(De.yellow(" nothing to undo")),process.exit(2)),await ed(c),console.log(` ${De.green("\u2192")} clipboard restored`);return}let o=await fu();if(o||(console.log(De.yellow(" clipboard is empty")),process.exit(2)),Yl(o)){Zl(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Gl(o),n=await hu();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(De.red(` "${e.as}" does not apply to this clipboard`)),console.log(De.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Tt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Tt(e,"asIs",o,o,"nothing else applies",0);return}let s=await io(_i,Bl({preview:zl(o),length:o.length,lineCount:o.split(`
308
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Jl(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Tt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${_i}.mode`,0);return}let i=Hl(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Tt(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 Tt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Tt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Tt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(pu(n),await ed(t)),Zl(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await Pi(Re,["key","--name","v","--mod","command"]).catch(a=>{console.log(De.red(` could not paste: ${a?.message??a}`))})}function Zl(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${De.dim("\u2192")} ${De.bold("unchanged")} ${De.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${De.green("\u2192")} ${De.bold(o.applied)} ${De.dim(`\xB7 ${o.reason}`)}`),console.log(De.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(De.dim(Vl(o.original))),console.log(De.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Vl(o.result)),!e.apply&&!e.paste&&console.log(De.dim(`
309
+ (dry run \u2014 pass --apply to write it back)`))}var Vl=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
310
310
  `).map(t=>` ${t}`).join(`
311
- `),ds=Qp(Xp(),".agentx","paste-undo.txt");function eu(e){try{Kp(Zp(ds),{recursive:!0}),Wl(ds,e,{mode:384})}catch{}}function ou(){try{let e=Vp(ds,"utf-8");return Wl(ds,"",{mode:384}),e.length?e:null}catch{return null}}async function tu(){let{stdout:e}=await ji("pbpaste",[],{maxBuffer:16777216});return e}async function Hl(e){await new Promise((o,t)=>{ql("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function nu(){if(!Yp(Ne))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await ji(Ne,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:su(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function su(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 iu}from"commander";import Ue from"chalk";ae();function Gl(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 Bn(()=>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 ru=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function au(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
312
- ${n}`:n,a=await fetch(`${ru}/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 cu(e){let o;try{o=j(e.config)}catch{o=void 0}let t=Pn(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??Mn(o);return{alert:Ta(t),banner:t.banner,channel:n}}var zl=new iu().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 ya,n=fa(),{alert:s,banner:i,channel:r}=cu(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=ro(o.config),d=Gl(s,Wn("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?Ue.yellow("\u25D0"):Ue.green("\u25CB")} ${ha(n)} ${Ue.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(Ue.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=au(r,o.chatId);if(o.flush){let g=await ja(l,{queue:t,alert:s});console.log(g?Ue.green(` delivered ${g} held notification(s)`):Ue.dim(" nothing was held"));return}e?.trim()||(console.log(Ue.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await Ia({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?Ue.green("\u2192"):Ue.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Ue.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Ue.yellow("?"):Ue.green("\u2713")} banner: ${d.shot.path}${Ue.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Ue.yellow(` ${d.error}`))}catch(g){console.log(Ue.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});Yt();Ir();wr();zt();import{Command as lu}from"commander";import{readFileSync as du}from"fs";var Yl=new lu().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?du(e.file,"utf8"):await gu()}catch(r){et(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return et("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return et(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return et("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return et("spec needs at least one entry in `questions`");try{xr(t.questions)}catch(r){return et(r?.message??String(r))}let n=t.seat||e.seat;ct(),process.env[Cr(n)]="active";let s=null;if(e.record!==!1)try{s=new On({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
313
- `)}jr({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await io(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return et(`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 et(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function gu(){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")}Yt();import{Command as Wu}from"commander";import{execFile as Bu,spawn as ld}from"child_process";import{promisify as Ju}from"util";import{existsSync as Hu,statSync as Gu}from"fs";import{join as dd}from"path";import{tmpdir as zu}from"os";import Q from"chalk";var mu={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."}]},pu={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."}]},uu={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."}]},Ci=[mu,pu,uu];ae();ae();import to from"chalk";import{execFile as fu}from"child_process";import{promisify as hu}from"util";import{createInterface as yu}from"readline";var Vl=hu(fu);function wu(e){e.type==="step"?console.log(`${to.cyan(` ${e.n}. ${e.action}`)}${e.target?to.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(to.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?to.red(` failed: ${e.error}`):to.dim(" done it")):e.type==="replanned"?console.log(to.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(to.cyan(` you: ${e.text}`)):e.type==="error"?console.log(to.red(` error: ${e.error}`)):e.type==="end"&&console.log(to.dim(` \xB7 ended (${e.reason})`))}async function bu(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Vl("open",["-a",e]).catch(()=>{});try{let s=(await ei()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function Kl(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await Vl("open",["-a",o.app]),i=await bu(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=Fn(n,t.agents,!1),a=t.voice.listener??cc,c=ft(n,t.agents[n]),l=new gc({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:ei,presence:new Un(c,Ne,n),speech:new ht,model:yt({system:dc(r.persona,a)}),act:mc});l.on(wu),console.log(to.bold(`
311
+ `),us=gu(du(),".agentx","paste-undo.txt");function pu(e){try{lu(mu(us),{recursive:!0}),Xl(us,e,{mode:384})}catch{}}function uu(){try{let e=cu(us,"utf-8");return Xl(us,"",{mode:384}),e.length?e:null}catch{return null}}async function fu(){let{stdout:e}=await Pi("pbpaste",[],{maxBuffer:16777216});return e}async function ed(e){await new Promise((o,t)=>{Kl("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function hu(){if(!au(Re))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Pi(Re,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:yu(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function yu(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 wu}from"commander";import Ue from"chalk";ae();function od(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 zn(()=>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 bu=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function $u(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
312
+ ${n}`:n,a=await fetch(`${bu}/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 ku(e){let o;try{o=I(e.config)}catch{o=void 0}let t=Un(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??qn(o);return{alert:Pa(t),banner:t.banner,channel:n}}var td=new wu().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 Aa,n=Sa(),{alert:s,banner:i,channel:r}=ku(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=ro(o.config),d=od(s,Gn("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?Ue.yellow("\u25D0"):Ue.green("\u25CB")} ${Ea(n)} ${Ue.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(Ue.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=$u(r,o.chatId);if(o.flush){let g=await Fa(l,{queue:t,alert:s});console.log(g?Ue.green(` delivered ${g} held notification(s)`):Ue.dim(" nothing was held"));return}e?.trim()||(console.log(Ue.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await La({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?Ue.green("\u2192"):Ue.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Ue.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Ue.yellow("?"):Ue.green("\u2713")} banner: ${d.shot.path}${Ue.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Ue.yellow(` ${d.error}`))}catch(g){console.log(Ue.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});Kt();Fr();Or();Vt();import{Command as vu}from"commander";import{readFileSync as xu}from"fs";var nd=new vu().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?xu(e.file,"utf8"):await Su()}catch(r){et(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return et("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return et(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return et("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return et("spec needs at least one entry in `questions`");try{Nr(t.questions)}catch(r){return et(r?.message??String(r))}let n=t.seat||e.seat;ct(),process.env[qr(n)]="active";let s=null;if(e.record!==!1)try{s=new Cn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
313
+ `)}Ur({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await io(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return et(`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 et(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Su(){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")}Kt();import{Command as of}from"commander";import{execFile as tf,spawn as wd}from"child_process";import{promisify as nf}from"util";import{existsSync as sf,statSync as rf}from"fs";import{join as bd}from"path";import{tmpdir as af}from"os";import Q from"chalk";var Eu={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."}]},Au={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."}]},Tu={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."}]},Mi=[Eu,Au,Tu];ae();ae();import to from"chalk";import{execFile as Ou}from"child_process";import{promisify as ju}from"util";import{createInterface as Iu}from"readline";var sd=ju(Ou);function Cu(e){e.type==="step"?console.log(`${to.cyan(` ${e.n}. ${e.action}`)}${e.target?to.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(to.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?to.red(` failed: ${e.error}`):to.dim(" done it")):e.type==="replanned"?console.log(to.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(to.cyan(` you: ${e.text}`)):e.type==="error"?console.log(to.red(` error: ${e.error}`)):e.type==="end"&&console.log(to.dim(` \xB7 ended (${e.reason})`))}async function Ru(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await sd("open",["-a",e]).catch(()=>{});try{let s=(await ri()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function id(e,o){let t=I(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 sd("open",["-a",o.app]),i=await Ru(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=Bn(n,t.agents,!1),a=t.voice.listener??yc,c=ft(n,t.agents[n]),l=new $c({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:ri,presence:new Jn(c,Re,n),speech:new ht,model:yt({system:bc(r.persona,a)}),act:kc});l.on(Cu),console.log(to.bold(`
314
314
  ${c.name} teaches: ${e}`)+to.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
315
- `));let g=yu({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}ae();import no from"chalk";import{execFile as Ru}from"child_process";import{existsSync as _i,writeFileSync as _u}from"fs";import{homedir as Du}from"os";import{join as ad,resolve as Pu}from"path";import{promisify as Mu}from"util";var qe={w:1e3,h:640},Ni=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Zl=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Xl=["none","semi","solid","fill","pattern"],Ri=180,ed=48,$u=["s","m","l","xl"],ku=["draw","sans","serif","mono"];function od(){return[`You are an illustrator drawing on a tldraw canvas ${qe.w} wide and ${qe.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 ${Ri}. 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 ${ed} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it, then an arrow from that text to the thing.",`geo is one of: ${Zl.join(", ")}.`,`color is one of: ${Ni.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
316
- `)}function Ot(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function ot(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var tt=(e,o,t)=>Math.min(t,Math.max(o,e)),Ql=e=>tt(ot(e)??1,.1,1),vu=/^#[0-9a-f]{6}$/i;function xu(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))Ni.includes(t)&&typeof n=="string"&&vu.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Su(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,ed)){if(!Array.isArray(t))return null;let n=ot(t[0]),s=ot(t[1]);if(n===null||s===null)return null;o.push([tt(n,0,qe.w),tt(s,0,qe.h)])}return o.length>=2?o:null}function td(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=xu(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=Ot(n.color,Ni,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Su(n.path),g=Ot(n.fill,Xl,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Ql(n.opacity)}}let a=ot(n.x),c=ot(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:tt(a,0,qe.w-20),y:tt(c,0,qe.h-20),size:Ot(n.size,$u,"l"),color:r,font:Ot(n.font,ku,"draw")};if(typeof n.geo=="string"){let l=ot(n.w),g=ot(n.h);if(l===null||g===null||l<4||g<4)return null;let d=tt(a,0,qe.w-4),u=tt(c,0,qe.h-4);return{kind:"geo",id:s,say:i,geo:Ot(n.geo,Zl,"rectangle"),x:d,y:u,w:Math.min(l,qe.w-d),h:Math.min(g,qe.h-u),color:r,fill:Ot(n.fill,Xl,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Ql(n.opacity)}}return null}var gs=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
317
- `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var Eu=500,Au=e=>`
315
+ `));let g=Iu({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}ae();import no from"chalk";import{execFile as Gu}from"child_process";import{existsSync as Ui,writeFileSync as zu}from"fs";import{homedir as Yu}from"os";import{join as hd,resolve as Vu}from"path";import{promisify as Ku}from"util";var qe={w:1e3,h:640},Li=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],cd=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],rd=["none","semi","solid","fill","pattern"],Fi=180,ld=48,Nu=["s","m","l","xl"],_u=["draw","sans","serif","mono"];function dd(){return[`You are an illustrator drawing on a tldraw canvas ${qe.w} wide and ${qe.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 ${Fi}. 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 ${ld} points, closed and filled, for any silhouette a box can't make: domes, arches, hills, foliage, stairs, shadows, reflections. Straight edges stay straight; give curves enough points. With fill none it is an open stroke: a railing, a grille bar, a crack, a horizon line.`,'Text: {"id":"title","say":"And a title.","text":"Sidi Bou Said","x":330,"y":40,"size":"xl","color":"black","font":"serif"}',`Arrow: {"id":"a1","say":"That's the sun.","arrow":["sun-note","sun"],"label":"","color":"black"}`,"An arrow joins two DIFFERENT earlier elements. To label something, first add a small text element beside it, then an arrow from that text to the thing.",`geo is one of: ${cd.join(", ")}.`,`color is one of: ${Li.join(", ")}. fill is fill (strong colour), solid (pale tint), semi, none or pattern. opacity is 0.1 to 1: use it for shadows, haze and atmospheric depth. size is s, m, l or xl. font is draw (hand-lettered), sans, serif or mono.`,"Keep everything inside the canvas. Give text room: an xl word is about 40 px tall and 28 px wide per letter.","say is a short caption, at most 8 words, in the voice of someone drawing it live. Caption only the steps worth narrating (about one in five) and leave say empty on the rest: captioned steps pause so they can be read, the others draw straight through."].join(`
316
+ `)}function Ot(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function ot(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var tt=(e,o,t)=>Math.min(t,Math.max(o,e)),ad=e=>tt(ot(e)??1,.1,1),Du=/^#[0-9a-f]{6}$/i;function Pu(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))Li.includes(t)&&typeof n=="string"&&Du.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Mu(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,ld)){if(!Array.isArray(t))return null;let n=ot(t[0]),s=ot(t[1]);if(n===null||s===null)return null;o.push([tt(n,0,qe.w),tt(s,0,qe.h)])}return o.length>=2?o:null}function gd(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=Pu(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=Ot(n.color,Li,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Mu(n.path),g=Ot(n.fill,rd,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:ad(n.opacity)}}let a=ot(n.x),c=ot(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:tt(a,0,qe.w-20),y:tt(c,0,qe.h-20),size:Ot(n.size,Nu,"l"),color:r,font:Ot(n.font,_u,"draw")};if(typeof n.geo=="string"){let l=ot(n.w),g=ot(n.h);if(l===null||g===null||l<4||g<4)return null;let d=tt(a,0,qe.w-4),u=tt(c,0,qe.h-4);return{kind:"geo",id:s,say:i,geo:Ot(n.geo,cd,"rectangle"),x:d,y:u,w:Math.min(l,qe.w-d),h:Math.min(g,qe.h-u),color:r,fill:Ot(n.fill,rd,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:ad(n.opacity)}}return null}var fs=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
317
+ `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var Lu=500,Fu=e=>`
318
318
  editor.zoomToBounds({ x: 0, y: 0, w: ${qe.w}, h: ${qe.h} }, { inset: ${e}, immediate: true })
319
319
  const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${qe.w}, y: 0 })
320
320
  const chrome = window.outerHeight - window.innerHeight
321
- return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${qe.w} }`;function nd(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 sd(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 Tu(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 id(e){return`const hex = ${JSON.stringify(e.colors)}
321
+ return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${qe.w} }`;function md(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 pd(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 Uu(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 ud(e){return`const hex = ${JSON.stringify(e.colors)}
322
322
  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('')
323
323
  const th = editor.getTheme('default')
324
324
  const colors = structuredClone(th.colors)
@@ -326,9 +326,9 @@ for (const mode of Object.keys(colors)) for (const [name, v] of Object.entries(h
326
326
  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 })
327
327
  }
328
328
  editor.updateTheme({ ...th, colors })
329
- return true`}function Ou(e,o){if(e.kind==="palette")return id(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
329
+ return true`}function qu(e,o){if(e.kind==="palette")return ud(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
330
330
  const el = ${JSON.stringify(e)}
331
- const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Eu/10)}))
331
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Lu/10)}))
332
332
  const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
333
333
  const id = createShapeId(${t(e.id)})
334
334
  editor.createShape({ id, type: 'geo', x: el.x, y: el.y, opacity: el.opacity, props: { geo: el.geo, w: 1, h: 1, color: el.color, fill: el.fill, dash: 'solid', size: 's' } })
@@ -368,60 +368,60 @@ return id`:`${n}
368
368
  const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
369
369
  const aid = typeof arrow === 'string' ? arrow : arrow?.id
370
370
  if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
371
- return aid ?? null`}function Iu(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=sd(e);return[yo(s.x,s.y+s.h/2),yo(s.x+s.w,s.y+s.h/2)]}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});async function rd(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise($=>setTimeout($,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Au(60)),g=new Set,d=new Map,u=[],f=!1,p=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},v=x=>{if(g.size>=Ri)return;let $=td(x,g);if(!$){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add($.id),w??=i()-c,u.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let x=new gs;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))x.push($).forEach(v);x.flush().forEach(v)}catch($){y=$?.message??String($)}finally{p=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let $=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,id(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-$});continue}let[R,C]=Iu(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(nd(l,R.x,R.y)),await s(250),o.presence.moveTo(nd(l,C.x,C.y));try{await o.api.exec(t.docId,Ou(x,a))}catch(P){n({type:"error",error:`${x.id}: ${P?.message??P}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?sd(x):x.kind==="path"?Tu(x.pts):yo(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-$});let I=(x.say?r:0)-(i()-$);I>0&&await s(I)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:p}}import{readFileSync as ju}from"fs";import{homedir as Cu}from"os";import{join as Nu}from"path";var un=Nu(Cu(),"Library","Application Support","tldraw","server.json"),ms=class{constructor(o=un,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=ju(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 Lu=Mu(Ru),Fu="claude-sonnet-5";function Uu(e){e.type==="planned"?console.log(no.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${no.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${no.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(no.yellow(` skipped: ${e.line}`)):console.log(no.red(` error: ${e.error}`))}async function qu(){if(!_i(un)){await Lu("open",["-a","tldraw offline"]);for(let e=0;e<40&&!_i(un);e++)await new Promise(o=>setTimeout(o,500));if(!_i(un))throw new Error("tldraw offline did not start")}}async function cd(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||Fu,i=Pu(o.out||ad(Du(),"Documents")),r=ft(n,t.agents[n]),a=yt({system:od(),model:s}),c=new Un(r,Ne,n),l=new ms;try{await qu();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(no.bold(`
371
+ return aid ?? null`}function Wu(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=pd(e);return[yo(s.x,s.y+s.h/2),yo(s.x+s.w,s.y+s.h/2)]}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});async function fd(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise($=>setTimeout($,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Fu(60)),g=new Set,d=new Map,u=[],f=!1,p=0,w=null,y=null,k=null,b=()=>{k?.(),k=null},v=x=>{if(g.size>=Fi)return;let $=gd(x,g);if(!$){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add($.id),w??=i()-c,u.push($),n({type:"planned",n:g.size,el:$,atMs:i()-c}),b()},A=(async()=>{let x=new fs;try{for await(let $ of o.model.reply(`Draw: ${e}`,t.signal))x.push($).forEach(v);x.flush().forEach(v)}catch($){y=$?.message??String($)}finally{p=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let $=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,ud(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-$});continue}let[N,C]=Wu(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(md(l,N.x,N.y)),await s(250),o.presence.moveTo(md(l,C.x,C.y));try{await o.api.exec(t.docId,qu(x,a))}catch(P){n({type:"error",error:`${x.id}: ${P?.message??P}`});continue}d.set(x.id,x.kind==="geo"?x:x.kind==="text"?pd(x):x.kind==="path"?Uu(x.pts):yo(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-$});let j=(x.say?r:0)-(i()-$);j>0&&await s(j)}return await A,y&&n({type:"error",error:`plan: ${y}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:w,planMs:p}}import{readFileSync as Bu}from"fs";import{homedir as Ju}from"os";import{join as Hu}from"path";var hn=Hu(Ju(),"Library","Application Support","tldraw","server.json"),hs=class{constructor(o=hn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=Bu(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 Xu=Ku(Gu),Qu="claude-sonnet-5";function Zu(e){e.type==="planned"?console.log(no.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${no.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${no.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(no.yellow(` skipped: ${e.line}`)):console.log(no.red(` error: ${e.error}`))}async function ef(){if(!Ui(hn)){await Xu("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Ui(hn);e++)await new Promise(o=>setTimeout(o,500));if(!Ui(hn))throw new Error("tldraw offline did not start")}}async function yd(e,o){let t=I(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||Qu,i=Vu(o.out||hd(Yu(),"Documents")),r=ft(n,t.agents[n]),a=yt({system:dd(),model:s}),c=new Jn(r,Re,n),l=new hs;try{await ef();let g=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),d=await l.createDoc(`agentx-draw-${g}`,i);await new Promise(k=>setTimeout(k,800)),console.log(no.bold(`
372
372
  ${r.name} draws: ${e}`)+no.dim(` (${s}, ${d.filePath})
373
- `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await rd(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Uu);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"),w=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):ad(i,`agentx-draw-${g}.png`);_u(w,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(no.bold(`
373
+ `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await fd(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Zu);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"),w=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):hd(i,`agentx-draw-${g}.png`);zu(w,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(no.bold(`
374
374
  ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+no.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 y=a.lastUsage;y&&console.log(no.dim(` tokens: ${y.inputTokens} in, ${y.outputTokens} out, ${y.cacheReadTokens} cache read, ${y.cacheWriteTokens} cache write; cost ${y.costUsd===null?"not reported":`$${y.costUsd.toFixed(4)}`}`)),console.log(no.dim(` ${d.filePath}
375
375
  ${w}
376
- `))}finally{a.close(),c.close()}}var Pi=Ju(Bu),gd=new Wu().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, "${Eo}" 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 cd(String(o.live),o):await Kl(String(o.live),o),process.exit(0)}catch(g){console.log(Q.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(Q.bold(`
376
+ `))}finally{a.close(),c.close()}}var Wi=nf(tf),$d=new of().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, "${Eo}" 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 yd(String(o.live),o):await id(String(o.live),o),process.exit(0)}catch(g){console.log(Q.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(Q.bold(`
377
377
  lessons
378
- `));for(let g of Ci)console.log(` ${Q.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${Q.dim(g.appHint)}
379
- `);return}let t=Ci.find(g=>g.id===e);t||(console.log(Q.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Hu(Ne)||(console.log(Q.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Ku(o.voice,o.agent);console.log(Q.bold(`
378
+ `));for(let g of Mi)console.log(` ${Q.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${Q.dim(g.appHint)}
379
+ `);return}let t=Mi.find(g=>g.id===e);t||(console.log(Q.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),sf(Re)||(console.log(Q.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:df(o.voice,o.agent);console.log(Q.bold(`
380
380
  ${t.title}`)),console.log(Q.dim(` ${t.appHint}
381
- `));try{t.start&&(await Pi("/usr/bin/open",Yu(t.start)),await Do(2e3),await ps(t.start.ready))}catch(g){console.log(Q.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=dd(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(Q.dim(` recording \u2192 ${i}`)),s=ld("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Do(2e3));let r=o.hud===!1?null:ld(Ne,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
382
- `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${Q.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 ps(d.before)}let u=o.speak===!1?Promise.resolve():Qu(d.say,n),f=d.find?await Vu(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 Pi(Ne,["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:w}=await Di(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:w!==!1,note:p??void 0}),w===!1&&console.log(Q.yellow(" \xB7 clicked, but the screen did not change")),await Do(d.afterClickWaitMs??1500)}if(d.type){await ps(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await Di(["type","--text",d.type]);if(p)throw console.log(Q.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 ps(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Di(["key","--name",d.key]);if(p)throw console.log(Q.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 Do((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Do(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),w;try{w=await mn(d.verify,p?{settle:!0,screen:ro()}:{})}catch(y){w=null,console.log(Q.yellow(` ? could not check: ${y?.message??y}`))}if(!w&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(w){let y=w.outcome==="confirmed"?Q.green("\u2713"):w.outcome==="refuted"?Q.red("\u2717"):Q.yellow("?");if(console.log(` ${y} ${Q.dim(w.reason)}`),!w.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(Q.red(`
383
- stopping: could not confirm \u2014 ${d.verify}`)),console.log(Q.dim(` ${w.reason}`)),console.log(Q.dim(` screenshot: ${w.sighting.shot.path}`)),await Do(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(Q.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 Do(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Do(2500);try{let{size:g}=Gu(i);console.log(Q.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(Q.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(Q.red(` lesson stopped before the end.
381
+ `));try{t.start&&(await Wi("/usr/bin/open",cf(t.start)),await Do(2e3),await ys(t.start.ready))}catch(g){console.log(Q.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=bd(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(Q.dim(` recording \u2192 ${i}`)),s=wd("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Do(2e3));let r=o.hud===!1?null:wd(Re,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
382
+ `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${Q.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 ys(d.before)}let u=o.speak===!1?Promise.resolve():mf(d.say,n),f=d.find?await lf(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 Wi(Re,["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:w}=await qi(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:w!==!1,note:p??void 0}),w===!1&&console.log(Q.yellow(" \xB7 clicked, but the screen did not change")),await Do(d.afterClickWaitMs??1500)}if(d.type){await ys(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await qi(["type","--text",d.type]);if(p)throw console.log(Q.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 ys(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await qi(["key","--name",d.key]);if(p)throw console.log(Q.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 Do((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Do(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),w;try{w=await un(d.verify,p?{settle:!0,screen:ro()}:{})}catch(y){w=null,console.log(Q.yellow(` ? could not check: ${y?.message??y}`))}if(!w&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(w){let y=w.outcome==="confirmed"?Q.green("\u2713"):w.outcome==="refuted"?Q.red("\u2717"):Q.yellow("?");if(console.log(` ${y} ${Q.dim(w.reason)}`),!w.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(Q.red(`
383
+ stopping: could not confirm \u2014 ${d.verify}`)),console.log(Q.dim(` ${w.reason}`)),console.log(Q.dim(` screenshot: ${w.sighting.shot.path}`)),await Do(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(Q.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 Do(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Do(2500);try{let{size:g}=rf(i);console.log(Q.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(Q.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(Q.red(` lesson stopped before the end.
384
384
  `)),process.exitCode=3;return}console.log(Q.green(`
385
385
  done.
386
- `))});function Yu(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${dd(zu(),"agentx-teach-chrome")}`,"--no-first-run","--no-default-browser-check","--window-position=0,200","--window-size=1440,680",`--app=${e.url}`]:["-a",e.app,e.url]}async function ps(e){let o=await mn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function Di(e){try{let{stdout:o}=await Pi(Ne,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 Vu(e,o=[]){try{let t=await qn({max:45});if(t.candidates.length<2)return null;let n=await io(dn,is({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),rs(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=as(n.answers,t.candidates);return s.present<.5?null:en(t,s.id)}catch{return null}}function Ku(e,o){if(e?.trim().toLowerCase()===Eo)return{provider:"system",elevenlabs:Zt(),system:null,fallback:!0};let t=e?Ln(e,Qt()):null;if(t)return{provider:"system",elevenlabs:Zt(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=j(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(Q.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?nc(oc(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:Zt(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(Q.dim(` no agent voice (${String(n?.message??n).split(`
387
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:Zt(),system:null,fallback:!0}}}var Xu=new ht;async function Qu(e,o){o&&await Xu.say({voice:o,text:e})}var Do=e=>new Promise(o=>setTimeout(o,e));ae();import{Command as md}from"commander";import Je from"chalk";import{createInterface as pd}from"readline";var Zu=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function It(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Zu()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function ef(e){e.type==="line"?console.log(`${Je.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Je.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Je.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Je.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Je.dim(" \xB7 hushed")):e.type==="error"?console.log(Je.red(` error: ${e.error}`)):e.type==="end"&&console.log(Je.dim(` \xB7 ended (${e.reason})`))}function ud(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 of(e,o,t){let n=j(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await It("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new ic(()=>n,()=>d),i.usePool(await sc(ec()))}let r=e.map(d=>s[d]?Fn(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 lc({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new ht,listener:n.voice.listener,model:(d,u)=>yt({system:u})});l.on(ef),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Je.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=pd({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(Je.dim(` ${ud(l.gaps)}`))}async function tf(e,o,t){let n=await It("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=pd({input:process.stdin});s.on("line",a=>{a.trim()&&It("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void It("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await It("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Je.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(Je.dim(` ${ud(r)}`))}var fd=new md().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?of:tf)([e,o],s,n),process.exit(0)}catch(i){console.error(Je.red(` ${i?.message??i}`)),process.exit(1)}}),hd=new md().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(Je.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await It("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Je.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ae();import{Command as nf}from"commander";import te from"chalk";import{existsSync as sf,readFileSync as wd,writeFileSync as bd}from"fs";import{resolve as yd}from"path";Pg();var jt=new nf().name("voice").description("list installed system voices and pick each agent's voice");function Mi(e){let o=e?[e]:[yd(process.cwd(),"agentx.json"),yd(process.cwd(),".agentx/config.json")],t=o.find(n=>sf(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function rf(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=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===Eo,y=w?null:Ln(t,s,a??e?.voice?.locale),k=y?`system voice ${Xs(y)}`:"the OS default voice";if((y||w)&&g==="system")u(w?Eo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(y||w)u(w?Eo:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}jt.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=Qt(),t;try{t=j(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?tc(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),l=Object.values(Qs(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(te.yellow(`
386
+ `))});function cf(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${bd(af(),"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 ys(e){let o=await un(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function qi(e){try{let{stdout:o}=await Wi(Re,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 lf(e,o=[]){try{let t=await Hn({max:45});if(t.candidates.length<2)return null;let n=await io(mn,ls({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),ds(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=gs(n.answers,t.candidates);return s.present<.5?null:tn(t,s.id)}catch{return null}}function df(e,o){if(e?.trim().toLowerCase()===Eo)return{provider:"system",elevenlabs:on(),system:null,fallback:!0};let t=e?Wn(e,en()):null;if(t)return{provider:"system",elevenlabs:on(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=I(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(Q.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?mc(dc(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:on(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(Q.dim(` no agent voice (${String(n?.message??n).split(`
387
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:on(),system:null,fallback:!0}}}var gf=new ht;async function mf(e,o){o&&await gf.say({voice:o,text:e})}var Do=e=>new Promise(o=>setTimeout(o,e));ae();import{Command as kd}from"commander";import Je from"chalk";import{createInterface as vd}from"readline";var pf=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function jt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(pf()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function uf(e){e.type==="line"?console.log(`${Je.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Je.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Je.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Je.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Je.dim(" \xB7 hushed")):e.type==="error"?console.log(Je.red(` error: ${e.error}`)):e.type==="end"&&console.log(Je.dim(` \xB7 ended (${e.reason})`))}function xd(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 ff(e,o,t){let n=I(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await jt("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new uc(()=>n,()=>d),i.usePool(await pc(lc()))}let r=e.map(d=>s[d]?Bn(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 wc({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new ht,listener:n.voice.listener,model:(d,u)=>yt({system:u})});l.on(uf),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Je.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=vd({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(Je.dim(` ${xd(l.gaps)}`))}async function hf(e,o,t){let n=await jt("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=vd({input:process.stdin});s.on("line",a=>{a.trim()&&jt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void jt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await jt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Je.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(Je.dim(` ${xd(r)}`))}var Sd=new kd().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?ff:hf)([e,o],s,n),process.exit(0)}catch(i){console.error(Je.red(` ${i?.message??i}`)),process.exit(1)}}),Ed=new kd().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(Je.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await jt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Je.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ae();import{Command as yf}from"commander";import te from"chalk";import{existsSync as wf,readFileSync as Td,writeFileSync as Od}from"fs";import{resolve as Ad}from"path";Vg();var It=new yf().name("voice").description("list installed system voices and pick each agent's voice");function Bi(e){let o=e?[e]:[Ad(process.cwd(),"agentx.json"),Ad(process.cwd(),".agentx/config.json")],t=o.find(n=>wf(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function bf(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=w=>{if(!a){l.system=w;return}let y=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...y,[a]:w}},f=a?` for ${a}`:"";if(t){let w=t.trim().toLowerCase()===Eo,y=w?null:Wn(t,s,a??e?.voice?.locale),k=y?`system voice ${ni(y)}`:"the OS default voice";if((y||w)&&g==="system")u(w?Eo:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!y&&!w&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(y||w)u(w?Eo:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}It.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=en(),t;try{t=I(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?gc(t.agents,t.voice,o):new Map;if(t)for(let[r,a]of Object.entries(t.agents)){let c=i.get(r),l=Object.values(si(r,a.voice?.system,a.voice?.gender,t.voice,o));for(let g of new Set([c,...l]))g&&s.set(g.id,[...s.get(g.id)??[],r])}if(!o.length)console.log(te.yellow(`
388
388
  No system voices found (system voices need macOS).
389
- `));else{let r=e.all?Ks(o,""):Ks(o,n);console.log(te.bold(`
389
+ `));else{let r=e.all?ti(o,""):ti(o,n);console.log(te.bold(`
390
390
  System voices${e.all?"":` (${n})`}, best first
391
391
  `));for(let a of r){let c=a.siri?te.magenta("siri"):a.quality==="standard"?te.dim("standard"):te.green(a.quality),l=s.get(a.id)?.join(", ");console.log(` ${(a.siri?`siri:${a.name.toLowerCase()}`:a.name).padEnd(12)} ${a.locale.padEnd(6)} ${c.padEnd(18)} ${te.dim((a.gender??"").padEnd(7))} ${l?te.cyan(l):""}`)}o.some(a=>a.quality!=="standard")||(console.log(te.dim(`
392
392
  More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(te.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}if(t){console.log(te.bold(`
393
393
  Agents
394
- `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=u=>u?Xs(u):te.dim("system default"),g=Object.entries(Qs(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,u])=>(u?.id??null)!==(i.get(r)?.id??null)).map(([u,f])=>`${te.dim(`${u}:`)} ${l(f)}`).join(te.dim(" \xB7 ")),d=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??te.dim("(default voice)")}`:`system ${l(i.get(r))}${g?te.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${d}${a.voice?.gender?te.dim(` (${a.voice.gender})`):""}`)}}console.log()});jt.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Eo}" 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=Mi(t.config),{raw:s,summary:i}=rf(JSON.parse(wd(n,"utf8")),e,o,t,Qt());bd(n,JSON.stringify(s,null,2)+`
395
- `),console.log(te.green(` ${e}: ${i}`)),console.log(te.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(te.red(` ${n.message}`)),process.exit(1)}});function $d(e,o){let t=rc(o,j(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
396
- `));let n=JSON.parse(wd(e,"utf8"));ac(n,o),bd(e,JSON.stringify(n,null,2)+`
397
- `)}jt.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${$r.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=Mi(t.config);if(e&&o){let i=o==="default"?null:o;$d(n,{agents:{[e]:{palette:i}}}),console.log(te.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(te.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=j(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(te.bold(`
394
+ `));for(let[r,a]of Object.entries(t.agents)){let c=a.voice?.provider??t.voice.provider,l=u=>u?ni(u):te.dim("system default"),g=Object.entries(si(r,a.voice?.system,a.voice?.gender,t.voice,o)).filter(([,u])=>(u?.id??null)!==(i.get(r)?.id??null)).map(([u,f])=>`${te.dim(`${u}:`)} ${l(f)}`).join(te.dim(" \xB7 ")),d=c==="elevenlabs"?`elevenlabs ${a.voice?.elevenlabsVoiceId??te.dim("(default voice)")}`:`system ${l(i.get(r))}${g?te.dim(" \xB7 ")+g:""}`;console.log(` ${r.padEnd(24)} ${d}${a.voice?.gender?te.dim(` (${a.voice.gender})`):""}`)}}console.log()});It.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Eo}" 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=Bi(t.config),{raw:s,summary:i}=bf(JSON.parse(Td(n,"utf8")),e,o,t,en());Od(n,JSON.stringify(s,null,2)+`
395
+ `),console.log(te.green(` ${e}: ${i}`)),console.log(te.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(te.red(` ${n.message}`)),process.exit(1)}});function jd(e,o){let t=fc(o,I(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
396
+ `));let n=JSON.parse(Td(e,"utf8"));hc(n,o),Od(e,JSON.stringify(n,null,2)+`
397
+ `)}It.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${Ir.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=Bi(t.config);if(e&&o){let i=o==="default"?null:o;jd(n,{agents:{[e]:{palette:i}}}),console.log(te.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(te.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=I(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(te.bold(`
398
398
  Orb palettes
399
- `));for(let i of br)console.log(` ${i.id.padEnd(10)} ${te.dim(i.colors.join(" "))}`);console.log(te.bold(`
399
+ `));for(let i of jr)console.log(` ${i.id.padEnd(10)} ${te.dim(i.colors.join(" "))}`);console.log(te.bold(`
400
400
  Agents
401
- `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=ft(i,r).color,c=kr(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${te.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(te.red(` ${n.message}`)),process.exit(1)}});jt.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, ${Zs.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Zs.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=Mi(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&&$d(o,{general:{card:t}});let n=j(o).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(t).length&&console.log(te.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(o){console.log(te.red(` ${o.message}`)),process.exit(1)}});import{Command as af}from"commander";import N from"chalk";var Po=new af().name("attach").description("wear an agentx agent identity in this Claude Code session"),us=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Go()}`;function fs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function hs(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 ys(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 vd(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function cf(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)} ${vd(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function lf(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 df(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)}`)}Po.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Bs.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",us).action(async(e,o)=>{let t=fs(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)),Fr(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Bs.join(", ")}`)),process.exit(1)),nn()||(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 hs(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)} (${vd(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: ${ys(n)}`)),process.exit(1)}});function kd(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function gf(e){let o=kd(e.kinds),t=kd(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}Po.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",us).action(async e=>{let o=fs(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)),nn()||(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 hs(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:gf(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: ${ys(t)}`)),process.exit(1)}});Po.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",us).action(async e=>{let o=fs(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await hs(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: ${ys(t)}`)),process.exit(1)}});Po.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",us).option("--json","raw JSON output").action(async e=>{let o=fs();try{let n=(await hs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:nn(),sessions:n},null,2));return}console.log(),console.log(nn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(tn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=lf(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)cf(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)df(a,a.sessionId===o)}r>0&&console.log(N.gray(`
402
- ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(N.red(`Could not read attach state: ${ys(t)}`)),process.exit(1)}});Po.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||Go()),t=Bc(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
401
+ `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=ft(i,r).color,c=Cr(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${te.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(te.red(` ${n.message}`)),process.exit(1)}});It.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, ${ii.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${ii.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=Bi(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&&jd(o,{general:{card:t}});let n=I(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(te.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(o){console.log(te.red(` ${o.message}`)),process.exit(1)}});import{Command as $f}from"commander";import R from"chalk";var Po=new $f().name("attach").description("wear an agentx agent identity in this Claude Code session"),ws=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Go()}`;function bs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function $s(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 ks(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${R.cyan("agentx daemon start")}`:o}function Cd(e){return e==="auto"?R.yellow:e==="manual"?R.gray:R.green}function kf(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):R.gray("(not bound)"),n=e.pending?R.yellow(`${e.pending} pending`):R.gray("empty"),s=o?R.cyan(" \u2190 this session"):"";console.log(` ${R.bold(t)} ${Cd(e.mode)(e.mode)} ${n} ${R.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${R.gray(e.cwd)}`)}function vf(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 xf(e,o=!1){let t=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=o?R.cyan(" \u2190 this session"):"";console.log(` ${R.bold("watching")} ${R.gray(t)} ${R.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${R.gray(e.cwd)}`)}Po.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Vs.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ws).action(async(e,o)=>{let t=bs(o.session);t||(console.error(R.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${R.cyan("--session <id>")} (list them with ${R.cyan("agentx attach list")}).`),process.exit(1)),Vr(o.mode)||(console.error(R.red(`Invalid mode "${o.mode}". Expected one of: ${Vs.join(", ")}`)),process.exit(1)),rn()||(console.error(R.yellow("Attach hooks are not installed yet.")),console.error(`Run ${R.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await $s(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${R.green("\u2713")} This session is now wearing ${R.bold(e)} (${Cd(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(R.yellow(` ${s} message(s) already queued for it.`)),console.log(R.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(R.red(`Bind failed: ${ks(n)}`)),process.exit(1)}});function Id(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function Sf(e){let o=Id(e.kinds),t=Id(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}Po.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",ws).action(async e=>{let o=bs(e.session);o||(console.error(R.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${R.cyan("--session <id>")}.`),process.exit(1)),rn()||(console.error(R.yellow("Attach hooks are not installed yet.")),console.error(`Run ${R.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await $s(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:Sf(e)}),console.log(`${R.green("\u2713")} This session is now ${R.bold("watching")}. It answers for no agent.`),console.log(R.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(R.gray(` Stop with ${R.cyan("agentx attach detach")}.`))}catch(t){console.error(R.red(`Watch failed: ${ks(t)}`)),process.exit(1)}});Po.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",ws).action(async e=>{let o=bs(e.session);o||(console.error(R.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await $s(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${R.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(R.red(`Detach failed: ${ks(t)}`)),process.exit(1)}});Po.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ws).option("--json","raw JSON output").action(async e=>{let o=bs();try{let n=(await $s(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:rn(),sessions:n},null,2));return}console.log(),console.log(rn()?`${R.green("\u2713")} Attach hooks installed ${R.gray(sn())}`:`${R.yellow("!")} Attach hooks not installed \u2014 run ${R.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=vf(n);if(console.log(R.bold(" Identities")),s.length===0)console.log(R.gray(" No session is wearing an identity right now."));else for(let a of s)kf(a,a.sessionId===o);if(i.length>0){console.log(),console.log(R.bold(" Watchers"));for(let a of i)xf(a,a.sessionId===o)}r>0&&console.log(R.gray(`
402
+ ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(R.red(`Could not read attach state: ${ks(t)}`)),process.exit(1)}});Po.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||Go()),t=Qc(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${R.green("\u2713")} Installed attach hooks in ${R.gray(t.path)}`:`${R.green("\u2713")} Attach hooks already up to date in ${R.gray(t.path)}`),console.log(R.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(R.gray(" PreToolUse guard installed at user scope.")),console.log(R.gray(` (An attached session runs under your permissions, not the agent's workspace
403
403
  settings \u2014 without this an attached production identity would be less
404
- 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)}});Po.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=Jc({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)}});ae();import{Command as mf}from"commander";import we from"chalk";var ws=new mf().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Sd(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=j(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Ed(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function xd(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 pf(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}ws.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}=Sd(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Ed(t)})}catch(r){console.log(we.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(we.dim(" (no processes)"));return}for(let r of i){let a=pf(r.state)(r.state.padEnd(9)),c=xd(r.spawnedAt),l=r.lastTurnAt?xd(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});ws.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}=Sd(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Ed(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${o}:${t}`))});import{Command as uf}from"commander";import Pe from"chalk";import{existsSync as Li,rmSync as ff}from"fs";import{resolve as Fi}from"path";var Ct=new uf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Ct.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(Pe.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Br(e,o,{verbose:n}),r=Date.now()-s;console.log(Pe.green(` \u2713 indexed ${i.docs} doc(s) for ${Pe.bold(e)} in ${r}ms`)),console.log(Pe.dim(` \u2192 ${i.path}`))});Ct.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Fi(e.cwd,".agentx","rag");if(!Li(o)){console.log(Pe.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Li(Fi(o,s,"index.json")));if(n.length===0){console.log(Pe.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Js(s);console.log(` ${Pe.bold(s)} ${i.docs} doc(s) ${Pe.dim(i.path)}`)}});Ct.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=Jr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Js(e);i.exists?console.log(Pe.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Pe.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Pe.bold(i.title)} ${Pe.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Pe.dim(i.path)}`),console.log(` ${Pe.dim(i.snippet.slice(0,200))}`)});Ct.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Fi(process.cwd(),".agentx","rag",e);if(!Li(o)){console.log(Pe.dim(` no index for ${e} \u2014 nothing to clear`));return}ff(o,{recursive:!0,force:!0}),console.log(Pe.green(` \u2713 cleared index for ${e}`))});ae();import{Command as hf}from"commander";import X from"chalk";import Nt from"prompts";var nt=new hf().name("backlog").description("manage the local backlog used by business workSource=backlog");function fn(e){let o=j(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new pc(n)}}function yf(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function wf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}nt.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}=fn(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(X.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${wf(n.status).padEnd(7)} ${yf(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});nt.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=fn(t.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=uc([o],i.source,n.config),a=await ti(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});nt.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=fn(o.config);t.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await ti(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});nt.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}=fn(o.config);t.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});nt.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=fn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(X.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Nt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?$f(o.config):kf(o.config);y.length?(i=(await Nt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Nt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Nt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Nt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await vf(o.config,i,a):await xf(o.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=oi({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Nt({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(X.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?bf(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:oi(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(p);console.log(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(X.dim(` ${y.id} \u2014 ${y.title}`))});function bf(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function $f(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 kf(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 vf(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 xf(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(Ad)}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(Ad):[]}function Ad(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 Sf}from"commander";import W from"chalk";import{existsSync as Ef,readFileSync as Af}from"fs";import{resolve as Tf}from"path";import Of from"prompts";ae();function Td(e){let o=e||Tf(process.cwd(),"agentx.json");return Ef(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Af(o,"utf-8"))}async function If(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Of([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wo=new Sf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wo.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: ${zs})`,zs).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){wo.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Gs(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Td(o.config),s=vr(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await If(o.notify,s),r=o.id||Xr(t.matched,o.agent),a=Zr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Qr(o.onError),enabled:!o.disabled}),c=a.onError,l=await ye(d=>Oe(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.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=Td(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=oa(ea(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])wo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await sa(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ye(t=>{if(!ut(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Yr(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",ta,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",na,"reject an agent's pending create/delete request (drops the request)"]])wo.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Gs(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as jf}from"commander";import xe from"chalk";var Mo=new jf("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Cf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Od(){return{root:process.cwd()}}function Ui(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Nf(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Cf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${Ui(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${Ui(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mo.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=La(Od(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(xe.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(xe.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Nf(t),console.log();console.log(xe.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function qi(e,o,t){let n=Jn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Fa(Od(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Mo.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,o)=>qi(e,"yes",o));Mo.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)=>qi(e,"no",o));Mo.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)=>qi(e,"later",o));Mo.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: ${Pa.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let o=Jn(),t=Ma(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:o});if(!t.ok){console.error(xe.red(` ${t.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${t.card.id} raised; expires ${Ui(t.card.expires)}, then: ${t.card.if_silent}`))});Mo.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let o={},t=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let a=Ec(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await Ac(o);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=Jn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as oh}from"commander";import Rt from"chalk";import ne from"chalk";import yn from"prompts";import{readFileSync as Rf,writeFileSync as _f,existsSync as Df}from"fs";import{resolve as Id}from"path";var Pf=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Mf(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Wi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function jd(e=".env"){let o=Id(e);if(!Df(o))return[];let t=Rf(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(Pf);i?n.push({kind:"kv",key:i[1],value:Mf(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Lf(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Wi(o.value)}`:o.raw).join(`
404
+ guarded than a spawned one.)`))):console.log(R.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${R.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(R.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Po.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=Zc({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${R.green("\u2713")} Removed attach hooks from ${R.gray(o.path)} (${o.events.join(", ")})`:`${R.gray("Nothing to remove.")}`),e.removeGuard||console.log(R.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(R.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ae();import{Command as Ef}from"commander";import we from"chalk";var vs=new Ef().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Nd(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=I(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 _d(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Rd(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 Af(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}vs.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}=Nd(e),n;try{n=await fetch(`${o}/api/processes`,{headers:_d(t)})}catch(r){console.log(we.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(we.dim(" (no processes)"));return}for(let r of i){let a=Af(r.state)(r.state.padEnd(9)),c=Rd(r.spawnedAt),l=r.lastTurnAt?Rd(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});vs.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}=Nd(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:_d(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${o}:${t}`))});import{Command as Tf}from"commander";import Pe from"chalk";import{existsSync as Ji,rmSync as Of}from"fs";import{resolve as Hi}from"path";var Ct=new Tf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Ct.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(Pe.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Zr(e,o,{verbose:n}),r=Date.now()-s;console.log(Pe.green(` \u2713 indexed ${i.docs} doc(s) for ${Pe.bold(e)} in ${r}ms`)),console.log(Pe.dim(` \u2192 ${i.path}`))});Ct.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Hi(e.cwd,".agentx","rag");if(!Ji(o)){console.log(Pe.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Ji(Hi(o,s,"index.json")));if(n.length===0){console.log(Pe.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ks(s);console.log(` ${Pe.bold(s)} ${i.docs} doc(s) ${Pe.dim(i.path)}`)}});Ct.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=ea(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ks(e);i.exists?console.log(Pe.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Pe.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Pe.bold(i.title)} ${Pe.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Pe.dim(i.path)}`),console.log(` ${Pe.dim(i.snippet.slice(0,200))}`)});Ct.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Hi(process.cwd(),".agentx","rag",e);if(!Ji(o)){console.log(Pe.dim(` no index for ${e} \u2014 nothing to clear`));return}Of(o,{recursive:!0,force:!0}),console.log(Pe.green(` \u2713 cleared index for ${e}`))});ae();import{Command as jf}from"commander";import X from"chalk";import Rt from"prompts";var nt=new jf().name("backlog").description("manage the local backlog used by business workSource=backlog");function yn(e){let o=I(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new vc(n)}}function If(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function Cf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}nt.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}=yn(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(X.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${Cf(n.status).padEnd(7)} ${If(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});nt.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=yn(t.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=xc([o],i.source,n.config),a=await ci(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});nt.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=yn(o.config);t.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await ci(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});nt.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}=yn(o.config);t.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});nt.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=yn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(X.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Rt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Nf(o.config):_f(o.config);y.length?(i=(await Rt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Rt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Rt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Rt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Df(o.config,i,a):await Pf(o.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=ai({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Rt({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(X.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?Rf(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:ai(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(p);console.log(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(X.dim(` ${y.id} \u2014 ${y.title}`))});function Rf(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Nf(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 _f(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 Df(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 Pf(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(Dd)}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(Dd):[]}function Dd(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 Mf}from"commander";import W from"chalk";import{existsSync as Lf,readFileSync as Ff}from"fs";import{resolve as Uf}from"path";import qf from"prompts";ae();function Pd(e){let o=e||Uf(process.cwd(),"agentx.json");return Lf(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Ff(o,"utf-8"))}async function Wf(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await qf([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wo=new Mf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wo.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: ${Zs})`,Zs).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){wo.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Qs(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Pd(o.config),s=Rr(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Wf(o.notify,s),r=o.id||aa(t.matched,o.agent),a=la({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:ca(o.onError),enabled:!o.disabled}),c=a.onError,l=await ye(d=>Oe(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.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=Pd(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=ga(da(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])wo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await ua(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ye(t=>{if(!ut(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);sa(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",ma,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",pa,"reject an agent's pending create/delete request (drops the request)"]])wo.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Qs(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as Bf}from"commander";import xe from"chalk";var Mo=new Bf("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Jf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Md(){return{root:process.cwd()}}function Gi(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Hf(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Jf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${Gi(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${Gi(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mo.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=za(Md(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(xe.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(xe.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Hf(t),console.log();console.log(xe.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function zi(e,o,t){let n=Yn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Ya(Md(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Mo.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,o)=>zi(e,"yes",o));Mo.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)=>zi(e,"no",o));Mo.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)=>zi(e,"later",o));Mo.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: ${Ha.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let o=Yn(),t=Ga(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:o});if(!t.ok){console.error(xe.red(` ${t.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${t.card.id} raised; expires ${Gi(t.card.expires)}, then: ${t.card.if_silent}`))});Mo.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let o={},t=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let a=_c(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await Dc(o);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=Yn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as uh}from"commander";import Nt from"chalk";import ne from"chalk";import bn from"prompts";import{readFileSync as Gf,writeFileSync as zf,existsSync as Yf}from"fs";import{resolve as Ld}from"path";var Vf=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Kf(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Yi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Fd(e=".env"){let o=Ld(e);if(!Yf(o))return[];let t=Gf(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(Vf);i?n.push({kind:"kv",key:i[1],value:Kf(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Xf(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Yi(o.value)}`:o.raw).join(`
405
405
  `)+`
406
- `}function hn(e,o,t=".env"){let n=Id(t),s=jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Wi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Wi(o)}`})),_f(n,Lf(s))}function Bi(e,o=".env"){return jd(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Cd="https://t.me/BotFather";async function Ff(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 Uf(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 Nd(e={}){console.log(),console.log(ne.bold(" Connect Telegram")),console.log(),console.log(ne.dim(` 1. Open ${Cd}`)),console.log(ne.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ne.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await yn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Cd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await yn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ne.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Ff(t.trim());n||(console.log(ne.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ne.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(ne.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(ne.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await yn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ne.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await yn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ne.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;hn(f,t.trim()),process.env[f]=t.trim();let p=await ye(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=ut(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Oe(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(ne.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ne.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ne.dim(` Token stored in .env as ${f}`)),console.log(ne.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ne.dim(" Daemon hot-reloaded.")):console.log(ne.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await yn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(ne.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ne.dim(" Waiting up to 90s..."));let y=await Uf(t.trim(),9e4);if(!y){console.log(ne.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ne.dim(" agentx config set notifications.destination.channel telegram")),console.log(ne.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ne.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ye(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ne.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ne.green(" \u2713 Default --notify target set")),console.log(ne.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ne.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ne.dim(" Daemon hot-reloaded."))}import be from"chalk";import Ji from"prompts";import{existsSync as Gi,mkdirSync as qf,readdirSync as Wf,readFileSync as Rd}from"fs";import{resolve as Hi}from"path";var Bf=".agentx/whatsapp-sessions";function Jf(){let e=Hi(process.cwd(),".agentx/daemon.pid");if(!Gi(e))return!1;try{let o=parseInt(Rd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Hf(e){if(!Gi(e))return!1;try{return Wf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;qf(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function _d(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),Jf()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ji({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||Hi(process.cwd(),"agentx.json");Gi(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Rd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Bf,s=Hi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Ji({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Hf(s)&&a){let{keep:l}=await Ji({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Gf(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Oe(l,"channels.whatsapp.enabled",!0),Oe(l,"channels.whatsapp.sessionDir",n),Oe(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as zf}from"crypto";import Ee from"chalk";import Dd from"prompts";var bs="agentx-mesh:",$s="//join/";function Yf(e){return Buffer.from(e,"utf-8").toString("base64url")}function Vf(e){return Buffer.from(e,"base64url").toString("utf-8")}function Kf(e){return`${bs}${$s}${Yf(JSON.stringify(e))}`}function Xf(e){if(!e.startsWith(`${bs}${$s}`))throw new Error(`Not a mesh invite link \u2014 expected ${bs}${$s}\u2026`);let o=e.slice(bs.length+$s.length),t=JSON.parse(Vf(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 Qf(){return zf(32).toString("hex")}function Zf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function eh(e){return e?.node?.name||e?.node?.id||"node"}async function Pd(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(Ee.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Bi("MESH_TOKEN");r||(r=Qf(),hn("MESH_TOKEN",r),console.log(Ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Zf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Dd({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(Ee.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ee.red(` \u2717 ${l.error}`)),process.exit(1));let g=Kf({url:a,token:r,name:eh(i),version:1});console.log(),console.log(Ee.bold(" Mesh invite")),console.log(),console.log(` ${Ee.cyan(g)}`),console.log(),console.log(Ee.dim(" Run on the other node:")),console.log(Ee.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ee.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Md(e,o={}){let t;try{t=Xf(e)}catch(i){console.log(Ee.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Bi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Dd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ee.red(" Aborted (keeping existing .env)")),process.exit(1))}hn("MESH_TOKEN",t.token);let s=await ye(i=>{Oe(i,"mesh.enabled",!0);let r=ut(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),Oe(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ee.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ee.green(" \u2713 Joined mesh")),console.log(Ee.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ee.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.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(Ee.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ee.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ee.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var _t=new oh().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");_t.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 Nd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});_t.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 _d({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Ld=_t.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Ld.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 Pd({url:e.url,configPath:e.config})});Ld.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 Md(e,{configPath:o.config})});_t.action(()=>{console.log(),console.log(Rt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Rt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Rt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Rt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Rt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Rt.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as th}from"commander";import ue from"chalk";var wn=new th().name("usage").description("token usage analysis and reporting");wn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=j(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});wn.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(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});wn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-ZRGI76RT.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(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.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(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as nh}from"commander";import $e from"chalk";import{readFileSync as sh}from"fs";import{resolve as ih}from"path";ae();var Lo=new nh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lo.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{Nr(ih(process.cwd(),".env"))}catch{}let o=rh(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-ZE2A3ARS.js");t(o)}catch(o){console.log($e.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log($e.dim(o.stack)),process.exit(1)}});function rh(e,o){try{let t=j();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
407
- `)),{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}}}}Lo.command("list").description("list configured boards").action(()=>{try{let e=j();if(!e.boards?.length){console.log($e.dim(`
406
+ `}function wn(e,o,t=".env"){let n=Ld(t),s=Fd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Yi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Yi(o)}`})),zf(n,Xf(s))}function Vi(e,o=".env"){return Fd(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Ud="https://t.me/BotFather";async function Qf(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 Zf(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 qd(e={}){console.log(),console.log(ne.bold(" Connect Telegram")),console.log(),console.log(ne.dim(` 1. Open ${Ud}`)),console.log(ne.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ne.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await bn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Ud],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await bn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ne.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Qf(t.trim());n||(console.log(ne.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ne.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(ne.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(ne.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await bn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ne.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await bn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ne.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;wn(f,t.trim()),process.env[f]=t.trim();let p=await ye(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=ut(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Oe(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(ne.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ne.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ne.dim(` Token stored in .env as ${f}`)),console.log(ne.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ne.dim(" Daemon hot-reloaded.")):console.log(ne.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await bn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(ne.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ne.dim(" Waiting up to 90s..."));let y=await Zf(t.trim(),9e4);if(!y){console.log(ne.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ne.dim(" agentx config set notifications.destination.channel telegram")),console.log(ne.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ne.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ye(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ne.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ne.green(" \u2713 Default --notify target set")),console.log(ne.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ne.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ne.dim(" Daemon hot-reloaded."))}import be from"chalk";import Ki from"prompts";import{existsSync as Qi,mkdirSync as eh,readdirSync as oh,readFileSync as Wd}from"fs";import{resolve as Xi}from"path";var th=".agentx/whatsapp-sessions";function nh(){let e=Xi(process.cwd(),".agentx/daemon.pid");if(!Qi(e))return!1;try{let o=parseInt(Wd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function sh(e){if(!Qi(e))return!1;try{return oh(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function ih(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;eh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Bd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),nh()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ki({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||Xi(process.cwd(),"agentx.json");Qi(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Wd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||th,s=Xi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Ki({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(sh(s)&&a){let{keep:l}=await Ki({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await ih(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Oe(l,"channels.whatsapp.enabled",!0),Oe(l,"channels.whatsapp.sessionDir",n),Oe(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as rh}from"crypto";import Ee from"chalk";import Jd from"prompts";var xs="agentx-mesh:",Ss="//join/";function ah(e){return Buffer.from(e,"utf-8").toString("base64url")}function ch(e){return Buffer.from(e,"base64url").toString("utf-8")}function lh(e){return`${xs}${Ss}${ah(JSON.stringify(e))}`}function dh(e){if(!e.startsWith(`${xs}${Ss}`))throw new Error(`Not a mesh invite link \u2014 expected ${xs}${Ss}\u2026`);let o=e.slice(xs.length+Ss.length),t=JSON.parse(ch(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 gh(){return rh(32).toString("hex")}function mh(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function ph(e){return e?.node?.name||e?.node?.id||"node"}async function Hd(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(Ee.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Vi("MESH_TOKEN");r||(r=gh(),wn("MESH_TOKEN",r),console.log(Ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||mh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Jd({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(Ee.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ee.red(` \u2717 ${l.error}`)),process.exit(1));let g=lh({url:a,token:r,name:ph(i),version:1});console.log(),console.log(Ee.bold(" Mesh invite")),console.log(),console.log(` ${Ee.cyan(g)}`),console.log(),console.log(Ee.dim(" Run on the other node:")),console.log(Ee.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ee.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Gd(e,o={}){let t;try{t=dh(e)}catch(i){console.log(Ee.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Vi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Jd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ee.red(" Aborted (keeping existing .env)")),process.exit(1))}wn("MESH_TOKEN",t.token);let s=await ye(i=>{Oe(i,"mesh.enabled",!0);let r=ut(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),Oe(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ee.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ee.green(" \u2713 Joined mesh")),console.log(Ee.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ee.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.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(Ee.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ee.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ee.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var _t=new uh().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");_t.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 qd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});_t.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 Bd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var zd=_t.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");zd.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 Hd({url:e.url,configPath:e.config})});zd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await Gd(e,{configPath:o.config})});_t.action(()=>{console.log(),console.log(Nt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Nt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Nt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Nt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Nt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Nt.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as fh}from"commander";import ue from"chalk";var $n=new fh().name("usage").description("token usage analysis and reporting");$n.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[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(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});$n.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(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});$n.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-KWSQLVSV.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(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.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(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as hh}from"commander";import $e from"chalk";import{readFileSync as yh}from"fs";import{resolve as wh}from"path";ae();var Lo=new hh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lo.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{Wr(wh(process.cwd(),".env"))}catch{}let o=bh(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-LEUIFDNJ.js");t(o)}catch(o){console.log($e.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log($e.dim(o.stack)),process.exit(1)}});function bh(e,o){try{let t=I();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
407
+ `)),{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}}}}Lo.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log($e.dim(`
408
408
  No boards configured.
409
- `));return}console.log();for(let o of e.boards){console.log(` ${$e.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log($e.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log($e.dim(` primary label: ${o.primaryToolLabel}`)),console.log($e.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});Lo.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{bn(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($e.red(` ${t.message}`)),process.exit(1)}});Lo.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{bn(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($e.red(` ${t.message}`)),process.exit(1)}});var zi=Lo.command("column").description("manage a board's columns (add / remove / edit / list)");zi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(sh("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($e.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(` ${$e.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${$e.dim(i)}`)}}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});zi.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{bn(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($e.red(` ${n.message}`)),process.exit(1)}});zi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{bn(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($e.red(` ${t.message}`)),process.exit(1)}});Lo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{bn(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($e.red(` ${o.message}`)),process.exit(1)}});function bn(e){let{summary:o,backupPath:t}=ao(n=>e(n));console.log($e.green(`
409
+ `));return}console.log();for(let o of e.boards){console.log(` ${$e.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log($e.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log($e.dim(` primary label: ${o.primaryToolLabel}`)),console.log($e.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});Lo.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{kn(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($e.red(` ${t.message}`)),process.exit(1)}});Lo.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{kn(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($e.red(` ${t.message}`)),process.exit(1)}});var Zi=Lo.command("column").description("manage a board's columns (add / remove / edit / list)");Zi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(yh("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($e.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(` ${$e.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${$e.dim(i)}`)}}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});Zi.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{kn(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($e.red(` ${n.message}`)),process.exit(1)}});Zi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{kn(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($e.red(` ${t.message}`)),process.exit(1)}});Lo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{kn(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($e.red(` ${o.message}`)),process.exit(1)}});function kn(e){let{summary:o,backupPath:t}=ao(n=>e(n));console.log($e.green(`
410
410
  \u2713 ${o}
411
411
  `)),t&&console.log($e.dim(` Backup: ${t}`)),console.log($e.dim(` Restart the dashboard to pick up the change if not auto-reloading.
412
- `))}import{Command as ah}from"commander";import m from"chalk";import{resolve as F,relative as Fd,dirname as Ud}from"path";import{execSync as st}from"child_process";import{writeFileSync as it,mkdirSync as bo,readFileSync as $n,readdirSync as ch,renameSync as ks,rmSync as lh,existsSync as Ye}from"fs";function Ae(e,o){return new Ws(kn(e),void 0,o||"graph")}function kn(e){return e||F(process.cwd(),".agentx/wiki")}function Vi(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Z=new ah().name("wiki").description("wiki knowledge base management");Z.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=Ae(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Vi(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())});Z.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=Ae(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});Z.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=Ae(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=F(process.cwd(),".agentx/graph");return Ye(u)?new vo({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(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),w=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(w)},l=(u,f)=>{let p=new Map;for(let y of u){let k=f.find(S=>S.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let v=b.join("/"),A=p.get(v);A?A.n++:p.set(v,{path:b,n:1})}if(p.size===0)return;let w;for(let y of p.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter($=>!f||($.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 $ of p.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(u),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
412
+ `))}import{Command as $h}from"commander";import m from"chalk";import{resolve as F,relative as Yd,dirname as Vd}from"path";import{execSync as st}from"child_process";import{writeFileSync as it,mkdirSync as bo,readFileSync as vn,readdirSync as kh,renameSync as Es,rmSync as vh,existsSync as Ye}from"fs";function Ae(e,o){return new Ys(xn(e),void 0,o||"graph")}function xn(e){return e||F(process.cwd(),".agentx/wiki")}function or(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Z=new $h().name("wiki").description("wiki knowledge base management");Z.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=Ae(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${or(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())});Z.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=Ae(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});Z.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=Ae(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=F(process.cwd(),".agentx/graph");return Ye(u)?new vo({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(y=>typeof y=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),w=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(w)},l=(u,f)=>{let p=new Map;for(let y of u){let k=f.find(S=>S.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let v=b.join("/"),A=p.get(v);A?A.n++:p.set(v,{path:b,n:1})}if(p.size===0)return;let w;for(let y of p.values())(!w||y.n>w.n)&&(w=y);return w?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=t.getUnabsorbedEntries(u).filter($=>!f||($.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 $ of p.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(u),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
413
413
  ${$.content}
414
414
  --- END ENTRY ---`).join(`
415
415
 
416
- `),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:R,mergeRecords:C,renderFactsBlock:I,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Te of t.listAgents())for(let ke of t.getAgentWiki(Te).listArticles(Te))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=$(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:Te,results:ke}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...me,...Te]);v=I(M);let ze=[...me.length>0?[`entries:${me.length}`]:[],...ke.filter(ve=>ve.records.length>0).map(ve=>`${ve.source}:${ve.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${ze.length?` (${ze.join(" ")})`:""}`));for(let ve of P(ke,J))console.log(m.yellow(` ! ${ve.source} ${ve.kind} \u2014 would supply ${ve.provides.join(", ")}`)),console.log(m.dim(` ${ve.hint}`))}}let A=ma(o,u,k,y.articles,b,p.length,v);console.log(m.dim(` Mode: ${Vi(o)}`));let S=F(w.baseDir,"_tmp");bo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");it(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=st(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:lt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if($=M.stdout||"",!$)throw M}let R=$;try{let M=JSON.parse($);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 C,I=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],me=G==="{"?"}":"]",J=0,Te=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){Te=M+1;break}if(Te===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=R.slice(L,Te);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],I=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ke.slice(0,300)}`));continue}for(let M of C){let ze=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);w.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:ze,lastUpdated:ze,sources:M.sources||[],graphPath:ve},M.content,u);let Jo=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("+")} ${Jo}${M.path}: ${M.title}${m.dim(_)}`);let he=(M.tags||[]).slice(0,4).join(", ");he&&console.log(m.dim(` tags: ${he}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(I.length>0){console.log(),console.log(m.yellow(` Gaps detected (${I.length} missing pieces):`));for(let M of I)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-2V2VGIT4.js"),ze=new M(kn(e.dir)).add(I.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));ze.added>0&&console.log(m.dim(` queued ${ze.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let 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()});Z.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=dh(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-LEO2N65G.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ye(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ye(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 w=p[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await pa({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 vs=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function xs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}vs.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(xs(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}`))}});vs.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(xs(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(`
416
+ `),v="";if(e.facts!==!1){let{extractHints:$,resolveFacts:N,mergeRecords:C,renderFactsBlock:j,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-4YPSHIXJ.js");if(!a){let J=new Set;for(let Te of t.listAgents())for(let ke of t.getAgentWiki(Te).listArticles(Te))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=$(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:Te,results:ke}=G.length>0?await N(G,{sources:J}):{records:[],results:[]},M=C([...me,...Te]);v=j(M);let ze=[...me.length>0?[`entries:${me.length}`]:[],...ke.filter(ve=>ve.records.length>0).map(ve=>`${ve.source}:${ve.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${ze.length?` (${ze.join(" ")})`:""}`));for(let ve of P(ke,J))console.log(m.yellow(` ! ${ve.source} ${ve.kind} \u2014 would supply ${ve.provides.join(", ")}`)),console.log(m.dim(` ${ve.hint}`))}}let A=ka(o,u,k,y.articles,b,p.length,v);console.log(m.dim(` Mode: ${or(o)}`));let S=F(w.baseDir,"_tmp");bo(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");it(x,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=st(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:lt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if($=M.stdout||"",!$)throw M}let N=$;try{let M=JSON.parse($);N=M.result||M.content||"",N||(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 C,j=[],P=N.indexOf("{"),B=N.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(N.slice(0,500)));continue}let G=N[L],me=G==="{"?"}":"]",J=0,Te=-1;for(let M=L;M<N.length;M++)if(N[M]===G)J++;else if(N[M]===me&&(J--,J===0)){Te=M+1;break}if(Te===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=N.slice(L,Te);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],j=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ke.slice(0,300)}`));continue}for(let M of C){let ze=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);w.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:ze,lastUpdated:ze,sources:M.sources||[],graphPath:ve},M.content,u);let Jo=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("+")} ${Jo}${M.path}: ${M.title}${m.dim(_)}`);let he=(M.tags||[]).slice(0,4).join(", ");he&&console.log(m.dim(` tags: ${he}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(j.length>0){console.log(),console.log(m.yellow(` Gaps detected (${j.length} missing pieces):`));for(let M of j)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-2V2VGIT4.js"),ze=new M(xn(e.dir)).add(j.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));ze.added>0&&console.log(m.dim(` queued ${ze.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let 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()});Z.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=xh(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-A6CLXAFS.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ye(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ye(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 w=p[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await va({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 As=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Ts(e){return e?F(e):F(process.cwd(),".agentx","wiki")}As.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(Ts(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}`))}});As.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(Ts(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(`
417
417
  `).map(s=>` ${s}`).join(`
418
- `)),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>)`))}});vs.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-KPEOVZ5V.js"),n=t(xs(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`))});vs.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-KPEOVZ5V.js"),n=t(xs(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 dh(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)}Z.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-WRWFAW5G.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Ae(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 y of f){let k=r(d,y),b=[];try{b=t(k).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(u.length>=g)break;try{let A=JSON.parse(n(r(k,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}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 y=0;y<u.length;y++){let k=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let v=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
418
+ `)),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>)`))}});As.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-FDEKCVAE.js"),n=t(Ts(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`))});As.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-FDEKCVAE.js"),n=t(Ts(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 xh(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)}Z.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-PJG52OHP.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Ae(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 y of f){let k=r(d,y),b=[];try{b=t(k).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(u.length>=g)break;try{let A=JSON.parse(n(r(k,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}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 y=0;y<u.length;y++){let k=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let v=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
419
419
  `)||"_(none returned)_",A;try{let S=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
420
420
 
421
421
  ${S.answer}
422
422
 
423
423
  **Citations:** ${x}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),p.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=p.join(`
424
- `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});Z.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-S6NHM5C3.js"),s=e.answers?$n(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=Ae(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 he=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${he.slice(0,80)}${he.length>80?"\u2026":""}`)+`
424
+ `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});Z.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-S6NHM5C3.js"),s=e.answers?vn(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=Ae(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 he=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${he.slice(0,80)}${he.length>80?"\u2026":""}`)+`
425
425
  `),he.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 w=[],y=!1;for(let _=0;_<p.length;_++){let he=p[_],Ve=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${he}
426
426
  ${m.green(">")} `);if(Ve==="/abort"){y=!0;break}if(Ve==="/done")break;Ve!=="/skip"&&Ve&&w.push({q:he,a:Ve})}if(!y){let _=await l(`
427
427
  ${m.dim("Anything else worth capturing?")}
@@ -430,16 +430,16 @@ ${S.answer}
430
430
  `),v=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(_=>`
431
431
  Q: ${_.q}
432
432
  A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
433
- `),A=F(a.baseDir,"_tmp");bo(A,{recursive:!0});let S=F(A,`interview-${t().slice(0,8)}.txt`);it(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,he=st(_,{env:lt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ve=JSON.parse(he);x=String(Ve.result||Ve.content||"")}catch{x=he}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let $=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(x=$[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let C=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let I={};for(let _ of C[1].split(`
434
- `)){let he=_.match(/^(\w+):\s*(.+)$/);he&&(I[he[1]]=he[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=I.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),me=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${me}`)),console.log(),console.log(x),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let Te=P,ke={title:B,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",he=F(A,`draft-${t().slice(0,8)}.md`);it(he,x);try{st(`${_} '${he}'`,{stdio:"inherit"});let Fs=$n(he,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Fs){let ko={};for(let Gt of Fs[1].split(`
435
- `)){let Us=Gt.match(/^(\w+):\s*(.+)$/);Us&&(ko[Us[1]]=Us[2].trim().replace(/^"(.*)"$/,"$1"))}Te=Fs[2],ke={...ke,title:ko.title||ke.title,type:ko.type||ke.type,access:ko.access||ke.access,related:ko.related?ko.related.replace(/^\[|\]$/g,"").split(",").map(Gt=>Gt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:ko.tags?ko.tags.replace(/^\[|\]$/g,"").split(",").map(Gt=>Gt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Ve){console.log(m.red(` editor failed: ${Ve.message}`));return}}if(!a.writeArticle(me,ke,Te,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let ze=a.extractWikilinks(Te),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Jo=ze.filter(_=>!ve.has(_.toLowerCase()));if(Jo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Jo.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.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-WRWFAW5G.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Ae(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=$n(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of p){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,w;if(r){let G=r[f];if(!G)break;p=G.q,w=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let G=y.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
436
- `)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:p,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let $=mh(x.content,v,A,x.meta.title,x.meta.type),R=F(i.baseDir,"_tmp");bo(R,{recursive:!0});let C=F(R,`quiz-patch-${t().slice(0,8)}.txt`);it(C,$);let I="";try{let G=`cat '${C}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=st(G,{env:lt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Te=JSON.parse(me);I=String(Te.result||Te.content||"")}catch{I=me}let J=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(I=J[1].trim()),I=I.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
437
- `).length,B=I.split(`
438
- `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let w=d[p];f.push(`## ${p+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}it(e.out,f.join(`
439
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});Z.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=Ae(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=Bd(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{st(`${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)}`))}});Z.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=Ae(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=Bd(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=gh(l.content,l.meta.title,l.meta.type,t),d=F(a.baseDir,"_tmp");bo(d,{recursive:!0});let u=F(d,`patch-${i().slice(0,8)}.txt`);it(u,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let S=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=st(S,{env:lt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(x);f=String(R.result||R.content||"")}catch{f=x}let $=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(f=$[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(`
433
+ `),A=F(a.baseDir,"_tmp");bo(A,{recursive:!0});let S=F(A,`interview-${t().slice(0,8)}.txt`);it(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,he=st(_,{env:lt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ve=JSON.parse(he);x=String(Ve.result||Ve.content||"")}catch{x=he}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let $=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(x=$[1].trim());let N=x.indexOf("---");N>0&&(x=x.slice(N));let C=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let j={};for(let _ of C[1].split(`
434
+ `)){let he=_.match(/^(\w+):\s*(.+)$/);he&&(j[he[1]]=he[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=j.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),me=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${me}`)),console.log(),console.log(x),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let Te=P,ke={title:B,type:j.type||d,related:j.related?j.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:j.tags?j.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:j.access||"public",created:j.created||new Date().toISOString().slice(0,10),lastUpdated:j.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",he=F(A,`draft-${t().slice(0,8)}.md`);it(he,x);try{st(`${_} '${he}'`,{stdio:"inherit"});let Hs=vn(he,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Hs){let ko={};for(let Yt of Hs[1].split(`
435
+ `)){let Gs=Yt.match(/^(\w+):\s*(.+)$/);Gs&&(ko[Gs[1]]=Gs[2].trim().replace(/^"(.*)"$/,"$1"))}Te=Hs[2],ke={...ke,title:ko.title||ke.title,type:ko.type||ke.type,access:ko.access||ke.access,related:ko.related?ko.related.replace(/^\[|\]$/g,"").split(",").map(Yt=>Yt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:ko.tags?ko.tags.replace(/^\[|\]$/g,"").split(",").map(Yt=>Yt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Ve){console.log(m.red(` editor failed: ${Ve.message}`));return}}if(!a.writeArticle(me,ke,Te,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let ze=a.extractWikilinks(Te),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Jo=ze.filter(_=>!ve.has(_.toLowerCase()));if(Jo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Jo.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.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-PJG52OHP.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Ae(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=vn(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of p){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,w;if(r){let G=r[f];if(!G)break;p=G.q,w=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let G=y.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
436
+ `)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:p,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push(k),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let $=Eh(x.content,v,A,x.meta.title,x.meta.type),N=F(i.baseDir,"_tmp");bo(N,{recursive:!0});let C=F(N,`quiz-patch-${t().slice(0,8)}.txt`);it(C,$);let j="";try{let G=`cat '${C}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=st(G,{env:lt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Te=JSON.parse(me);j=String(Te.result||Te.content||"")}catch{j=me}let J=j.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(j=J[1].trim()),j=j.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!j||j.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
437
+ `).length,B=j.split(`
438
+ `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},j,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let w=d[p];f.push(`## ${p+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}it(e.out,f.join(`
439
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});Z.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=Ae(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=Qd(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{st(`${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)}`))}});Z.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=Ae(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=Qd(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=Sh(l.content,l.meta.title,l.meta.type,t),d=F(a.baseDir,"_tmp");bo(d,{recursive:!0});let u=F(d,`patch-${i().slice(0,8)}.txt`);it(u,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let S=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=st(S,{env:lt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let N=JSON.parse(x);f=String(N.result||N.content||"")}catch{f=x}let $=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(f=$[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(`
440
440
  `).length,w=f.split(`
441
- `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${w} lines (${w-p>=0?"+":""}${w-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),y=x==="y"||x==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(l.meta.related||[]).filter(S=>!b.includes(S));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Bd(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 gh(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(`
442
- `)}function mh(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
441
+ `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${w} lines (${w-p>=0?"+":""}${w-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),y=x==="y"||x==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(l.meta.related||[]).filter(S=>!b.includes(S));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Qd(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 Sh(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(`
442
+ `)}function Eh(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
443
443
 
444
444
  ${t}
445
445
 
@@ -452,8 +452,8 @@ Incorporate it into the most relevant existing section, or create a short new se
452
452
  ${t}
453
453
 
454
454
  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(`
455
- `)}Z.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=Ae(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(!Ye(u))continue;let f=F(u,i),p=r.map(b=>({mode:b,dir:F(u,b)})).filter(b=>Ye(b.dir));if(p.length===0)continue;let w=new Map;Yi(f,b=>{let v=Fd(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=qd($n(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)Yi(b.dir,v=>{let A=Fd(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let S=qd($n(v,"utf-8"));S?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),S;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?S="upgrade":S="archive":S="promote";let x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${$} ${x} ${m.dim(b.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let C=F(f,b.relPath);Ye(C)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Wd(u,b),g++):(bo(Ud(C),{recursive:!0}),ks(b.absPath,C),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let C=F(f,A.relPath);if(Ye(C)){let I=F(u,"_versions",A.relPath.replace(/\.md$/,""));bo(I,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");ks(C,F(I,`${P}.md`))}bo(Ud(C),{recursive:!0}),ks(b.absPath,C),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else Wd(u,b),g++}catch(C){console.log(m.red(` ! ${S} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let b of p)try{lh(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Yi(e,o){if(Ye(e))for(let t of ch(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?Yi(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function qd(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
456
- `)){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 Wd(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));bo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");ks(o.absPath,F(t,`${n}.md`))}Z.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=Ae(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let w=g.baseDir,y=F(w,"_tmp");bo(y,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),v=uh(b),A=F(y,"migrate-prompt.txt");it(A,v);let S;try{let x=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$=st(x,{env:lt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse($),I=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!I)throw new Error("no JSON array in classifier response");S=JSON.parse(I[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let $=S.find(L=>L.path===x.path),R=ph($?.type);if(!$||!R){console.log(m.yellow(` ? ${x.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let C=g.extractWikilinks(x.content),I={...x.meta,type:R.type,related:C.length?C:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=C.length?m.dim(` \u2192 ${C.slice(0,3).join(", ")}${C.length>3?", \u2026":""}`):"",B=R.alias?m.dim(` (from "${R.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+R.type+"]")}${B} ${x.path}${P}`),i&&(g.writeArticle(x.path,I,x.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function ph(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 uh(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}"
455
+ `)}Z.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=Ae(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(!Ye(u))continue;let f=F(u,i),p=r.map(b=>({mode:b,dir:F(u,b)})).filter(b=>Ye(b.dir));if(p.length===0)continue;let w=new Map;er(f,b=>{let v=Yd(f,b);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let A=Kd(vn(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:v,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of p)er(b.dir,v=>{let A=Yd(b.dir,v);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let S=Kd(vn(v,"utf-8"));S?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:v,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let v=b.title.toLowerCase(),A=w.get(v),S;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?S="upgrade":S="archive":S="promote";let x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),N=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${$} ${x} ${m.dim(b.mode+"/")}${N}`),S==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let C=F(f,b.relPath);Ye(C)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Xd(u,b),g++):(bo(Vd(C),{recursive:!0}),Es(b.absPath,C),w.set(v,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let C=F(f,A.relPath);if(Ye(C)){let j=F(u,"_versions",A.relPath.replace(/\.md$/,""));bo(j,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");Es(C,F(j,`${P}.md`))}bo(Vd(C),{recursive:!0}),Es(b.absPath,C),w.set(v,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else Xd(u,b),g++}catch(C){console.log(m.red(` ! ${S} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let b of p)try{vh(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function er(e,o){if(Ye(e))for(let t of kh(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?er(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Kd(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
456
+ `)){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 Xd(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));bo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Es(o.absPath,F(t,`${n}.md`))}Z.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=Ae(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let w=g.baseDir,y=F(w,"_tmp");bo(y,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),v=Th(b),A=F(y,"migrate-prompt.txt");it(A,v);let S;try{let x=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$=st(x,{env:lt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),N=JSON.parse($),j=String(N.result||N.content||"").match(/\[[\s\S]*\]/);if(!j)throw new Error("no JSON array in classifier response");S=JSON.parse(j[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let $=S.find(L=>L.path===x.path),N=Ah($?.type);if(!$||!N){console.log(m.yellow(` ? ${x.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let C=g.extractWikilinks(x.content),j={...x.meta,type:N.type,related:C.length?C:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=C.length?m.dim(` \u2192 ${C.slice(0,3).join(", ")}${C.length>3?", \u2026":""}`):"",B=N.alias?m.dim(` (from "${N.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+N.type+"]")}${B} ${x.path}${P}`),i&&(g.writeArticle(x.path,j,x.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Ah(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 Th(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}"
457
457
  title: "${t.meta.title}"
458
458
  tags: [${i}]
459
459
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -493,51 +493,51 @@ Output (JSON array, one entry per input article, same order):
493
493
  [
494
494
  {"path": "path/to/article.md", "type": "project"},
495
495
  ...
496
- ]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Ae(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()});Z.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-EXNBBAZG.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(),Cc(o,t,e.agent,n,e.mode)});Z.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-PBFG5R7D.js"),c=Ae(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(u.length>=g)break e;let v=k.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),$=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!($&&!$.fit)||u.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(y=>Math.max(y.length,...u.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map(k=>y[k])));if(e.fields){let y=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
496
+ ]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Ae(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()});Z.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-VV4X7PEK.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(),Uc(o,t,e.agent,n,e.mode)});Z.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-W3ZTOJUT.js"),c=Ae(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(u.length>=g)break e;let v=k.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...o(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,t({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),$=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!($&&!$.fit)||u.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(y=>Math.max(y.length,...u.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map(k=>y[k])));if(e.fields){let y=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
497
497
  ${u.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
498
- ${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."))});Z.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-WRWFAW5G.js"),n=Ae(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()}});Z.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=Ae(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()});Z.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=Ae(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ye(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vo({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(),w=new Map(p.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let R=String($.meta?.sender??""),C=s.fingerprint({text:$.content,channel:$.source,sender:R}),I=r.get(C);if(!I?.length)continue;let P=I.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:I,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.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=Ae(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-EXNBBAZG.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()});Z.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 Ws(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Vi(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(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()});Z.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");Ye(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=Ye(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${fh(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.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-PBFG5R7D.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Ae(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let R of $.listArticles(x)){if(f>=u)break e;let C=$.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let I=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),o(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(C.meta.type,I.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(kn(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 y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...p.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of p)console.log(y.map(($,R)=>v(x[$],R)).join(" "));let A=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${p.length-A} 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 ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=$);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-EXNBBAZG.js"),I=C(),P=I?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
499
- `),L=R.length>10?`
500
- \u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
498
+ ${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."))});Z.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-PJG52OHP.js"),n=Ae(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()}});Z.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=Ae(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()});Z.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=Ae(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ye(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vo({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(),w=new Map(p.map(v=>[v.id,v])),y=0,k=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let $=w.get(x);if(!$)continue;let N=String($.meta?.sender??""),C=s.fingerprint({text:$.content,channel:$.source,sender:N}),j=r.get(C);if(!j?.length)continue;let P=j.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:j,n:1})}if(A.size===0)continue;k++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.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=Ae(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-VV4X7PEK.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()});Z.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 Ys(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:or(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(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()});Z.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");Ye(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=Ye(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Oh(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.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-W3ZTOJUT.js"),{QuestionStore:c}=await import("./questions-2V2VGIT4.js"),l=Ae(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let $=l.getAgentWiki(x);for(let N of $.listArticles(x)){if(f>=u)break e;let C=$.readArticle(N.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let j=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),o(C.meta.type),{links:[{kind:"article",id:N.path}],features:{agent:x,type:C.meta.type??"?"}});if(!j){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(C.meta.type,j.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:N.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(xn(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 y=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...p.map($=>k($[x]).length))),v=(x,$)=>String(x)+" ".repeat(Math.max(0,b[$]-k(x).length));console.log(),console.log(m.bold(y.map((x,$)=>v(x,$)).join(" ")));for(let x of p)console.log(y.map(($,N)=>v(x[$],N)).join(" "));let A=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${p.length-A} 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 ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),$=x[e.notifyTier]??x.pillar,N=g.filter(C=>(x[C.tier??"furniture"]??9)<=$);if(N.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-VV4X7PEK.js"),j=C(),P=j?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=N.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
499
+ `),L=N.length>10?`
500
+ \u2026and ${N.length-10} more`:"",G=`${N.length} wiki gap(s) need you (${e.notifyTier}+):
501
501
  ${B}${L}
502
502
 
503
- agentx wiki questions`,me=I?.daemon?.port??I?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.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-PBFG5R7D.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Ae(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(I=>[I.name.toLowerCase().trim(),I])),v=0,A=0,S=[],x=!1;e:for(let I of p){let P=f.getAgentWiki(I);for(let B of P.listArticles(I)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:I,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Te,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let ze=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...Te]);if(ze.length===0)continue;let{content:ve,edits:Jo}=u(L.content,ze[0],J);if(Jo.length!==0){for(let _ of Jo)S.push({agent:I,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,I)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],R=$.map(I=>Math.max(I.length,...S.map(P=>String(P[I]).length))),C=I=>I.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C($)));for(let I of S)console.log(C($.map(P=>I[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(kn(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`))});Z.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(kn(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Ae(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(u?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Z.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-PBFG5R7D.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=Ae(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:k}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),I=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:C,failures:S,elapsed:I},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 ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${P($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let L=$.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Te,ke)=>ke.recall-Te.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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);Ye(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");Ye(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 fh(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"}Ug();import{Command as hh}from"commander";import D from"chalk";import{resolve as Ss}from"path";import{existsSync as yh}from"fs";ae();var Dt=new hh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Dt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=j();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new vo({baseDir:Ss(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 w=r[p],y=jn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let k=wh(w,a,c),b=null;try{b=await bh(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{$h(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),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()});Dt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=j();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Ss(process.cwd(),o.graph.baseDir);if(!yh(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new vo({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()});Dt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=j();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new vo({baseDir:Ss(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let C=await fetch(`${t}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let I=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch($){console.log(D.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.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 w=p?r:l,y=new Map;w.levels.forEach(($,R)=>y.set($.id,R));let k=[...g].sort(($,R)=>(y.get($.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${$.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function wh(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(`
503
+ agentx wiki questions`,me=j?.daemon?.port??j?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${N.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.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-W3ZTOJUT.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-4YPSHIXJ.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Ae(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(j=>[j.name.toLowerCase().trim(),j])),v=0,A=0,S=[],x=!1;e:for(let j of p){let P=f.getAgentWiki(j);for(let B of P.listArticles(j)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:j,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Te,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let ze=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...Te]);if(ze.length===0)continue;let{content:ve,edits:Jo}=u(L.content,ze[0],J);if(Jo.length!==0){for(let _ of Jo)S.push({agent:j,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,j)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],N=$.map(j=>Math.max(j.length,...S.map(P=>String(P[j]).length))),C=j=>j.map((P,B)=>String(P).padEnd(N[B])).join(" ");console.log(),console.log(m.bold(C($)));for(let j of S)console.log(C($.map(P=>j[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-2V2VGIT4.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(xn(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`))});Z.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-2V2VGIT4.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(xn(t.dir));if(t.dismiss){let f=r.resolve(e,"dismissed");console.log(f?m.dim(` dismissed: ${f.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=Ae(t.dir,t.mode).getAgentWiki(a.agentId),g=l.readArticle(a.path);if(!g){console.log(m.yellow(` article gone: ${a.path}`));return}let d=s(g.content,a.field,`${o} (answered by operator)`);if(!d){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=l.writeArticle(a.path,g.meta,d.content,a.agentId);console.log(u?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Z.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-W3ZTOJUT.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=Ae(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:k}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),N=l(A,"seat","seat"),C=d(N,{minN:50}),j=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:C,failures:S,elapsed:j},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${P($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let L=$.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${j}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Te,ke)=>ke.recall-Te.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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);Ye(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");Ye(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 Oh(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"}Zg();import{Command as jh}from"commander";import D from"chalk";import{resolve as Os}from"path";import{existsSync as Ih}from"fs";ae();var Dt=new jh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Dt.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=I();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 vo({baseDir:Os(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 w=r[p],y=Nn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let k=Ch(w,a,c),b=null;try{b=await Rh(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{Nh(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),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()});Dt.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=I();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Os(process.cwd(),o.graph.baseDir);if(!Ih(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-5VGHWPBW.js"),s=new vo({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()});Dt.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=I();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 vo({baseDir:Os(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let C=await fetch(`${t}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let j=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!j.ok)throw new Error(`classifications HTTP ${j.status}`);d=(await j.json()).classifications||[]}catch($){console.log(D.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),f=l?.levels?.map($=>$.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 w=p?r:l,y=new Map;w.levels.forEach(($,N)=>y.set($.id,N));let k=[...g].sort(($,N)=>(y.get($.level)??99)-(y.get(N.level)??99)),b=0,v=0,A=0;for(let $ of k){if(c.has($.id)){v++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(N){A++,console.log(D.yellow(` skip node ${$.id}: ${N.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let $ of d)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function Ch(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(`
504
504
  `),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(`
505
- `)}async function bh(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 Or((c?.content||"").toString())}finally{clearTimeout(r)}}function $h(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Ki(){let e=j();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=Ss(process.cwd(),e.graph.baseDir);return{store:new vo({baseDir:o}),baseDir:o}}var Xi=Dt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Xi.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=Ki();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(jn(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]"))});Xi.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=Ki();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}: ${jn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});Xi.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Ki();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 Ah}from"commander";import V from"chalk";import{Command as Hd}from"commander";import le from"chalk";import{existsSync as kh}from"fs";import{resolve as vh}from"path";import xh from"better-sqlite3";function Sh(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(le.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Eh(e){let o=vh(process.cwd(),e);return kh(o)||(console.log(le.red(` No db at ${o}`)),process.exit(1)),new xh(o,{readonly:!0})}var Gd=new Hd().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(Xt)).option("--max <n>","max clusters distilled per run",String(Rn)).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(le.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Eh(e.path),t=await ua(o,{since:Sh(e.since),agentId:e.agent,sessions:new Pr(process.cwd()),minOccurrences:Number(e.minOccurrences)||Xt,max:Number(e.max)||Rn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(le.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(` ${le.cyan(n.key)} ${le.bold(`\xD7${n.count}`)} ${le.dim(n.status)}`),n.sampleMessage&&console.log(le.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(le.dim(`
505
+ `)}async function Rh(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 Lr((c?.content||"").toString())}finally{clearTimeout(r)}}function Nh(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function tr(){let e=I();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=Os(process.cwd(),e.graph.baseDir);return{store:new vo({baseDir:o}),baseDir:o}}var nr=Dt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");nr.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=tr();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(Nn(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]"))});nr.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=tr();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}: ${Nn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});nr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=tr();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 Fh}from"commander";import V from"chalk";import{Command as eg}from"commander";import le from"chalk";import{existsSync as _h}from"fs";import{resolve as Dh}from"path";import Ph from"better-sqlite3";function Mh(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(le.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Lh(e){let o=Dh(process.cwd(),e);return _h(o)||(console.log(le.red(` No db at ${o}`)),process.exit(1)),new Ph(o,{readonly:!0})}var og=new eg().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Zt)).option("--max <n>","max clusters distilled per run",String(Mn)).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(le.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Lh(e.path),t=await xa(o,{since:Mh(e.since),agentId:e.agent,sessions:new Gr(process.cwd()),minOccurrences:Number(e.minOccurrences)||Zt,max:Number(e.max)||Mn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(le.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(` ${le.cyan(n.key)} ${le.bold(`\xD7${n.count}`)} ${le.dim(n.status)}`),n.sampleMessage&&console.log(le.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(le.dim(`
506
506
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(le.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(le.green(` \u2713 draft written: ${n.id}`)+le.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(le.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(le.yellow(` \u26A0 ${n}`));t.dryRun?console.log(le.dim(`
507
507
  dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(le.dim(`
508
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Jd={hourly:"0 * * * *",daily:"0 3 * * *"},zd=new Hd().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(Xt)).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?Jd.hourly:e.daily?Jd.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(le.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(le.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Xt,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 ${Rn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
509
- `),i=await ye(a=>{Oe(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Oe(a,"crons.procedure-extract.enabled",!1):o&&Oe(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(le.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(le.green(` \u2713 ${r} procedure extraction: off`)):(console.log(le.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(le.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(le.dim(" on-task counting: enabled")),console.log(le.dim(` threshold: ${t} occurrences`))),console.log(le.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var so=new Ah().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");so.addCommand(Gd);so.addCommand(zd);so.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 xo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(V.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"?V.green(n.meta.status):n.meta.status==="draft"?V.yellow(n.meta.status):V.dim(n.meta.status);console.log(` ${V.cyan(n.meta.id)} ${V.bold(n.meta.title)} ${s}`),console.log(` ${V.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${V.dim("source:")} ${V.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${V.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(V.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});so.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 xo,t=e.steps?String(e.steps):`## Steps
508
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Zd={hourly:"0 * * * *",daily:"0 3 * * *"},tg=new eg().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(Zt)).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?Zd.hourly:e.daily?Zd.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(le.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(le.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||Zt,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 ${Mn} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
509
+ `),i=await ye(a=>{Oe(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Oe(a,"crons.procedure-extract.enabled",!1):o&&Oe(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(le.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(le.green(` \u2713 ${r} procedure extraction: off`)):(console.log(le.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(le.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(le.dim(" on-task counting: enabled")),console.log(le.dim(` threshold: ${t} occurrences`))),console.log(le.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var so=new Fh().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");so.addCommand(og);so.addCommand(tg);so.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 xo,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(V.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"?V.green(n.meta.status):n.meta.status==="draft"?V.yellow(n.meta.status):V.dim(n.meta.status);console.log(` ${V.cyan(n.meta.id)} ${V.bold(n.meta.title)} ${s}`),console.log(` ${V.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${V.dim("source:")} ${V.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${V.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(V.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});so.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 xo,t=e.steps?String(e.steps):`## Steps
510
510
 
511
511
  1. (fill in)
512
512
 
513
513
  ## Notes
514
514
 
515
- `;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(V.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(V.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(V.red(` add failed: ${n.message}`)),process.exit(1)}});so.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new xo,t=o.get(e)??o.getDraft(e);t||(console.log(V.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(V.bold(` ${t.meta.title}`)+V.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(V.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(V.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(V.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(V.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(V.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(V.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(V.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});so.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new xo;try{let t=o.promoteDraft(e);console.log(V.green(` \u2713 promoted: ${t.meta.id}`)),console.log(V.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});so.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new xo;try{o.rejectDraft(e),console.log(V.green(` \u2713 rejected: ${e}`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});so.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new xo;try{o.deprecate(e),console.log(V.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});so.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 xo,n=Vr(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(V.dim(" no matching procedures"));return}for(let s of n)console.log(` ${V.cyan(s.procedure.meta.id)} ${V.bold(s.score.toFixed(2))} ${V.dim(s.reasons.join(", "))}`),console.log(V.dim(` ${s.procedure.meta.trigger}`))});import{Command as Ih}from"commander";import E from"chalk";import{resolve as Mt,basename as jh}from"path";import{existsSync as Qi,readFileSync as Zi,writeFileSync as Es}from"fs";import OS from"better-sqlite3";import{readFileSync as Th}from"fs";import{resolve as Pt,dirname as Yd}from"path";import{fileURLToPath as Oh}from"url";var vn=[{name:"linear",title:"Linear",description:"Trigger \u2192 Agent \u2192 End. Smallest workflow that runs."},{name:"branching",title:"Branching",description:"Classify, then route on the result via a branch node."},{name:"extract",title:"Structured extraction",description:"Pull typed fields from free-form text via extract.structured."},{name:"retry",title:"Retry + fallback",description:"Per-node retry policy with a branch fallback path."}];function Vd(e){let o=Yd(Oh(import.meta.url)),t=process.argv[1]?Yd(process.argv[1]):"",n=[Pt(o,`${e}.yaml`),Pt(o,"workflows/templates",`${e}.yaml`),Pt(o,"..","workflows/templates",`${e}.yaml`),Pt(o,"../..","workflows/templates",`${e}.yaml`),t?Pt(t,"workflows/templates",`${e}.yaml`):"",t?Pt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Th(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
515
+ `;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(V.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(V.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(V.red(` add failed: ${n.message}`)),process.exit(1)}});so.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new xo,t=o.get(e)??o.getDraft(e);t||(console.log(V.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(V.bold(` ${t.meta.title}`)+V.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(V.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(V.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(V.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(V.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(V.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(V.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(V.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});so.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new xo;try{let t=o.promoteDraft(e);console.log(V.green(` \u2713 promoted: ${t.meta.id}`)),console.log(V.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});so.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new xo;try{o.rejectDraft(e),console.log(V.green(` \u2713 rejected: ${e}`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});so.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new xo;try{o.deprecate(e),console.log(V.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});so.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 xo,n=ia(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(V.dim(" no matching procedures"));return}for(let s of n)console.log(` ${V.cyan(s.procedure.meta.id)} ${V.bold(s.score.toFixed(2))} ${V.dim(s.reasons.join(", "))}`),console.log(V.dim(` ${s.procedure.meta.trigger}`))});import{Command as Wh}from"commander";import E from"chalk";import{resolve as Mt,basename as Bh}from"path";import{existsSync as sr,readFileSync as ir,writeFileSync as js}from"fs";import HS from"better-sqlite3";import{readFileSync as Uh}from"fs";import{resolve as Pt,dirname as ng}from"path";import{fileURLToPath as qh}from"url";var Sn=[{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 sg(e){let o=ng(qh(import.meta.url)),t=process.argv[1]?ng(process.argv[1]):"",n=[Pt(o,`${e}.yaml`),Pt(o,"workflows/templates",`${e}.yaml`),Pt(o,"..","workflows/templates",`${e}.yaml`),Pt(o,"../..","workflows/templates",`${e}.yaml`),t?Pt(t,"workflows/templates",`${e}.yaml`):"",t?Pt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Uh(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
516
516
  ${n.join(`
517
- `)}`)}var He=new Ih().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");He.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Ho().list();if(!o.length){console.log(E.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"?E.green("dispatch: active"):E.yellow(`dispatch: ${t.state}`);console.log(` ${E.cyan(t.id)} ${E.bold(t.title)} ${E.dim(`v${t.version} \xB7`)} ${r} ${E.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${i?` ${E.dim(i)}`:""}`),console.log(` ${E.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});He.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 Ho().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Ur(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});He.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=Mt(process.cwd(),e);Qi(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=Zi(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?mt(r,{filePath:e}):JSON.parse(r),l=gt.safeParse(c);if(!l.success){console.log(E.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=Cn(l.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(E.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof Nn?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new Ho().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(E.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(E.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(E.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});He.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${vn.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");vn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${vn.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(E.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Ho;!o.force&&n.get(e)&&(console.log(E.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Vd(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=mt(s,{filePath:`${e}.yaml`}),c=gt.safeParse(a);if(!c.success){console.log(E.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(E.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=Mt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=mt(s,{filePath:`${e}.yaml`}),c=gt.parse(a);Es(r,JSON.stringify(c,null,2)+`
518
- `)}else Es(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${t}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${r}`)),console.log(E.dim(` 2. agentx workflow validate ${r}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});He.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of vn)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});He.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=Mt(process.cwd(),e);Qi(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=Zi(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?mt(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof Nn?u.message:`parse error: ${u?.message??u}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=gt.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=Cn(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Ho,l=s?jh(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Mt(c.baseDir,`${r.data.id}.${l}`);if(Es(g,s?n:JSON.stringify(r.data,null,2)+`
519
- `),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(E.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(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});He.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 Kt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(E.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"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(r)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${E.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});He.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(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Mt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Qi(s)){let c=Zi(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?mt(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof Nn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=gt.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=Cn(d.data);if(u.length){console.log(E.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Ho,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=Mt(f.baseDir,`${p}.${w}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
520
- `;Es(y,k),n=p,console.log(E.dim(` ad-hoc registered as "${p}" \u2192 ${y}`));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(E.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(E.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?E.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Ch({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Ch(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"?E.green:a==="error"?E.red:E.cyan,l=r.totalTokens!=null?E.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?E.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${E.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${E.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(` ${E.dim("run finished:")} ${c.status}`),console.log(E.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(E.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}He.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}Kd(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(E.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(E.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(E.yellow(` no traces for "${e}"`)),console.log(E.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(E.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Kd(i)});function Kd(e){let o=e.status||"ok",t=o==="ok"?E.green:o==="error"?E.red:E.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))} ${E.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${E.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${E.dim("model:")} ${i}`),console.log(` ${E.dim("tokens:")} ${n} ${E.dim("duration:")} ${s}`),e.error&&console.log(` ${E.dim("error:")} ${E.red(String(e.error).slice(0,300))}`),console.log()}He.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 Kt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});He.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 Kt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});He.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 Kt({nodeId:t}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});import{Command as Xd}from"commander";import se from"chalk";import rt from"prompts";import{readFileSync as Nh,existsSync as Rh}from"fs";import{resolve as _h}from"path";var xn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],er=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Qd={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 Zd(){let e=_h(process.cwd(),"agentx.json");if(!Rh(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Nh(e,"utf-8"))}function Dh(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?se.yellow("\u26A0 no signing secret"):se.green("\u2713 active"):se.dim("disabled")}function Ph(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=er.has(e.source)?se.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${se.cyan(e.id)} ${Dh(e)}`),console.log(` ${se.dim(e.source)} \u2192 ${se.bold(e.agentId)}${n}`),console.log(` POST ${se.dim(t)}`),e.secretEnv&&console.log(` secret: ${se.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${se.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${se.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${se.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var $o=new Xd().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");$o.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Zd(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(se.dim(`
517
+ `)}`)}var He=new Wh().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");He.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Ho().list();if(!o.length){console.log(E.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"?E.green("dispatch: active"):E.yellow(`dispatch: ${t.state}`);console.log(` ${E.cyan(t.id)} ${E.bold(t.title)} ${E.dim(`v${t.version} \xB7`)} ${r} ${E.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${i?` ${E.dim(i)}`:""}`),console.log(` ${E.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});He.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 Ho().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Kr(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});He.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=Mt(process.cwd(),e);sr(i)||(console.log(E.red(` file not found: ${i}`)),process.exit(1));try{let r=ir(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?mt(r,{filePath:e}):JSON.parse(r),l=gt.safeParse(c);if(!l.success){console.log(E.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=_n(l.data);if(g.length){console.log(E.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(E.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof Dn?r.message:`parse error: ${r?.message??r}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let t=new Ho().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(E.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(E.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(E.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});He.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Sn.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");Sn.some(a=>a.name===t)||(console.log(E.red(` unknown template "${o.template}"`)),console.log(E.dim(` available: ${Sn.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(E.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Ho;!o.force&&n.get(e)&&(console.log(E.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=sg(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=mt(s,{filePath:`${e}.yaml`}),c=gt.safeParse(a);if(!c.success){console.log(E.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(E.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=Mt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=mt(s,{filePath:`${e}.yaml`}),c=gt.parse(a);js(r,JSON.stringify(c,null,2)+`
518
+ `)}else js(r,s);console.log(),console.log(E.green(` \u2713 scaffolded ${r}`)),console.log(E.dim(` template: ${t}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${r}`)),console.log(E.dim(` 2. agentx workflow validate ${r}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});He.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Sn)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});He.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=Mt(process.cwd(),e);sr(t)||(console.log(E.red(` file not found: ${t}`)),process.exit(1));let n=ir(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?mt(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof Dn?u.message:`parse error: ${u?.message??u}`;console.log(E.red(` ${f}`)),process.exit(1)}let r=gt.safeParse(i);if(!r.success){console.log(E.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=_n(r.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Ho,l=s?Bh(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Mt(c.baseDir,`${r.data.id}.${l}`);if(js(g,s?n:JSON.stringify(r.data,null,2)+`
519
+ `),console.log(E.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(E.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(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});He.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 Qt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(E.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"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(r)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${E.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});He.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(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Mt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&sr(s)){let c=ir(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?mt(c,{filePath:e}):JSON.parse(c)}catch(b){let v=b instanceof Dn?b.message:`parse error: ${b?.message??b}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=gt.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=_n(d.data);if(u.length){console.log(E.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Ho,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=Mt(f.baseDir,`${p}.${w}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
520
+ `;js(y,k),n=p,console.log(E.dim(` ad-hoc registered as "${p}" \u2192 ${y}`));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(E.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(E.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?E.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Jh({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Jh(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"?E.green:a==="error"?E.red:E.cyan,l=r.totalTokens!=null?E.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?E.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${E.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${E.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(` ${E.dim("run finished:")} ${c.status}`),console.log(E.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(E.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}He.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}ig(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(E.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(E.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(E.yellow(` no traces for "${e}"`)),console.log(E.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(E.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)ig(i)});function ig(e){let o=e.status||"ok",t=o==="ok"?E.green:o==="error"?E.red:E.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))} ${E.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${E.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${E.dim("model:")} ${i}`),console.log(` ${E.dim("tokens:")} ${n} ${E.dim("duration:")} ${s}`),e.error&&console.log(` ${E.dim("error:")} ${E.red(String(e.error).slice(0,300))}`),console.log()}He.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 Qt({nodeId:t}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});He.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 Qt({nodeId:t}).setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});He.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 Qt({nodeId:t}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});import{Command as rg}from"commander";import se from"chalk";import rt from"prompts";import{readFileSync as Hh,existsSync as Gh}from"fs";import{resolve as zh}from"path";var En=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],rr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),ag={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 cg(){let e=zh(process.cwd(),"agentx.json");if(!Gh(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Hh(e,"utf-8"))}function Yh(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?se.yellow("\u26A0 no signing secret"):se.green("\u2713 active"):se.dim("disabled")}function Vh(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=rr.has(e.source)?se.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${se.cyan(e.id)} ${Yh(e)}`),console.log(` ${se.dim(e.source)} \u2192 ${se.bold(e.agentId)}${n}`),console.log(` POST ${se.dim(t)}`),e.secretEnv&&console.log(` secret: ${se.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${se.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${se.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${se.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var $o=new rg().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");$o.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=cg(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(se.dim(`
521
521
  No webhooks registered. Add one with: agentx webhook add
522
- `));return}console.log();for(let n of t)Ph(n)});$o.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${xn.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=Zd(),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 rt({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 rt({type:"select",name:"source",message:"Source",choices:xn.map(p=>({title:`${p}${er.has(p)?" \u2713 wired":""}`,value:p,description:Qd[p]}))})).source),!xn.includes(a))throw new Error(`Source must be one of: ${xn.join(", ")}`);if(!c&&d&&(i?c=((await rt({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await rt({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 rt({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await rt({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ye(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.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(se.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(se.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(se.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});$o.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await rt({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await ye(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(se.green(`\u2713 removed webhook "${e}"`))});function eg(e){return async o=>{let t=await ye(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(se.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}$o.command("enable <id>").description("enable a webhook entry").action(eg(!0));$o.command("disable <id>").description("disable a webhook entry").action(eg(!1));var As=new Xd().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");As.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await ye(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(se.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});As.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await ye(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(se.green(`\u2713 removed trigger ${o} from "${e}"`))});As.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 ye(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(se.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});$o.addCommand(As);$o.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=xn.map(t=>({source:t,wired:er.has(t),hint:Qd[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?se.green("\u2713 wired"):se.dim("inbound-only");console.log(` ${se.cyan(t.source.padEnd(8))} ${n} ${se.dim(t.hint)}`)}console.log(),console.log(se.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(se.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Mh}from"commander";import ie from"chalk";ae();function Lt(e){let{summary:o,backupPath:t}=ao(n=>e(n));console.log(ie.green(`
522
+ `));return}console.log();for(let n of t)Vh(n)});$o.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${En.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=cg(),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 rt({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 rt({type:"select",name:"source",message:"Source",choices:En.map(p=>({title:`${p}${rr.has(p)?" \u2713 wired":""}`,value:p,description:ag[p]}))})).source),!En.includes(a))throw new Error(`Source must be one of: ${En.join(", ")}`);if(!c&&d&&(i?c=((await rt({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await rt({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 rt({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await rt({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ye(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(w=>w.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(se.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(se.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(se.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});$o.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await rt({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await ye(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(se.green(`\u2713 removed webhook "${e}"`))});function lg(e){return async o=>{let t=await ye(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(se.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}$o.command("enable <id>").description("enable a webhook entry").action(lg(!0));$o.command("disable <id>").description("disable a webhook entry").action(lg(!1));var Is=new rg().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Is.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await ye(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(se.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});Is.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await ye(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(se.green(`\u2713 removed trigger ${o} from "${e}"`))});Is.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 ye(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(se.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});$o.addCommand(Is);$o.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=En.map(t=>({source:t,wired:rr.has(t),hint:ag[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?se.green("\u2713 wired"):se.dim("inbound-only");console.log(` ${se.cyan(t.source.padEnd(8))} ${n} ${se.dim(t.hint)}`)}console.log(),console.log(se.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(se.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Kh}from"commander";import ie from"chalk";ae();function Lt(e){let{summary:o,backupPath:t}=ao(n=>e(n));console.log(ie.green(`
523
523
  \u2713 ${o}`)),t&&console.log(ie.dim(` Backup: ${t}`)),console.log(ie.dim(` Restart the daemon (or POST /reload) for the change to take effect.
524
- `))}function Ts(){try{return j().business||{}}catch{return{}}}var Ft=new Mh().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");Ft.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=Ts();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(ie.yellow(" business block not enabled (or missing).")),console.log(ie.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(ie.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(ie.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?ie.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?ie.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${ie.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(ie.bold(` Projects (${n.length})`)),n.length===0)console.log(ie.dim(" (empty)"));else for(let r of n){let a=r.pm?ie.dim(` \xB7 pm=${r.pm}`):"",c=r.client?ie.dim(` \xB7 client=${r.client}`):"";console.log(` ${ie.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(ie.bold(` Contact map (${s.length})`)),s.length===0)console.log(ie.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(` ${ie.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?ie.dim(` (${r.displayName})`):""}`)}console.log()});var or=Ft.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");or.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=Ts(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(ie.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${ie.cyan(n)} ${s.role}${s.reportsTo?ie.dim(` \u2192 ${s.reportsTo}`):""}`)});or.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);Lt(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}`:""})`))});or.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{Lt(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 tr=Ft.command("project").description("manage business.projects \u2014 id, pm, client");tr.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=Ts().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ie.dim(" no projects"));return}for(let n of t)console.log(` ${ie.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});tr.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)=>{Lt(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`})});tr.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{Lt(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 nr=Ft.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");nr.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=Ts().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ie.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+"/":""}${ie.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});nr.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(ie.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),Lt(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`})});nr.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=>{Lt(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 Lh}from"commander";import Me from"chalk";ae();var Fh={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function sr(e){let o=Fh[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Os(){let o=j().business?.standup?.plansDir||".agentx/plans";return new fc(o)}var Ut=new Lh().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Ut.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=sr(e),n=Os(),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(`
525
- `):(console.error(Me.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Me.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=ni(s);if(r.length){console.log(Me.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Me.dim(` \u2022 ${a}`))}});Ut.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Os();if(e){let n=sr(e),s=o.read(n);if(!s){console.log(Me.dim(` No ${n} plan set.`));return}og(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Me.yellow(" No plan set at any tier.")),console.log(Me.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Me.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}og(t.tier,t.date,t.content)});Ut.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Os().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Me.dim(" No plans yet."));return}for(let n of t)console.log(` ${Me.cyan(n.tier.padEnd(5))} ${Me.bold(n.date.padEnd(11))} ${Me.dim(n.path)}`)});Ut.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=sr(e),n=Os().read(o);if(!n){console.log(Me.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Me.green(` \u2713 ${o} plan cleared (${n.path})`))});function og(e,o,t){console.log(Me.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
526
- `))console.log(` ${s}`);console.log();let n=ni(t);n.length&&console.log(Me.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Uh}from"commander";import Y from"chalk";ae();function qh(){try{return j().notifications||{}}catch{return{}}}function Wh(){try{return j().channels?.ntfy}catch{return}}function Bh(){try{return j().channels?.push}catch{return}}function qt(e){let{summary:o,backupPath:t}=ao(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Y.green(`
524
+ `))}function Cs(){try{return I().business||{}}catch{return{}}}var Ft=new Kh().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");Ft.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=Cs();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(ie.yellow(" business block not enabled (or missing).")),console.log(ie.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(ie.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(ie.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?ie.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?ie.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${ie.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(ie.bold(` Projects (${n.length})`)),n.length===0)console.log(ie.dim(" (empty)"));else for(let r of n){let a=r.pm?ie.dim(` \xB7 pm=${r.pm}`):"",c=r.client?ie.dim(` \xB7 client=${r.client}`):"";console.log(` ${ie.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(ie.bold(` Contact map (${s.length})`)),s.length===0)console.log(ie.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(` ${ie.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?ie.dim(` (${r.displayName})`):""}`)}console.log()});var ar=Ft.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");ar.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=Cs(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(ie.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${ie.cyan(n)} ${s.role}${s.reportsTo?ie.dim(` \u2192 ${s.reportsTo}`):""}`)});ar.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);Lt(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}`:""})`))});ar.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{Lt(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 cr=Ft.command("project").description("manage business.projects \u2014 id, pm, client");cr.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=Cs().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ie.dim(" no projects"));return}for(let n of t)console.log(` ${ie.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});cr.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)=>{Lt(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`})});cr.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{Lt(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 lr=Ft.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");lr.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=Cs().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ie.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+"/":""}${ie.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});lr.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(ie.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),Lt(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`})});lr.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=>{Lt(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 Xh}from"commander";import Me from"chalk";ae();var Qh={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function dr(e){let o=Qh[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Rs(){let o=I().business?.standup?.plansDir||".agentx/plans";return new Sc(o)}var Ut=new Xh().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Ut.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=dr(e),n=Rs(),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(`
525
+ `):(console.error(Me.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Me.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=li(s);if(r.length){console.log(Me.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Me.dim(` \u2022 ${a}`))}});Ut.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Rs();if(e){let n=dr(e),s=o.read(n);if(!s){console.log(Me.dim(` No ${n} plan set.`));return}dg(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Me.yellow(" No plan set at any tier.")),console.log(Me.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Me.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}dg(t.tier,t.date,t.content)});Ut.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Rs().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Me.dim(" No plans yet."));return}for(let n of t)console.log(` ${Me.cyan(n.tier.padEnd(5))} ${Me.bold(n.date.padEnd(11))} ${Me.dim(n.path)}`)});Ut.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=dr(e),n=Rs().read(o);if(!n){console.log(Me.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Me.green(` \u2713 ${o} plan cleared (${n.path})`))});function dg(e,o,t){console.log(Me.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
526
+ `))console.log(` ${s}`);console.log();let n=li(t);n.length&&console.log(Me.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Zh}from"commander";import Y from"chalk";ae();function ey(){try{return I().notifications||{}}catch{return{}}}function oy(){try{return I().channels?.ntfy}catch{return}}function ty(){try{return I().channels?.push}catch{return}}function qt(e){let{summary:o,backupPath:t}=ao(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Y.green(`
527
527
  \u2713 ${o}`)),t&&console.log(Y.dim(` Backup: ${t}`)),console.log(Y.dim(` Restart the daemon (or POST /reload) for the change to take effect.
528
- `))}var po=new Uh().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");po.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=qh();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let c=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Y.cyan(o.destination.channel+":"+o.destination.chatId)}${Y.dim(c)}`)}else console.log(` destination ${Y.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Y.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Y.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Y.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Y.dim("off")}`);let n=Pn(o.local);if(console.log(` local.banner ${n.banner?"on":Y.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:Y.dim("off")}`),console.log(` local.icon ${n.icon??Y.dim("AgentX logo")}`),n.banner){let c=await xc();c.state!=="unsupported"&&(console.log(` local.helper ${c.state==="ready"?c.message:Y.yellow(c.message)}`),c.fix&&console.log(` ${Y.dim("Fix: "+c.fix)}`))}let s;try{s=j()}catch{s=void 0}console.log(` channel ${Mn(s)} ${Y.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=Ys(Bh()),r=i.role==="relay"?`relays to ${i.relayTo}`:`this node sends \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing (agentx app push-keys)"}`;console.log(` push ${i.enabled?"on":Y.dim("off")} ${Y.dim(r)}`);let a=ii(Wh());console.log(` ntfy ${a.enabled?"on":Y.dim("off")} ${Y.dim(`${a.server} \xB7 topic ${a.topicSet?"set":"unset"} \xB7 token ${a.tokenSet?"set":"unset"}`)}`),console.log()});po.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){qt(o=>(delete o.destination,"notifications destination cleared"));return}qt(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})`:""}`))});po.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(Y.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(Y.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";qt(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});po.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(Y.red(" threshold must be a non-negative integer")),process.exit(1)),qt(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});po.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(Y.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{qt(n=>(n.local=Oa(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(Y.dim(` Run agentx desktop install to put the new icon on the helper.
529
- `))}catch(n){console.log(Y.red(` ${n?.message??n}`)),process.exit(1)}});po.command("channel <name>").description("channel agentx notify uses when --channel is not given: push, ntfy, telegram\u2026 (unset: push when it is on, else ntfy)").action(e=>{let o=e.trim();/^[\w-]+$/.test(o)||(console.log(Y.red(` not a channel name: ${e}`)),process.exit(1)),qt(t=>(t.channel=o,`notifications.channel = ${o}`))});po.command("push").description("set up notifications on the phone app: on/off, contact, or relay to the node that hosts the app").option("--subject <contact>","contact for the push services: mailto:you@example.com or an https:// URL").option("--relay-to <peer>",'mesh peer that hosts the phone app (on every other node); "" makes this node the host').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.subject!==void 0&&(o.subject=e.subject),e.relayTo!==void 0&&(o.relayTo=e.relayTo),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=ao(s=>{s.channels=s.channels||{},s.channels.push=Da(s.channels.push,o);let i=Ys(s.channels.push);return`channels.push ${i.enabled?"on":"off"} \xB7 ${i.role==="relay"?`relays to ${i.relayTo}`:`host \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing"}`}`});console.log(Y.green(`
528
+ `))}var po=new Zh().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");po.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=ey();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let c=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Y.cyan(o.destination.channel+":"+o.destination.chatId)}${Y.dim(c)}`)}else console.log(` destination ${Y.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Y.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Y.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Y.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Y.dim("off")}`);let n=Un(o.local);if(console.log(` local.banner ${n.banner?"on":Y.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:Y.dim("off")}`),console.log(` local.icon ${n.icon??Y.dim("AgentX logo")}`),n.banner){let c=await Rc();c.state!=="unsupported"&&(console.log(` local.helper ${c.state==="ready"?c.message:Y.yellow(c.message)}`),c.fix&&console.log(` ${Y.dim("Fix: "+c.fix)}`))}let s;try{s=I()}catch{s=void 0}console.log(` channel ${qn(s)} ${Y.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=ei(ty()),r=i.role==="relay"?`relays to ${i.relayTo}`:`this node sends \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing (agentx app push-keys)"}`;console.log(` push ${i.enabled?"on":Y.dim("off")} ${Y.dim(r)}`);let a=gi(oy());console.log(` ntfy ${a.enabled?"on":Y.dim("off")} ${Y.dim(`${a.server} \xB7 topic ${a.topicSet?"set":"unset"} \xB7 token ${a.tokenSet?"set":"unset"}`)}`),console.log()});po.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){qt(o=>(delete o.destination,"notifications destination cleared"));return}qt(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})`:""}`))});po.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(Y.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(Y.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";qt(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});po.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(Y.red(" threshold must be a non-negative integer")),process.exit(1)),qt(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});po.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(Y.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{qt(n=>(n.local=Ma(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(Y.dim(` Run agentx desktop install to put the new icon on the helper.
529
+ `))}catch(n){console.log(Y.red(` ${n?.message??n}`)),process.exit(1)}});po.command("channel <name>").description("channel agentx notify uses when --channel is not given: push, ntfy, telegram\u2026 (unset: push when it is on, else ntfy)").action(e=>{let o=e.trim();/^[\w-]+$/.test(o)||(console.log(Y.red(` not a channel name: ${e}`)),process.exit(1)),qt(t=>(t.channel=o,`notifications.channel = ${o}`))});po.command("push").description("set up notifications on the phone app: on/off, contact, or relay to the node that hosts the app").option("--subject <contact>","contact for the push services: mailto:you@example.com or an https:// URL").option("--relay-to <peer>",'mesh peer that hosts the phone app (on every other node); "" makes this node the host').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.subject!==void 0&&(o.subject=e.subject),e.relayTo!==void 0&&(o.relayTo=e.relayTo),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=ao(s=>{s.channels=s.channels||{},s.channels.push=Ja(s.channels.push,o);let i=ei(s.channels.push);return`channels.push ${i.enabled?"on":"off"} \xB7 ${i.role==="relay"?`relays to ${i.relayTo}`:`host \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing"}`}`});console.log(Y.green(`
530
530
  \u2713 ${t}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
531
- `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});po.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=ao(s=>{s.channels=s.channels||{},s.channels.ntfy=jc(s.channels.ntfy,o);let i=ii(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(Y.green(`
531
+ `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});po.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=ao(s=>{s.channels=s.channels||{},s.channels.ntfy=Fc(s.channels.ntfy,o);let i=gi(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(Y.green(`
532
532
  \u2713 ${t}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
533
- `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as Jh}from"commander";import Fo from"chalk";import{readdirSync as ir,statSync as tg,unlinkSync as Hh,rmSync as Gh,existsSync as ng}from"fs";import{resolve as sg,join as ig}from"path";var rg=[{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 rr(e,o){if(!ng(e))return[];let t=[];for(let n of ir(e,{withFileTypes:!0})){let s=ig(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...rr(s,!0))}return t}var js=new Jh().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");js.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of rg){let t=sg(process.cwd(),o.dir),n=rr(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=tg(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(` ${Fo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Is(s).padStart(10)} oldest=${r}`)}console.log(Fo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Is(e).padStart(10)} total`)),console.log(),console.log(Fo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});js.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(Fo.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(Fo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Fo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of rg){if(n&&r.dir!==n)continue;let a=sg(process.cwd(),r.dir),c=rr(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=tg(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{Hh(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{ag(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Fo.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${Is(g)})`),s+=l,i+=g}console.log(),console.log(Fo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Is(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function ag(e){if(ng(e))for(let o of ir(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=ig(e,o.name);ag(t);try{ir(t).length===0&&Gh(t,{recursive:!1})}catch{}}}function Is(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 zh}from"commander";import U from"chalk";var Uo=new zh().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Uo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new pt().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()});Uo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new pt().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()});Uo.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=Yh(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=qr.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 pt().save(s.data);console.log(U.green(`
533
+ `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as ny}from"commander";import Fo from"chalk";import{readdirSync as gr,statSync as gg,unlinkSync as sy,rmSync as iy,existsSync as mg}from"fs";import{resolve as pg,join as ug}from"path";var fg=[{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 mr(e,o){if(!mg(e))return[];let t=[];for(let n of gr(e,{withFileTypes:!0})){let s=ug(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...mr(s,!0))}return t}var _s=new ny().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");_s.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of fg){let t=pg(process.cwd(),o.dir),n=mr(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=gg(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(` ${Fo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Ns(s).padStart(10)} oldest=${r}`)}console.log(Fo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Ns(e).padStart(10)} total`)),console.log(),console.log(Fo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});_s.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(Fo.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(Fo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Fo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of fg){if(n&&r.dir!==n)continue;let a=pg(process.cwd(),r.dir),c=mr(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=gg(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{sy(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{hg(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Fo.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${Ns(g)})`),s+=l,i+=g}console.log(),console.log(Fo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Ns(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function hg(e){if(mg(e))for(let o of gr(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=ug(e,o.name);hg(t);try{gr(t).length===0&&iy(t,{recursive:!1})}catch{}}}function Ns(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 ry}from"commander";import U from"chalk";var Uo=new ry().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Uo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new pt().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()});Uo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new pt().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()});Uo.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=ay(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=Xr.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 pt().save(s.data);console.log(U.green(`
534
534
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
535
- `))});Uo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new pt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Uo.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 pt().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 Wr(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)}});Uo.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 Yh(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}ae();import{Command as Vh}from"commander";import ee from"chalk";var cg=new Vh().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=j(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(ee.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(ee.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(ee.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let u;for(;(u=l.indexOf(`
535
+ `))});Uo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new pt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Uo.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 pt().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 Qr(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)}});Uo.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 ay(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}ae();import{Command as cy}from"commander";import ee from"chalk";var yg=new cy().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=I(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(ee.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(ee.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(ee.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:g,value:d}=await a.read();if(g)break;l+=c.decode(d,{stream:!0});let u;for(;(u=l.indexOf(`
536
536
 
537
- `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),Kh(f)}}}catch(r){console.error(ee.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Kh(e){let o="message",t="";for(let i of e.split(`
538
- `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ee.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ee.cyan(n.phase?.padEnd(9)??"run"),r=ee.bold(n.workflowId??""),a=ee.dim((n.runId??"").slice(0,8)),c=n.nodeId?ee.yellow(n.nodeId):"",l=n.note?ee.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ee.magenta(`task.${n.phase}`.padEnd(14)),r=ee.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ee.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ee.cyan(a)} ${c}`);break}case"signal":{let i=ee.green("signal".padEnd(9)),r=ee.bold(n.name),a=ee.dim(`(${n.scope})`),c=n.workflowId?ee.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ee.blue("mesh".padEnd(9)),r=ee.bold(n.peer),a=n.healthy?ee.green("\u2713 healthy"):ee.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ee.dim(n.delta??"")}`);break}case"channel":{let i=ee.yellow("channel".padEnd(9)),r=n.direction==="in"?ee.cyan("\u2190"):ee.magenta("\u2192"),a=ee.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ee.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ee.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}ae();import{Command as Xh}from"commander";import Wt from"chalk";function Qh(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 lg=new Xh().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let a=j(e.config);o||(o=a.dashboard?.daemonUrl||""),t||(t=a.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n={};t&&(n.Authorization=`Bearer ${t}`);let s;try{let a=await fetch(Qh(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(Wt.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(Wt.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(Wt.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(Wt.dim(" no events"));return}for(let a of i)console.log(` ${Lr(a)} ${Wt.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(Wt.dim(`
539
- ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as ey}from"commander";import Cs from"chalk";import{spawn as oy}from"node:child_process";import{execFileSync as Zh}from"node:child_process";function dg(e=()=>Zh("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 gg=new ey().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(Cs.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-YIBETZDJ.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:dg();if(n?.ok){let{fetchAgents:l}=await import("./client-YIBETZDJ.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.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(Cs.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=oy("opencode",["--standalone"],{stdio:"inherit",env:p});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Cs.yellow(n.reason)),console.error(Cs.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-B6WGWI3A.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 ty}from"commander";import K from"chalk";import{randomUUID as ug}from"crypto";import{createInterface as ny}from"node:readline/promises";import sy from"ora";import Ns from"chalk";function mg(e){console.error(),console.error(Ns.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Ns.dim(` ${e.why}`)),console.error(),console.error(` Use ${Ns.cyan(e.instead)} instead.`),e.note&&console.error(Ns.dim(` ${e.note}`)),console.error()}var pg={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 fg=new ty().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)=>{mg({what:"agentx chat",...pg});let t=Nc({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${ug().slice(0,12)}`,r=[];try{r=await Hn(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-BHRANF7Z.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}ry(t.baseUrl,n,i,s);let a=ny({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
540
- bye`)),process.exit(0)});;){let g;try{g=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${ug().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Hn(t);for(let w of p){let y=w.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await Hn(t)).find(y=>y.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=sy({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=iy(n);try{let p=await Rc(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(w,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function iy(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
537
+ `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),ly(f)}}}catch(r){console.error(ee.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function ly(e){let o="message",t="";for(let i of e.split(`
538
+ `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ee.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ee.cyan(n.phase?.padEnd(9)??"run"),r=ee.bold(n.workflowId??""),a=ee.dim((n.runId??"").slice(0,8)),c=n.nodeId?ee.yellow(n.nodeId):"",l=n.note?ee.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ee.magenta(`task.${n.phase}`.padEnd(14)),r=ee.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ee.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ee.cyan(a)} ${c}`);break}case"signal":{let i=ee.green("signal".padEnd(9)),r=ee.bold(n.name),a=ee.dim(`(${n.scope})`),c=n.workflowId?ee.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ee.blue("mesh".padEnd(9)),r=ee.bold(n.peer),a=n.healthy?ee.green("\u2713 healthy"):ee.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ee.dim(n.delta??"")}`);break}case"channel":{let i=ee.yellow("channel".padEnd(9)),r=n.direction==="in"?ee.cyan("\u2190"):ee.magenta("\u2192"),a=ee.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ee.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ee.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}ae();import{Command as dy}from"commander";import Wt from"chalk";function gy(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 wg=new dy().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=I(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(gy(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(Wt.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(Wt.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(Wt.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(Wt.dim(" no events"));return}for(let a of i)console.log(` ${Yr(a)} ${Wt.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(Wt.dim(`
539
+ ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as py}from"commander";import Ds from"chalk";import{spawn as uy}from"node:child_process";import{execFileSync as my}from"node:child_process";function bg(e=()=>my("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 $g=new py().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(Ds.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-SWODYWKD.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:bg();if(n?.ok){let{fetchAgents:l}=await import("./client-SWODYWKD.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(y=>y.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(y=>[y.id,{name:`AgentX ${y.name||y.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(Ds.dim(`Opening ${n.version} with AgentX model ${d}.`));let w=uy("opencode",["--standalone"],{stdio:"inherit",env:p});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Ds.yellow(n.reason)),console.error(Ds.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-MMWB4O72.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 fy}from"commander";import K from"chalk";import{randomUUID as xg}from"crypto";import{createInterface as hy}from"node:readline/promises";import yy from"ora";import Ps from"chalk";function kg(e){console.error(),console.error(Ps.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Ps.dim(` ${e.why}`)),console.error(),console.error(` Use ${Ps.cyan(e.instead)} instead.`),e.note&&console.error(Ps.dim(` ${e.note}`)),console.error()}var vg={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 Sg=new fy().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)=>{kg({what:"agentx chat",...vg});let t=qc({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${xg().slice(0,12)}`,r=[];try{r=await Vn(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-VCHZLQ57.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}by(t.baseUrl,n,i,s);let a=hy({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
540
+ bye`)),process.exit(0)});;){let g;try{g=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${xg().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Vn(t);for(let w of p){let y=w.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await Vn(t)).find(y=>y.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=yy({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=wy(n);try{let p=await Wc(t,n,g,{channel:s,chatId:i,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let w=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(w,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function wy(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
541
541
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
542
542
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
543
543
  `&&(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(`
@@ -552,17 +552,17 @@ agentx wiki questions`,me=I?.daemon?.port??I?.port??18800;try{let J=await fetch(
552
552
  `))},finishError(r){o&&!t&&process.stdout.write(`
553
553
  `),process.stdout.write(K.red(` \u2717 ${r}
554
554
 
555
- `))}}}function ry(e,o,t,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(K.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as ay}from"commander";import re from"chalk";import{readFileSync as cy}from"fs";import{existsSync as ly,readdirSync as dy}from"fs";import{resolve as gy}from"path";var Rs=["user","feedback","project","reference"],qo=new ay().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");qo.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(!Rs.includes(e.type)){console.error(re.red(` --type must be one of: ${Rs.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await my();else try{o=cy(e.file,"utf-8")}catch(s){console.error(re.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(re.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new dt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(re.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});qo.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 dt().list(e.agent);if(e.type){if(!Rs.includes(e.type)){console.error(re.red(` --type must be one of: ${Rs.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(re.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(re.bold(` ${s.type}`)),n=s.type),console.log(` ${re.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(re.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});qo.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 dt().get(o.agent,e);if(!n){console.error(re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(re.bold(`${n.type}/${n.name}`)+re.dim(` (${n.description})`)),console.log(re.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});qo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new dt().remove(o.agent,e)){console.error(re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(re.green(` \u2713 memory "${e}" removed`))});qo.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 dt().indexMarkdown(e.agent);if(!t){console.log(re.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var _s=qo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function ar(e){if(e)return[e];let o=gy(process.cwd(),".agentx/memory");return ly(o)?dy(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}_s.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 Vt;for(let t of ar(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${re.bold(t)} ${n||re.dim("(none)")}`)}});_s.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Vt,t=0;for(let n of ar(e.agent))for(let s of o.held(n))t++,console.log(` ${re.bold(n)} ${re.cyan(s.id)} ${re.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(re.dim(" nothing held"))});for(let e of["approve","reject"])_s.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 Vt().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(re.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(re.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});_s.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 Vt,t=0;for(let n of ar(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${re.bold(n)} ${s}`),t+=s}console.log(e.apply?re.green(` \u2713 deleted ${t} fact(s) containing credentials`):re.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});async function my(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}_g();import cr from"chalk";import{Command as py}from"commander";import{resolve as uy}from"path";var hg=new py().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(uy(e.cwd)),e.stdio!==!1?await ia():(uo.error("Only stdio transport is currently supported."),uo.info(`Usage: ${cr.green("agentx serve --stdio")} or configure in your MCP client.`),uo.break(),uo.info("Add to Claude Code:"),uo.info(cr.dim(" claude mcp add agentx -- npx agentx serve --stdio")),uo.break(),uo.info("Add to Cursor/MCP config:"),uo.info(cr.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){wc(o)}});import{Command as fy}from"commander";import de from"chalk";import{spawn as lr}from"child_process";import{mkdirSync as hy,writeFileSync as Ms,readFileSync as yy,readdirSync as wy,rmSync as wg,openSync as bg,existsSync as Ds}from"fs";import{resolve as by,join as Le}from"path";import{randomBytes as $y}from"crypto";var yg={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"}]};var $g="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",ky="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function vy(e,o){return[{dir:Le(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(yg,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:Le(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:Le(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 xy(e,o,t){let n=Le(e.dir,"workspaces",e.agentId);hy(n,{recursive:!0}),Ms(Le(n,"CLAUDE.md"),`# ${e.agentName}
555
+ `))}}}function by(e,o,t,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(K.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as $y}from"commander";import re from"chalk";import{readFileSync as ky}from"fs";import{existsSync as vy,readdirSync as xy}from"fs";import{resolve as Sy}from"path";var Ms=["user","feedback","project","reference"],qo=new $y().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");qo.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(!Ms.includes(e.type)){console.error(re.red(` --type must be one of: ${Ms.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Ey();else try{o=ky(e.file,"utf-8")}catch(s){console.error(re.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(re.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new dt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(re.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});qo.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 dt().list(e.agent);if(e.type){if(!Ms.includes(e.type)){console.error(re.red(` --type must be one of: ${Ms.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(re.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(re.bold(` ${s.type}`)),n=s.type),console.log(` ${re.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(re.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});qo.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 dt().get(o.agent,e);if(!n){console.error(re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(re.bold(`${n.type}/${n.name}`)+re.dim(` (${n.description})`)),console.log(re.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});qo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new dt().remove(o.agent,e)){console.error(re.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(re.green(` \u2713 memory "${e}" removed`))});qo.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 dt().indexMarkdown(e.agent);if(!t){console.log(re.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var Ls=qo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function pr(e){if(e)return[e];let o=Sy(process.cwd(),".agentx/memory");return vy(o)?xy(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}Ls.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 Xt;for(let t of pr(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${re.bold(t)} ${n||re.dim("(none)")}`)}});Ls.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new Xt,t=0;for(let n of pr(e.agent))for(let s of o.held(n))t++,console.log(` ${re.bold(n)} ${re.cyan(s.id)} ${re.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(re.dim(" nothing held"))});for(let e of["approve","reject"])Ls.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 Xt().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(re.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(re.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});Ls.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 Xt,t=0;for(let n of pr(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${re.bold(n)} ${s}`),t+=s}console.log(e.apply?re.green(` \u2713 deleted ${t} fact(s) containing credentials`):re.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});async function Ey(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}zg();import ur from"chalk";import{Command as Ay}from"commander";import{resolve as Ty}from"path";var Eg=new Ay().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(Ty(e.cwd)),e.stdio!==!1?await fa():(uo.error("Only stdio transport is currently supported."),uo.info(`Usage: ${ur.green("agentx serve --stdio")} or configure in your MCP client.`),uo.break(),uo.info("Add to Claude Code:"),uo.info(ur.dim(" claude mcp add agentx -- npx agentx serve --stdio")),uo.break(),uo.info("Add to Cursor/MCP config:"),uo.info(ur.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Tc(o)}});import{Command as Oy}from"commander";import de from"chalk";import{spawn as fr}from"child_process";import{mkdirSync as jy,writeFileSync as qs,readFileSync as Iy,readdirSync as Cy,rmSync as Tg,openSync as Og,existsSync as Fs}from"fs";import{resolve as Ry,join as Le}from"path";import{randomBytes as Ny}from"crypto";var Ag={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"}]};var jg="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",_y="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Dy(e,o){return[{dir:Le(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(Ag,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:Le(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:Le(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 Py(e,o,t){let n=Le(e.dir,"workspaces",e.agentId);jy(n,{recursive:!0}),qs(Le(n,"CLAUDE.md"),`# ${e.agentName}
556
556
 
557
557
  ${e.persona}
558
- `),Ms(Le(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}};Ms(Le(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function dr(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function gr(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 Ps(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
558
+ `),qs(Le(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}};qs(Le(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function hr(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function yr(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 Us(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
559
559
  `).join(`
560
- `)}`)}var kg=new fy().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").action(async e=>{let o=parseInt(e.basePort,10),t=by(process.cwd(),".agentx-demo"),n=vy(t,o),s=Le(t,"mesh-token"),i=!!e.reuse&&Ds(s)&&Ds(Le(n[0].dir,"agentx.json")),r=i?yy(s,"utf8").trim():$y(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Ds(l))&&(console.error(de.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Ds(t))for(let f of wy(t))wg(Le(t,f),{recursive:!0,force:!0});for(let f of n)xy(f,n,r);Ms(s,r+`
561
- `,{mode:384})}console.log(),console.log(de.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(de.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(de.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=f=>{if(!g){g=!0;for(let p of c)try{p.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{wg(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let u={...process.env};delete u.ANTHROPIC_API_KEY,delete u.ANTHROPIC_API_KEY_OLD,delete u.OPENAI_API_KEY,delete u.DEEPSEEK_API_KEY,u.INTENT_LEDGER_MODE||="shadow";try{for(let y of n){let k=bg(Le(y.dir,"daemon.log"),"a"),b=lr(process.execPath,[l,"daemon","start","-c",Le(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Le(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(de.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Le(y.dir,"daemon.log")})`))}for(let y of n)await dr(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(de.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=bg(Le(n[0].dir,"board.log"),"a"),k=lr(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await dr("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(de.green(" \u2713 dashboard up")),await dr("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(de.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let p=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${de.cyan(p)} (all three nodes via the mesh)`),console.log(de.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{lr(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(de.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Ps("You \u2192 @cx (laptop-paris)",$g,de.cyan);let y=await gr(n[0].port,"/task",{agent:"cx",message:$g});Ps("@cx (laptop-paris)",y.content||"(no content)",de.green),console.log(),console.log(de.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await gr(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:ky}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";Ps("@builder (vps-nyc)",b,de.yellow);let v=await gr(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Ps("@cx (laptop-paris)",v.content||"(no content)",de.green),console.log(),console.log(de.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(de.dim(` Worth your time? A star helps others find it: ${de.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(de.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(de.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(de.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(de.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(de.red(` Demo failed: ${f.message}`)),console.error(de.dim(` Node logs: ${n.map(p=>Le(p.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as Sy}from"commander";import{randomUUID as Ey}from"crypto";import{readFileSync as Ay}from"fs";import{resolve as Ty}from"path";ae();var xg=new Sy().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??Ay(0,"utf8")).trim();t||vg("no task given (pass it as an argument or on stdin)");let n=j(o.config?Ty(o.config):void 0),s=n.agents[o.agent];s||vg(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Rr(o.agent,s,l,i)}let r=new Kr(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${Ey()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
560
+ `)}`)}var Ig=new Oy().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").action(async e=>{let o=parseInt(e.basePort,10),t=Ry(process.cwd(),".agentx-demo"),n=Dy(t,o),s=Le(t,"mesh-token"),i=!!e.reuse&&Fs(s)&&Fs(Le(n[0].dir,"agentx.json")),r=i?Iy(s,"utf8").trim():Ny(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Fs(l))&&(console.error(de.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Fs(t))for(let f of Cy(t))Tg(Le(t,f),{recursive:!0,force:!0});for(let f of n)Py(f,n,r);qs(s,r+`
561
+ `,{mode:384})}console.log(),console.log(de.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(de.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(de.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=f=>{if(!g){g=!0;for(let p of c)try{p.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{Tg(t,{recursive:!0,force:!0})}catch{}process.exit(f)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let u={...process.env};delete u.ANTHROPIC_API_KEY,delete u.ANTHROPIC_API_KEY_OLD,delete u.OPENAI_API_KEY,delete u.DEEPSEEK_API_KEY,u.INTENT_LEDGER_MODE||="shadow";try{for(let y of n){let k=Og(Le(y.dir,"daemon.log"),"a"),b=fr(process.execPath,[l,"daemon","start","-c",Le(y.dir,"agentx.json")],{cwd:y.dir,env:{...u,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Le(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(de.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Le(y.dir,"daemon.log")})`))}for(let y of n)await hr(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(de.green(" \u2713 three daemons up"));let f=n[0].port+10;{let y=Og(Le(n[0].dir,"board.log"),"a"),k=fr(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...u,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await hr("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${f}/live`)).ok,3e4),console.log(de.green(" \u2713 dashboard up")),await hr("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(de.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let p=`http://127.0.0.1:${f}/live`;if(console.log(),console.log(` Dashboard: ${de.cyan(p)} (all three nodes via the mesh)`),console.log(de.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{fr(y,[p],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(de.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Us("You \u2192 @cx (laptop-paris)",jg,de.cyan);let y=await yr(n[0].port,"/task",{agent:"cx",message:jg});Us("@cx (laptop-paris)",y.content||"(no content)",de.green),console.log(),console.log(de.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await yr(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:_y}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";Us("@builder (vps-nyc)",b,de.yellow);let v=await yr(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Us("@cx (laptop-paris)",v.content||"(no content)",de.green),console.log(),console.log(de.dim(` Inspect the run: ${p} \xB7 ledger rows on each node record every dispatch`)),console.log(de.dim(` Worth your time? A star helps others find it: ${de.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(de.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(de.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(de.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(de.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(f){console.error(),console.error(de.red(` Demo failed: ${f.message}`)),console.error(de.dim(` Node logs: ${n.map(p=>Le(p.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as My}from"commander";import{randomUUID as Ly}from"crypto";import{readFileSync as Fy}from"fs";import{resolve as Uy}from"path";ae();var Rg=new My().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??Fy(0,"utf8")).trim();t||Cg("no task given (pass it as an argument or on stdin)");let n=I(o.config?Uy(o.config):void 0),s=n.agents[o.agent];s||Cg(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Br(o.agent,s,l,i)}let r=new ra(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${Ly()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
562
562
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
563
- `),process.exit(c.error?1:0)});function vg(e){console.error(`agentx exec: ${e}`),process.exit(1)}ae();import{Command as Oy}from"commander";import je from"chalk";var Wo=new Oy().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Wo.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 Sn("/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(je.dim(" no chats cached yet"));return}console.log(),console.log(je.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?je.cyan("group"):je.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${je.dim(n.jid.padEnd(40))} ${je.dim(i)}`)}console.log()}catch(o){Bt(o)}});Wo.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 Sn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(je.dim(" no contacts cached yet"));return}console.log(),console.log(je.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} ${je.dim(i)} ${je.dim(n.jid)}`)}console.log()}catch(o){Bt(o)}});Wo.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 pr("/whatsapp/ingest",o);mr(t,!!e.dryRun)}catch(o){Bt(o)}});Wo.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 pr("/whatsapp/ingest",t);mr(n,!!o.dryRun)}catch(t){Bt(t)}});Wo.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 pr("/whatsapp/ingest",t);mr(n,!!o.dryRun)}catch(t){Bt(t)}});Wo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Sn("/whatsapp/state"),o=await Sn("/whatsapp/chats"),t=await Sn("/whatsapp/contacts");console.log(),console.log(je.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){Bt(e)}});function mr(e,o){if(console.log(),console.log(je.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(je.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(je.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(je.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(je.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(je.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Sg(){try{let e=j(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function Sn(e){let o=await fetch(`${Sg()}${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 pr(e,o){let t=await fetch(`${Sg()}${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 Bt(e){console.error(je.red(` ${e.message||e}`)),process.exit(1)}ae();import{Command as Iy}from"commander";import ge from"chalk";import{existsSync as jy,mkdirSync as Eg,writeFileSync as En}from"fs";import{join as Jt,resolve as Cy}from"path";var An=new Iy().name("plugin").description("manage agentx plugins (Move B)");An.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=j().plugins??[];if(console.log(),o.length===0){console.log(ge.dim(" No plugins configured.")),console.log(ge.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ge.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ge.cyan(t)}`);console.log(),console.log(ge.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});An.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(ge.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=Cy(o.cwd,t);jy(n)&&!o.force&&(console.log(ge.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Eg(n,{recursive:!0}),Eg(Jt(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;En(Jt(n,"package.json"),Dy(e,s)),En(Jt(n,"tsconfig.json"),Py()),En(Jt(n,"src/index.ts"),My(e)),En(Jt(n,"README.md"),Ly(e,s)),En(Jt(n,".gitignore"),Fy()),console.log(),console.log(ge.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ge.bold(" Next steps:")),console.log(ge.dim(` cd ${t}`)),console.log(ge.dim(" pnpm install")),console.log(ge.dim(" pnpm build")),console.log(ge.dim(" pnpm link --global # for local testing")),console.log(ge.dim(" # then in your agentx project:")),console.log(ge.dim(` pnpm link --global ${e}`)),console.log(ge.dim(` agentx config set plugins[0] "${e}"`)),console.log(ge.dim(" agentx plugin doctor")),console.log()});An.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=j().plugins??[];if(console.log(),o.length===0){console.log(ge.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Ny(n);s.kind==="ok"?console.log(` ${ge.green("\u2713")} ${ge.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ge.red("\u2717")} ${ge.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ge.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});async function Ny(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Ry(o);if(!_y(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Ua.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 Ry(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 _y(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Dy(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)+`
564
- `}function Py(){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)+`
565
- `}function My(e){return`// ${e} \u2014 AgentX plugin
563
+ `),process.exit(c.error?1:0)});function Cg(e){console.error(`agentx exec: ${e}`),process.exit(1)}ae();import{Command as qy}from"commander";import Ie from"chalk";var Wo=new qy().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Wo.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 An("/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(Ie.dim(" no chats cached yet"));return}console.log(),console.log(Ie.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ie.cyan("group"):Ie.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ie.dim(n.jid.padEnd(40))} ${Ie.dim(i)}`)}console.log()}catch(o){Bt(o)}});Wo.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 An("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ie.dim(" no contacts cached yet"));return}console.log(),console.log(Ie.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} ${Ie.dim(i)} ${Ie.dim(n.jid)}`)}console.log()}catch(o){Bt(o)}});Wo.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 br("/whatsapp/ingest",o);wr(t,!!e.dryRun)}catch(o){Bt(o)}});Wo.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 br("/whatsapp/ingest",t);wr(n,!!o.dryRun)}catch(t){Bt(t)}});Wo.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 br("/whatsapp/ingest",t);wr(n,!!o.dryRun)}catch(t){Bt(t)}});Wo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await An("/whatsapp/state"),o=await An("/whatsapp/chats"),t=await An("/whatsapp/contacts");console.log(),console.log(Ie.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){Bt(e)}});function wr(e,o){if(console.log(),console.log(Ie.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(Ie.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ie.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ie.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ie.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ie.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Ng(){try{let e=I(),[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 An(e){let o=await fetch(`${Ng()}${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 br(e,o){let t=await fetch(`${Ng()}${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 Bt(e){console.error(Ie.red(` ${e.message||e}`)),process.exit(1)}ae();import{Command as Wy}from"commander";import ge from"chalk";import{existsSync as By,mkdirSync as _g,writeFileSync as Tn}from"fs";import{join as Jt,resolve as Jy}from"path";var On=new Wy().name("plugin").description("manage agentx plugins (Move B)");On.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=I().plugins??[];if(console.log(),o.length===0){console.log(ge.dim(" No plugins configured.")),console.log(ge.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ge.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ge.cyan(t)}`);console.log(),console.log(ge.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});On.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(ge.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=Jy(o.cwd,t);By(n)&&!o.force&&(console.log(ge.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),_g(n,{recursive:!0}),_g(Jt(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Tn(Jt(n,"package.json"),Yy(e,s)),Tn(Jt(n,"tsconfig.json"),Vy()),Tn(Jt(n,"src/index.ts"),Ky(e)),Tn(Jt(n,"README.md"),Xy(e,s)),Tn(Jt(n,".gitignore"),Qy()),console.log(),console.log(ge.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ge.bold(" Next steps:")),console.log(ge.dim(` cd ${t}`)),console.log(ge.dim(" pnpm install")),console.log(ge.dim(" pnpm build")),console.log(ge.dim(" pnpm link --global # for local testing")),console.log(ge.dim(" # then in your agentx project:")),console.log(ge.dim(` pnpm link --global ${e}`)),console.log(ge.dim(` agentx config set plugins[0] "${e}"`)),console.log(ge.dim(" agentx plugin doctor")),console.log()});On.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=I().plugins??[];if(console.log(),o.length===0){console.log(ge.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Hy(n);s.kind==="ok"?console.log(` ${ge.green("\u2713")} ${ge.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ge.red("\u2717")} ${ge.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ge.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});async function Hy(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Gy(o);if(!zy(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Va.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 Gy(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 zy(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Yy(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)+`
564
+ `}function Vy(){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)+`
565
+ `}function Ky(e){return`// ${e} \u2014 AgentX plugin
566
566
  //
567
567
  // A plugin's default export is { manifest, setup }. The daemon calls
568
568
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -598,7 +598,7 @@ const plugin = {
598
598
  }
599
599
 
600
600
  export default plugin
601
- `}function Ly(e,o){return`# ${e}
601
+ `}function Xy(e,o){return`# ${e}
602
602
 
603
603
  ${o}
604
604
 
@@ -625,19 +625,24 @@ agentx plugin doctor
625
625
  \`\`\`
626
626
 
627
627
  Restart the daemon to activate.
628
- `}function Fy(){return`node_modules/
628
+ `}function Qy(){return`node_modules/
629
629
  dist/
630
630
  *.log
631
631
  .env
632
- `}import{Command as Uy}from"commander";import Ce from"chalk";import{writeFileSync as qy,mkdirSync as Wy,existsSync as Ls,readFileSync as Ag,appendFileSync as Tg}from"fs";import{resolve as Ht,dirname as jg}from"path";import{homedir as fr}from"os";var Cg=new Uy().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-ZRGI76RT.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Hy(t);break;case"bash":s=Ky(t);break;case"fish":s=Xy(t);break;default:console.error(Ce.red(`unsupported shell: ${n}`)),console.error(Ce.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Ht(String(e.output)):By(n);Wy(jg(i),{recursive:!0}),qy(i,s),console.log(Ce.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Jy(n,i,!!e.yes)});function By(e){let o=fr();switch(e){case"zsh":return Ht(o,".zsh","completions","_agentx");case"bash":return Ht(o,".bash_completion.d","agentx.bash");case"fish":return Ht(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Jy(e,o,t){if(e==="zsh"){let n=Ht(fr(),".zshrc"),s=jg(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ls(n)?Ag(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ce.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ls(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Tg(n,g.join(`
632
+ `}import{Command as Zy}from"commander";import Ce from"chalk";import{writeFileSync as ew,mkdirSync as ow,existsSync as Ws,readFileSync as Dg,appendFileSync as Pg}from"fs";import{resolve as Ht,dirname as Fg}from"path";import{homedir as kr}from"os";var Ug=new Zy().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-KWSQLVSV.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=sw(t);break;case"bash":s=lw(t);break;case"fish":s=dw(t);break;default:console.error(Ce.red(`unsupported shell: ${n}`)),console.error(Ce.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Ht(String(e.output)):tw(n);ow(Fg(i),{recursive:!0}),ew(i,s),console.log(Ce.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),nw(n,i,!!e.yes)});function tw(e){let o=kr();switch(e){case"zsh":return Ht(o,".zsh","completions","_agentx");case"bash":return Ht(o,".bash_completion.d","agentx.bash");case"fish":return Ht(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function nw(e,o,t){if(e==="zsh"){let n=Ht(kr(),".zshrc"),s=Fg(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ws(n)?Dg(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ce.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ws(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Pg(n,g.join(`
633
633
  `)+`
634
- `),console.log(Ce.green("\u2713 Patched ~/.zshrc")),console.log(Ce.dim("Reload your shell: exec zsh"));return}console.log(Ce.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ce.cyan(` ${i}`)),l&&console.log(Ce.cyan(` ${r}`)),console.log(),console.log(Ce.dim("Then reload: exec zsh")),console.log(Ce.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ht(fr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ls(n)?Ag(n,"utf-8"):"").includes(o)){console.log(Ce.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ls(n)){Tg(n,`
634
+ `),console.log(Ce.green("\u2713 Patched ~/.zshrc")),console.log(Ce.dim("Reload your shell: exec zsh"));return}console.log(Ce.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ce.cyan(` ${i}`)),l&&console.log(Ce.cyan(` ${r}`)),console.log(),console.log(Ce.dim("Then reload: exec zsh")),console.log(Ce.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ht(kr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ws(n)?Dg(n,"utf-8"):"").includes(o)){console.log(Ce.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ws(n)){Pg(n,`
635
635
  # agentx completion
636
636
  ${s}
637
- `),console.log(Ce.green("\u2713 Patched ~/.bashrc")),console.log(Ce.dim("Reload your shell: exec bash"));return}console.log(Ce.dim("Add this to ~/.bashrc:")),console.log(Ce.cyan(` ${s}`)),console.log(),console.log(Ce.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ce.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ge(e){return e._name||e.name()||""}function Bo(e){return e.commands.filter(o=>{let t=Ge(o);return!(!t||t==="help")})}function Tn(e){return e.options.filter(o=>!o.hidden)}function Hy(e){let o=[];return o.push("#compdef agentx"),o.push(""),Ng(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
638
- `)}function Og(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Ng(e,o,t){let n=Bo(e),i=Tn(e).map(Yy).filter(c=>!!c),r=Og(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(Vy).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=Og([...o,Ge(c)]);t.push(` (${Ge(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Ng(c,[...o,Ge(c)],t)}function Gy(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function zy(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Yy(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=Gy(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Vy(e){let o=zy(e.description()||"");return`'${Ge(e)}[${o}]'`}function Ky(e){let o=Bo(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(Ge).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=Bo(n).map(Ge),i=Ig(n);if(t.push(` ${Ge(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 Bo(n)){let a=Ig(r);t.push(` ${Ge(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(`
639
- `)}function Ig(e){let o=[];for(let t of Tn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Xy(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 Bo(e)){let n=hr(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ge(t)}" -d "${n}"`)}o.push("");for(let t of Tn(e)){let n=ur(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Bo(e)){let n=Ge(t);o.push(`# ${n}`);for(let s of Tn(t)){let i=ur(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Bo(t)){let i=hr(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Bo(t).map(Ge).join(" ")}" -a "${Ge(s)}" -d "${i}"`);for(let r of Tn(s)){let a=ur(r,[`__fish_seen_subcommand_from ${Ge(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
640
- `)}function hr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ur(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=hr(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function U1(){let e=await da(),o=new Qy().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=Oc(n);Ic(s)&&Tc("cli",s)});for(let t of[nl,el,_t,bt,vt,Xe,Sc,Yo,es,wo,Mo,Po,Zn,gg,Ro,xl,Nl,pn,Bl,zl,Yl,gd,fd,hd,jt,wn,hg,rn,Oo,Cg])o.addCommand(t);for(let t of Rg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Rg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Zy(t,74," "),""].join(`
641
- `)}),o}var Rg=[Z,Dt,qo,so,cn,Ct,He,$o,Lo,nt,Ft,Ut,Co,We,At,ws,cg,lg,ho,Vo,_c,Ko,An,wi,Uo,St,bi,js,po,Wo,kg,xg,fg];function Zy(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(`
642
- `)}export{U1 as a};
643
- //# sourceMappingURL=chunk-PRHIW6SQ.js.map
637
+ `),console.log(Ce.green("\u2713 Patched ~/.bashrc")),console.log(Ce.dim("Reload your shell: exec bash"));return}console.log(Ce.dim("Add this to ~/.bashrc:")),console.log(Ce.cyan(` ${s}`)),console.log(),console.log(Ce.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ce.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ge(e){return e._name||e.name()||""}function Bo(e){return e.commands.filter(o=>{let t=Ge(o);return!(!t||t==="help")})}function jn(e){return e.options.filter(o=>!o.hidden)}function sw(e){let o=[];return o.push("#compdef agentx"),o.push(""),qg(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
638
+ `)}function Mg(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function qg(e,o,t){let n=Bo(e),i=jn(e).map(aw).filter(c=>!!c),r=Mg(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(cw).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=Mg([...o,Ge(c)]);t.push(` (${Ge(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)qg(c,[...o,Ge(c)],t)}function iw(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function rw(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function aw(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=iw(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function cw(e){let o=rw(e.description()||"");return`'${Ge(e)}[${o}]'`}function lw(e){let o=Bo(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(Ge).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=Bo(n).map(Ge),i=Lg(n);if(t.push(` ${Ge(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 Bo(n)){let a=Lg(r);t.push(` ${Ge(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(`
639
+ `)}function Lg(e){let o=[];for(let t of jn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function dw(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 Bo(e)){let n=vr(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ge(t)}" -d "${n}"`)}o.push("");for(let t of jn(e)){let n=$r(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Bo(e)){let n=Ge(t);o.push(`# ${n}`);for(let s of jn(t)){let i=$r(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Bo(t)){let i=vr(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Bo(t).map(Ge).join(" ")}" -a "${Ge(s)}" -d "${i}"`);for(let r of jn(s)){let a=$r(r,[`__fish_seen_subcommand_from ${Ge(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
640
+ `)}function vr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function $r(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=vr(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 mw}from"commander";import zt from"chalk";import{readFile as pw}from"node:fs/promises";var Gt="anis-marrouchi/agentx",xr=`https://raw.githubusercontent.com/${Gt}/main/contrib/models.json`,Js=`https://github.com/${Gt}/issues/new/choose`,Bg=`https://github.com/${Gt}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,Wg=8e3,Bs={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 Sr(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 Er(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: ${Js}`].join(`
641
+ `)}function gw(e){return`---
642
+ _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function Jg(e,o){let t=Bs[e.category];if(!t)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(Bs).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}
643
+
644
+ ${gw({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${Gt}/issues/new?${a.toString()}`;if(c.length>Wg)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${Wg}). Shorten it, or paste it into the web form.`);return c}async function Hg(e,o=fetch){let t=`repo:${Gt} 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/${Gt}/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 Ar(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 In=new mw().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(zt.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${Js}`),console.log(" 2. Let your agent help: install the skill with"),console.log(zt.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: ${Bg}`),console.log(` Categories: ${Object.keys(Bs).join(", ")}`),console.log()});In.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",xr).action(async(e,o)=>{try{let t=await Ar(o.models);if(Sr(e,t)){console.log(zt.green(` "${e}" is on the recommended list.`));return}console.log(Er(e,t)),process.exitCode=1}catch(t){console.error(zt.red(` ${t.message}`)),console.error(` You can always write the issue yourself: ${Js}`),process.exitCode=1}});In.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 Hg(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}
645
+ ${t.url}`)}catch(o){console.error(zt.red(` ${o.message}`)),process.exitCode=1}});In.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",xr).action(async(e,o)=>{try{let t=await Ar(o.models);if(!Sr(o.model,t)){console.log(Er(o.model,t)),process.exitCode=1;return}let n=e==="-"?await uw():await pw(e,"utf8"),s=JSON.parse(n),{version:i}=await Pn(),r=Jg({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(zt.red(` ${t.message}`)),process.exitCode=1}});async function uw(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function gT(){let e=await Pn(),o=new fw().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=Mc(n);Lc(s)&&Pc("cli",s)});for(let t of[ml,ll,_t,bt,vt,Xe,Nc,Yo,ss,wo,Mo,Po,ns,$g,No,Rl,ql,fn,Ql,td,nd,$d,Sd,Ed,It,$n,Eg,cn,Oo,Ug,In])o.addCommand(t);for(let t of Gg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Gg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,hw(t,74," "),""].join(`
646
+ `)}),o}var Gg=[Z,Dt,qo,so,dn,Ct,He,$o,Lo,nt,Ft,Ut,Co,We,At,vs,yg,wg,ho,Vo,Bc,Ko,On,Si,Uo,St,Ei,_s,po,Wo,Ig,Rg,Sg];function hw(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(`
647
+ `)}export{gT as a};
648
+ //# sourceMappingURL=chunk-WDRLN7F2.js.map