agentix-cli 0.72.0 → 0.74.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 (112) hide show
  1. package/dist/{App-244WEQJR.js → App-U2MOUDOM.js} +2 -2
  2. package/dist/{ChatApp-SFP6SHUU.js → ChatApp-YY4RGZSI.js} +2 -2
  3. package/dist/{agent-PMNBXRFW.js → agent-HEL3Y4NA.js} +2 -2
  4. package/dist/{board-dashboard-J34PSEJS.js → board-dashboard-GNMELVCM.js} +262 -179
  5. package/dist/board-dashboard-GNMELVCM.js.map +1 -0
  6. package/dist/{chunk-335JCO5R.js → chunk-22TKLH6A.js} +170 -170
  7. package/dist/chunk-22TKLH6A.js.map +1 -0
  8. package/dist/{chunk-OSHG52OO.js → chunk-2RGXCUE3.js} +26 -26
  9. package/dist/{chunk-OSHG52OO.js.map → chunk-2RGXCUE3.js.map} +1 -1
  10. package/dist/{chunk-PY54XYAG.js → chunk-3TQ2WONT.js} +2 -2
  11. package/dist/{chunk-OWRPCMGW.js → chunk-6PUNM3Y7.js} +233 -214
  12. package/dist/chunk-6PUNM3Y7.js.map +1 -0
  13. package/dist/chunk-7XB2CVC3.js +2 -0
  14. package/dist/chunk-7XB2CVC3.js.map +1 -0
  15. package/dist/{chunk-DMWFRKWR.js → chunk-BOY572B3.js} +2 -2
  16. package/dist/{chunk-QKV7FN67.js → chunk-CVEL3UBP.js} +2 -2
  17. package/dist/{chunk-YVLFX35J.js → chunk-DEYXG7OA.js} +2 -2
  18. package/dist/{chunk-55N4VTWX.js → chunk-E343ELHB.js} +2 -2
  19. package/dist/{chunk-576L7ZFD.js → chunk-HAUOH34T.js} +2 -2
  20. package/dist/{chunk-7XR5LGLD.js → chunk-HGEZBEBI.js} +2 -2
  21. package/dist/{chunk-PC5LKW3L.js → chunk-HX4AF2N4.js} +2 -2
  22. package/dist/{chunk-FMUOVVXX.js → chunk-IEEKRDVW.js} +2 -2
  23. package/dist/{chunk-VWMO4C72.js → chunk-JXBXIH23.js} +2 -2
  24. package/dist/{chunk-MESWF2ZM.js → chunk-MMTP7WWU.js} +2 -2
  25. package/dist/{chunk-UFPWMNUW.js → chunk-RDEDIOAH.js} +2 -2
  26. package/dist/{chunk-PHSYP22H.js → chunk-ROKRMNVL.js} +2 -2
  27. package/dist/{chunk-J6RZOP7Z.js → chunk-S4NYBA3M.js} +2 -2
  28. package/dist/{chunk-PBRI3MTE.js → chunk-TUPHLC77.js} +2 -2
  29. package/dist/chunk-U7LOXDIP.js +15 -0
  30. package/dist/chunk-U7LOXDIP.js.map +1 -0
  31. package/dist/{chunk-Z5TXWHDN.js → chunk-W7XQCUDK.js} +2 -2
  32. package/dist/{chunk-FWQVXZ5T.js → chunk-WIBDEAAB.js} +32 -30
  33. package/dist/chunk-WIBDEAAB.js.map +1 -0
  34. package/dist/{chunk-TT4T6CB3.js → chunk-X6MK5VK3.js} +2 -2
  35. package/dist/cli.js +1 -1
  36. package/dist/client-7SK3SEQV.js +2 -0
  37. package/dist/{config-X7BHZ75G.js → config-6UXC7MPC.js} +2 -2
  38. package/dist/config-mutator-QNTAKNI7.js +2 -0
  39. package/dist/doctor-FNM7ZKP3.js +2 -0
  40. package/dist/{facts-X44PF73W.js → facts-2K6UX5GD.js} +6 -6
  41. package/dist/facts-2K6UX5GD.js.map +1 -0
  42. package/dist/index.d.ts +251 -6
  43. package/dist/index.js +1 -1
  44. package/dist/program-3DYKSCIY.js +2 -0
  45. package/dist/{promote-36XF4LH7.js → promote-I5QCWYXG.js} +2 -2
  46. package/dist/{query-YFZ6GWHU.js → query-WNOCMO46.js} +2 -2
  47. package/dist/{registry-WJSGG62F.js → registry-KXNT3HID.js} +2 -2
  48. package/dist/{request-planner-OXRWVBXI.js → request-planner-VAHGNG7U.js} +2 -2
  49. package/dist/{review-candidates-5XZWP2BN.js → review-candidates-UQJ3IA2Z.js} +2 -2
  50. package/dist/{routing-XEPCPLVM.js → routing-AVMCSZXP.js} +2 -2
  51. package/dist/schedule-tool-O47FNQ3A.js +2 -0
  52. package/dist/scheduler-DBAQHLHQ.js +2 -0
  53. package/dist/{seat-FGFHW363.js → seat-2GOJBTII.js} +2 -2
  54. package/dist/{select-N6CIZF2S.js → select-GIDPNJAA.js} +2 -2
  55. package/dist/{set-enabled-L7Z6H7EG.js → set-enabled-QW33PWJV.js} +2 -2
  56. package/dist/{tool-OSH6GHIF.js → tool-RXQ4F6HI.js} +2 -2
  57. package/dist/wiki-T22CW4EY.js +2 -0
  58. package/package.json +1 -1
  59. package/dist/board-dashboard-J34PSEJS.js.map +0 -1
  60. package/dist/chunk-335JCO5R.js.map +0 -1
  61. package/dist/chunk-FWQVXZ5T.js.map +0 -1
  62. package/dist/chunk-NMFXY3QU.js +0 -2
  63. package/dist/chunk-NMFXY3QU.js.map +0 -1
  64. package/dist/chunk-OWRPCMGW.js.map +0 -1
  65. package/dist/chunk-RAYOK4GI.js +0 -15
  66. package/dist/chunk-RAYOK4GI.js.map +0 -1
  67. package/dist/client-L4JAPXTE.js +0 -2
  68. package/dist/config-mutator-R2KBGTZJ.js +0 -2
  69. package/dist/doctor-5VFQVAVC.js +0 -2
  70. package/dist/facts-X44PF73W.js.map +0 -1
  71. package/dist/program-6C3G65YA.js +0 -2
  72. package/dist/schedule-tool-WQCO2YUG.js +0 -2
  73. package/dist/scheduler-4NQ62XDK.js +0 -2
  74. package/dist/wiki-E46QDRS7.js +0 -2
  75. /package/dist/{App-244WEQJR.js.map → App-U2MOUDOM.js.map} +0 -0
  76. /package/dist/{ChatApp-SFP6SHUU.js.map → ChatApp-YY4RGZSI.js.map} +0 -0
  77. /package/dist/{agent-PMNBXRFW.js.map → agent-HEL3Y4NA.js.map} +0 -0
  78. /package/dist/{chunk-PY54XYAG.js.map → chunk-3TQ2WONT.js.map} +0 -0
  79. /package/dist/{chunk-DMWFRKWR.js.map → chunk-BOY572B3.js.map} +0 -0
  80. /package/dist/{chunk-QKV7FN67.js.map → chunk-CVEL3UBP.js.map} +0 -0
  81. /package/dist/{chunk-YVLFX35J.js.map → chunk-DEYXG7OA.js.map} +0 -0
  82. /package/dist/{chunk-55N4VTWX.js.map → chunk-E343ELHB.js.map} +0 -0
  83. /package/dist/{chunk-576L7ZFD.js.map → chunk-HAUOH34T.js.map} +0 -0
  84. /package/dist/{chunk-7XR5LGLD.js.map → chunk-HGEZBEBI.js.map} +0 -0
  85. /package/dist/{chunk-PC5LKW3L.js.map → chunk-HX4AF2N4.js.map} +0 -0
  86. /package/dist/{chunk-FMUOVVXX.js.map → chunk-IEEKRDVW.js.map} +0 -0
  87. /package/dist/{chunk-VWMO4C72.js.map → chunk-JXBXIH23.js.map} +0 -0
  88. /package/dist/{chunk-MESWF2ZM.js.map → chunk-MMTP7WWU.js.map} +0 -0
  89. /package/dist/{chunk-UFPWMNUW.js.map → chunk-RDEDIOAH.js.map} +0 -0
  90. /package/dist/{chunk-PHSYP22H.js.map → chunk-ROKRMNVL.js.map} +0 -0
  91. /package/dist/{chunk-J6RZOP7Z.js.map → chunk-S4NYBA3M.js.map} +0 -0
  92. /package/dist/{chunk-PBRI3MTE.js.map → chunk-TUPHLC77.js.map} +0 -0
  93. /package/dist/{chunk-Z5TXWHDN.js.map → chunk-W7XQCUDK.js.map} +0 -0
  94. /package/dist/{chunk-TT4T6CB3.js.map → chunk-X6MK5VK3.js.map} +0 -0
  95. /package/dist/{client-L4JAPXTE.js.map → client-7SK3SEQV.js.map} +0 -0
  96. /package/dist/{config-X7BHZ75G.js.map → config-6UXC7MPC.js.map} +0 -0
  97. /package/dist/{config-mutator-R2KBGTZJ.js.map → config-mutator-QNTAKNI7.js.map} +0 -0
  98. /package/dist/{doctor-5VFQVAVC.js.map → doctor-FNM7ZKP3.js.map} +0 -0
  99. /package/dist/{program-6C3G65YA.js.map → program-3DYKSCIY.js.map} +0 -0
  100. /package/dist/{promote-36XF4LH7.js.map → promote-I5QCWYXG.js.map} +0 -0
  101. /package/dist/{query-YFZ6GWHU.js.map → query-WNOCMO46.js.map} +0 -0
  102. /package/dist/{registry-WJSGG62F.js.map → registry-KXNT3HID.js.map} +0 -0
  103. /package/dist/{request-planner-OXRWVBXI.js.map → request-planner-VAHGNG7U.js.map} +0 -0
  104. /package/dist/{review-candidates-5XZWP2BN.js.map → review-candidates-UQJ3IA2Z.js.map} +0 -0
  105. /package/dist/{routing-XEPCPLVM.js.map → routing-AVMCSZXP.js.map} +0 -0
  106. /package/dist/{schedule-tool-WQCO2YUG.js.map → schedule-tool-O47FNQ3A.js.map} +0 -0
  107. /package/dist/{scheduler-4NQ62XDK.js.map → scheduler-DBAQHLHQ.js.map} +0 -0
  108. /package/dist/{seat-FGFHW363.js.map → seat-2GOJBTII.js.map} +0 -0
  109. /package/dist/{select-N6CIZF2S.js.map → select-GIDPNJAA.js.map} +0 -0
  110. /package/dist/{set-enabled-L7Z6H7EG.js.map → set-enabled-QW33PWJV.js.map} +0 -0
  111. /package/dist/{tool-OSH6GHIF.js.map → tool-RXQ4F6HI.js.map} +0 -0
  112. /package/dist/{wiki-E46QDRS7.js.map → wiki-T22CW4EY.js.map} +0 -0
@@ -1,42 +1,42 @@
1
- import{a as sl,b as ns,g as il}from"./chunk-7XR5LGLD.js";import{a as Vc,c as Kc}from"./chunk-PC5LKW3L.js";import{a as Ke,b as Hc,f as Gc,g as zc,h as Yc,i as os,j as Xc,k as Qc,l as ki,m as ol,o as nl}from"./chunk-J6RZOP7Z.js";import{a as Zc,c as el,d as tl}from"./chunk-Z3IP66SL.js";import{a as ai,b as Sa}from"./chunk-RKPAVWXF.js";import{c as ma}from"./chunk-SZDACK6O.js";import{a as yo}from"./chunk-GV7S5BAX.js";import{e as ga}from"./chunk-GSX4NK2N.js";import{$ as bi,A as yc,B as di,C as wc,D as bc,E as $c,F as kc,G as vc,H as xc,I as Ic,J as Cc,K as bo,L as Qn,M as fi,N as Nc,O as Rc,P as _c,Q as Dc,R as $o,S as ko,T as Pc,U as Mc,V as Re,W as Zn,X as ln,Y as hi,Z as Lc,_ as qc,a as ka,aa as Bc,b as va,ba as es,c as xa,ca as vo,d as Na,da as ts,e as Ra,ea as $i,fa as Jc,k as Jn,l as Ma,m as rn,n as Hn,o as Ua,p as qa,q as Za,r as ec,s as Vn,t as li,u as ic,v as dc,w as pc,x as uc,y as fc,z as hc}from"./chunk-OWRPCMGW.js";import{D as cc,E as lc,Ga as Fc,Ha as yi,Ia as Uc,Ja as wi,R as an,U as gi,V as Kn,W as Sc,Xa as lt,Za as Wc,ba as At,ca as Ec,da as mi,fa as pi,ha as Ac,ia as Tc,ja as cn,na as Xn,p as Et,qa as jc,ra as Oc,sa as ui,t as rc,w as ac}from"./chunk-FWQVXZ5T.js";import{a as _a,d as Da,e as Pa}from"./chunk-PY54XYAG.js";import{a as Gn,b as zn,c as Wa,d as Ba,e as Ja,g as Ha,h as Ga,j as za,k as Ya,l as Va,m as Ka,p as Yn,r as Xa,s as Qa}from"./chunk-BYJ3A55Y.js";import{a as La,p as Fa}from"./chunk-VWMO4C72.js";import{a as tc,b as oc,c as nc,d as sc}from"./chunk-2D3RYIDU.js";import{a as gc,b as mc}from"./chunk-EKJG63EJ.js";import{A as St,G as ba,R as $a,g as sa,p as ia,u as si,v as la}from"./chunk-OSHG52OO.js";import{b as po,g as fo,h as Wn,i as Bn,j as ho,k as da,l as Gt,m as sn}from"./chunk-PBRI3MTE.js";import{e as ha,f as ri,k as ya}from"./chunk-WP6KLXTP.js";import{a as na}from"./chunk-N6EWZGIX.js";import{b as uo}from"./chunk-DP7RTNDM.js";import{a as ci,e as Ea,f as Aa,h as Ta,i as ja,k as Oa,l as Ia,m as Ca}from"./chunk-576L7ZFD.js";import{f as pa,g as ua,h as ii}from"./chunk-76Z4VHDX.js";import{a as aa,k as fa}from"./chunk-DMWFRKWR.js";import{b as ye,c as Oe,d as wo,e as wa}from"./chunk-55N4VTWX.js";import{a as oi}from"./chunk-QKV7FN67.js";import{a as ni,b as ra}from"./chunk-GQ76J72O.js";import{j as ca}from"./chunk-X5C5W3E4.js";import{h as oa}from"./chunk-DWADWDMU.js";import{g as xt,i as qn}from"./chunk-TT4T6CB3.js";import{b as mo,d as ta}from"./chunk-2GIDVZ4H.js";import{a as ti,b as Fr,c as bm,d as Fn,e as Ur,f as Vr,g as vm,h as Kr,i as xm,m as go,n as Qr,o as Zr,s as ea,v as ct,w as nn}from"./chunk-YVLFX35J.js";import{a as Xr,b as Sm}from"./chunk-FX3D7YON.js";import{a as ht,b as lo,e as Gr,f as on}from"./chunk-72SZI2UW.js";import{a as ft,b as wm}from"./chunk-7I7IEX4S.js";import{A as ie,m as qr,n as Wr,p as Br,q as $m,v as Jr,w as Hr,x as I,y as Un}from"./chunk-RAYOK4GI.js";import{g as zr,k as Yr,l as km}from"./chunk-RGDKHYY2.js";import{Command as Em}from"commander";var rl=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 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()});ie();import{Command as Am}from"commander";import{execFileSync as Qe}from"node:child_process";import{cpSync as al,existsSync as Si,mkdirSync as vi,mkdtempSync as Tm,readdirSync as jm,rmSync as cl,writeFileSync as ll}from"node:fs";import{dirname as dl,join as De}from"node:path";import{homedir as ss,release as Om,tmpdir as Im}from"node:os";import{setTimeout as Cm}from"node:timers/promises";function is(){let e=Wa(process.platform,process.arch,Om());if(e)throw new Error(e)}function rs(){let e=De(ss(),"Library/LaunchAgents"),t=[];try{t=jm(e).filter(Ha)}catch{}let o=t.flatMap(n=>{let s=De(e,n);try{return[{file:s,plist:Qe("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ga(e,o)}function dn(e){return`gui/${process.getuid()}/${e.label}`}async function xi(e){try{Qe("launchctl",["bootout",dn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Qe("launchctl",["print",dn(e)],{stdio:"pipe"})}catch{return}await Cm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function gl(e){if(!Si(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Qe("launchctl",["print",dn(e)],{stdio:"pipe"})}catch{t=!1}t||Qe("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Qe("launchctl",["kickstart",dn(e)],{stdio:"pipe"})}function Nm(){let e=Ka();if(e&&Si(De(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 xo=new Am("desktop").description("install and control the macOS desktop assistant");xo.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=>{is();let t=I(),o=Ba(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Nm(),r=De(ss(),"Applications"),{keep:a,remove:c}=rs();if(console.log(`Desktop assistant \u2192 ${De(r,Gn)}
2
- Computer-use helper \u2192 ${De(r,zn)}
1
+ import{a as ll,b as as,g as dl}from"./chunk-HGEZBEBI.js";import{a as el,c as tl}from"./chunk-HX4AF2N4.js";import{a as Xe,b as Kc,f as Xc,g as Qc,h as Zc,i as rs,j as ol,k as nl,l as Ei,m as al,o as cl}from"./chunk-S4NYBA3M.js";import{a as sl,c as il,d as rl}from"./chunk-Z3IP66SL.js";import{a as gi,b as ja}from"./chunk-RKPAVWXF.js";import{c as ha}from"./chunk-SZDACK6O.js";import{a as bo}from"./chunk-GV7S5BAX.js";import{e as fa}from"./chunk-GSX4NK2N.js";import{$ as Gc,A as kc,B as ui,C as vc,D as xc,E as Sc,F as Ec,G as Ac,H as Tc,I as _c,J as Dc,K as Pc,L as ko,M as os,N as bi,O as Mc,P as Lc,Q as Fc,R as Uc,S as vo,T as xo,U as qc,V as Wc,W as _e,X as ns,Y as gn,Z as $i,_ as Bc,a as Ea,aa as xi,b as Aa,ba as Yc,c as Ta,ca as ss,d as Pa,da as So,e as Ma,ea as is,fa as Si,ga as Vc,k as Yn,l as qa,m as cn,n as Vn,o as Ja,p as Ha,q as nc,r as sc,s as Zn,t as pi,u as lc,v as uc,w as yc,x as wc,y as bc,z as $c}from"./chunk-6PUNM3Y7.js";import{H as mc,I as pc,Na as Jc,Oa as ki,Pa as Hc,Qa as vi,V as ln,Y as fi,Z as es,_ as jc,cb as dt,eb as zc,fa as jt,ga as Oc,ha as hi,ja as yi,la as Ic,ma as Cc,na as dn,p as Tt,ra as ts,t as dc,ua as Nc,va as Rc,w as gc,wa as wi}from"./chunk-WIBDEAAB.js";import{a as La,d as Fa,e as Ua}from"./chunk-3TQ2WONT.js";import{a as Kn,b as Xn,c as Ga,d as za,e as Ya,g as Va,h as Ka,j as Xa,k as Qa,l as Za,m as ec,p as Qn,r as tc,s as oc}from"./chunk-BYJ3A55Y.js";import{a as Wa,p as Ba}from"./chunk-JXBXIH23.js";import{a as ic,b as rc,c as ac,d as cc}from"./chunk-2D3RYIDU.js";import{a as fc,b as hc}from"./chunk-EKJG63EJ.js";import{C as At,I as xa,T as Sa,g as ca,p as la,w as ci,x as pa}from"./chunk-2RGXCUE3.js";import{b as fo,g as yo,h as Gn,i as zn,j as wo,k as ua,l as zt,m as an}from"./chunk-TUPHLC77.js";import{e as $a,f as di,k as ka}from"./chunk-WP6KLXTP.js";import{a as Jn}from"./chunk-N6EWZGIX.js";import{b as ho}from"./chunk-DP7RTNDM.js";import{a as mi,e as Oa,f as Ia,h as Ca,i as Na,k as Ra,l as _a,m as Da}from"./chunk-HAUOH34T.js";import{f as ya,g as wa,h as li}from"./chunk-76Z4VHDX.js";import{a as ga,k as ba}from"./chunk-BOY572B3.js";import{b as pe,c as Oe,d as $o,e as va}from"./chunk-E343ELHB.js";import{a as ri}from"./chunk-CVEL3UBP.js";import{a as ai,b as da}from"./chunk-GQ76J72O.js";import{j as ma}from"./chunk-X5C5W3E4.js";import{h as aa}from"./chunk-DWADWDMU.js";import{g as Et,i as Hn}from"./chunk-X6MK5VK3.js";import{b as uo,d as ra}from"./chunk-2GIDVZ4H.js";import{a as ii,b as Jr,c as Am,d as Wn,e as Hr,f as ea,g as Om,h as ta,i as Im,m as po,n as na,o as sa,s as ia,v as lt,w as rn}from"./chunk-DEYXG7OA.js";import{a as oa,b as Cm}from"./chunk-FX3D7YON.js";import{a as yt,b as mo,e as Xr,f as sn}from"./chunk-72SZI2UW.js";import{a as ht,b as Em}from"./chunk-7I7IEX4S.js";import{A as Bn,C as ne,m as Gr,n as zr,p as Yr,q as Tm,x as Vr,y as Kr,z as I}from"./chunk-U7LOXDIP.js";import{g as Qr,k as Zr,l as jm}from"./chunk-RGDKHYY2.js";import{Command as Nm}from"commander";var gl=new Nm().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 Ma({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});ne();import{Command as Rm}from"commander";import{execFileSync as Ze}from"node:child_process";import{cpSync as ml,existsSync as ji,mkdirSync as Ai,mkdtempSync as _m,readdirSync as Dm,rmSync as pl,writeFileSync as ul}from"node:fs";import{dirname as fl,join as Pe}from"node:path";import{homedir as cs,release as Pm,tmpdir as Mm}from"node:os";import{setTimeout as Lm}from"node:timers/promises";function ls(){let e=Ga(process.platform,process.arch,Pm());if(e)throw new Error(e)}function ds(){let e=Pe(cs(),"Library/LaunchAgents"),t=[];try{t=Dm(e).filter(Va)}catch{}let o=t.flatMap(n=>{let s=Pe(e,n);try{return[{file:s,plist:Ze("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ka(e,o)}function mn(e){return`gui/${process.getuid()}/${e.label}`}async function Ti(e){try{Ze("launchctl",["bootout",mn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Ze("launchctl",["print",mn(e)],{stdio:"pipe"})}catch{return}await Lm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function hl(e){if(!ji(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Ze("launchctl",["print",mn(e)],{stdio:"pipe"})}catch{t=!1}t||Ze("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Ze("launchctl",["kickstart",mn(e)],{stdio:"pipe"})}function Fm(){let e=ec();if(e&&ji(Pe(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Eo=new Rm("desktop").description("install and control the macOS desktop assistant");Eo.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{ls();let t=I(),o=za(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Fm(),r=Pe(cs(),"Applications"),{keep:a,remove:c}=ds();if(console.log(`Desktop assistant \u2192 ${Pe(r,Kn)}
2
+ Computer-use helper \u2192 ${Pe(r,Xn)}
3
3
  Agent \u2192 ${n?`${o} (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{Qe("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=Qe("/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(De(Im(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){al(De(i,"apps",p),De(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let h=p==="mac-helper"?Ya(t.notifications.local.icon):[];Qe("/bin/bash",[De(g,p,"build.sh"),...h],{stdio:"inherit"})}let d=De(ss(),"Library/Logs/agentx-desktop.err.log"),u=za({label:a.label,executable:De(r,Gn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:Va(ss()),cli:De(i,"dist/cli.js"),node:process.execPath,log:d,path:Ja(l,process.env.AGENTX_VOICE_PATH)}),f=De(g,"desktop.plist");ll(f,u,{mode:384}),Qe("plutil",["-lint",f],{stdio:"pipe"}),await xi(a);for(let p of c)p.label!==a.label&&await xi(p),cl(p.file,{force:!0});vi(r,{recursive:!0});for(let[p,h,w]of[["mac-voice","AgentX Voice.app",Gn],["mac-helper",zn,zn]])al(De(g,p,"build",h),De(r,w),{recursive:!0});vi(dl(a.file),{recursive:!0}),vi(dl(d),{recursive:!0}),ll(a.file,u,{mode:384}),gl(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{Ze("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=Ze("/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=_m(Pe(Mm(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){ml(Pe(i,"apps",p),Pe(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let h=p==="mac-helper"?Qa(t.notifications.local.icon):[];Ze("/bin/bash",[Pe(g,p,"build.sh"),...h],{stdio:"inherit"})}let d=Pe(cs(),"Library/Logs/agentx-desktop.err.log"),u=Xa({label:a.label,executable:Pe(r,Kn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:Za(cs()),cli:Pe(i,"dist/cli.js"),node:process.execPath,log:d,path:Ya(l,process.env.AGENTX_VOICE_PATH)}),f=Pe(g,"desktop.plist");ul(f,u,{mode:384}),Ze("plutil",["-lint",f],{stdio:"pipe"}),await Ti(a);for(let p of c)p.label!==a.label&&await Ti(p),pl(p.file,{force:!0});Ai(r,{recursive:!0});for(let[p,h,w]of[["mac-voice","AgentX Voice.app",Kn],["mac-helper",Xn,Xn]])ml(Pe(g,p,"build",h),Pe(r,w),{recursive:!0});Ai(fl(a.file),{recursive:!0}),Ai(fl(d),{recursive:!0}),ul(a.file,u,{mode:384}),hl(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{cl(g,{recursive:!0,force:!0})}});xo.command("start").description("start the installed desktop assistant").action(()=>{is(),gl(rs().keep),console.log("Desktop assistant started.")});xo.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{is(),await xi(rs().keep),console.log("Desktop assistant stopped.")});xo.command("status").description("show the desktop login service status").action(()=>{is();let{keep:e}=rs();try{console.log(Qe("launchctl",["print",dn(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Si(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Lm}from"commander";import{open as Fm}from"fs/promises";import{existsSync as ls,mkdirSync as Rm,readFileSync as ds,writeFileSync as ml}from"fs";import{homedir as _m}from"os";import{dirname as Dm,resolve as Ei}from"path";var Ai="/attach/",pl="/guard/check";function ul(e,t,o=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${t}${e}${o}`}' 2>/dev/null || true`}function as(e,t,o){let n={hooks:[{type:"command",command:ul(e,t),timeout:10}]};return o!==void 0&&(n.matcher=o),n}function Pm(e){return{SessionStart:[as("/attach/session-start",e,"")],UserPromptSubmit:[as("/attach/prompt",e)],Stop:[as("/attach/stop",e)],SessionEnd:[as("/attach/session-end",e)]}}function Mm(e){let t=ul("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:t,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:t,timeout:10}]}]}function cs(e,t){return Array.isArray(e?.hooks)&&e.hooks.some(o=>typeof o?.command=="string"&&o.command.includes(t))}function gn(){return Ei(_m(),".claude/settings.json")}function zt(e=process.cwd()){for(let t of[e,Ei(e,"..")]){let o=Ei(t,"agentx.json");if(ls(o))try{let n=JSON.parse(ds(o,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function fl(e,t={}){let o=t.path??gn(),n=t.withGuard!==!1,s={};if(ls(o))try{s=JSON.parse(ds(o,"utf-8"))}catch(g){throw new Error(`${o} 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(Pm(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!cs(f,Ai)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!cs(d,pl)):[];r.PreToolUse=[...g,...Mm(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(Rm(Dm(o),{recursive:!0}),ml(o,`${JSON.stringify(s,null,2)}
9
- `)),{path:o,changed:l,events:a,guardInstalled:c}}function hl(e={}){let t=e.path??gn();if(!ls(t))return{path:t,changed:!1,events:[],guardInstalled:!1};let o;try{o=JSON.parse(ds(t,"utf-8"))}catch(a){throw new Error(`${t} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(o),s=o.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?pl:Ai;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!cs(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 o.hooks}let r=JSON.stringify(o)!==n;return r&&ml(t,`${JSON.stringify(o,null,2)}
10
- `),{path:t,changed:r,events:i,guardInstalled:!1}}function mn(e=gn()){if(!ls(e))return!1;try{return!!JSON.parse(ds(e,"utf-8"))?.hooks?.Stop?.some?.(o=>cs(o,Ai))}catch{return!1}}var gs=new Lm("monitor").description("Register external CLI sessions and report ended runs to the briefing"),yl=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${zt()}`;async function wl(e,t,o){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+t,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(o),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}gs.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",yl).action(async e=>{try{await wl(e.url,"register",Da.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(t){console.error(t.message),process.exitCode=1}});gs.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",yl).action(async e=>{try{let t=await Fm(e.transcript,"r"),o;try{let n=await t.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 t.read(i,0,s,Math.max(0,n.size-s));o=(n.size>s?`[Transcript truncated: last 90 KB only]
11
- `:"")+i.subarray(0,r).toString("utf8")}finally{await t.close()}await wl(e.url,"ended",Pa.parse({sessionId:e.session,runId:e.run,transcript:o})),console.log("Run queued for review.")}catch(t){console.error(t.message),process.exitCode=1}});import{Command as eb}from"commander";import{Command as Ym}from"commander";ie();import T from"chalk";import{existsSync as Vm,readFileSync as Km}from"fs";ie();import{Command as Um}from"commander";import ne from"chalk";import{spawn as $l}from"child_process";import{existsSync as qm,readFileSync as Wm,unlinkSync as Bm}from"fs";import{resolve as Ti}from"path";var ji=e=>new Promise(t=>setTimeout(t,e));function Oi(e){try{return process.kill(e,0),!0}catch{return!1}}async function So(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(3e3)});return t.ok?await t.json():null}catch{return null}}async function Jm(e){let t=await So(`${e}/daemon/restart`);if(typeof t?.inflight?.total=="number")return t.inflight.total;let o=await So(`${e}/health`);return o?typeof o.inflight?.total=="number"?o.inflight.total:Array.isArray(o.agents)?o.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Hm(e){for(let t of[Ti(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let o=parseInt(Wm(t,"utf-8").trim(),10);if(Number.isFinite(o)&&Oi(o))return o}catch{}return null}function Gm(e){return new Promise(t=>{let o=$l(e[0],e.slice(1),{stdio:"inherit"});o.on("error",()=>t(127)),o.on("exit",n=>t(n??1))})}var kl=new Um("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 t=I(e.config),[o,n]=t.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!o||o==="0.0.0.0"?"127.0.0.1":o}:${s}`,r=await So(`${i}/health`);r||(console.log(ne.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(ne.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await So(`${i}/daemon/restart`),c=a?.pid??wc(s)??Hm(process.cwd()),l=a?.service??(c?hc(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=uc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?yc(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${ne.bold(r.node?.name||r.node?.id||i)}${c?ne.dim(` (PID ${c})`):""}`),console.log(` Run by: ${fc(l)}`),f.ok||(console.log(ne.red(` ${f.reason}`)),console.log(ne.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(ne.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(ne.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(ne.dim(" Would run:"));for(let b of f.steps)console.log(ne.dim(` ${bl(b,c)}`));console.log();return}if(e.whenIdle){let b=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite(b)||b<0)&&(console.log(ne.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await pc({read:()=>Jm(i),intervalMs:E*1e3,timeoutMs:b*6e4,onCheck:v=>{v!==S&&v!==null&&v>0&&console.log(ne.dim(` Waiting: ${v} task(s) running...`)),S=v}});if(x.outcome==="unreachable"&&(console.log(ne.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(ne.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let v=x.inflight??"some";e.abortOnTimeout&&(console.log(ne.yellow(` Still ${v} task(s) running after ${b} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(ne.yellow(` Still ${v} task(s) running after ${b} min. Restarting anyway:`)),console.log(ne.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(ne.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=Ti(g,".agentx");try{mc(p,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let h=Date.now(),w=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(ne.dim(" Restarting..."));for(let b of f.steps){if(await zm(b,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||b.kind==="exec"&&b.mayFail)continue;let S=b===f.steps[0];try{S&&Bm(Ti(p,gc))}catch{}console.log(ne.red(` Step failed: ${bl(b,c)}`)),console.log(S?ne.dim(` The daemon is still running. Restart it with: ${f.manual}`):ne.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,$=Date.now();for(;Date.now()-$<k;){let b=await So(`${i}/health`);if(b&&typeof b.uptime=="number"&&b.uptime*1e3<=Date.now()-h+2e3){let E=await So(`${i}/daemon/restart`);console.log(ne.green(` Daemon is back${E?.pid?` (PID ${E.pid})`:""} after ${Math.round((Date.now()-h)/1e3)}s.`)),console.log();return}await ji(1e3)}console.log(ne.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(ne.dim(` Start it with: ${f.manual}`)),console.log(ne.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function bl(e,t){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${t??"<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 zm(e,t){switch(e.kind){case"exec":return await Gm(e.argv)===0;case"sigterm":if(!t.pid)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!t.pid)return!0;let o=Date.now(),n=!1;for(;Oi(t.pid)&&Date.now()-o<t.drainLimitMs;)!n&&Date.now()-o>3e3&&(console.log(ne.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await ji(500);return Oi(t.pid)?(console.log(ne.yellow(` The old daemon (PID ${t.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(t.service.kind!=="launchd")return!0;let o=Date.now();for(;di(t.service)&&Date.now()-o<3e4;)await ji(500);return!di(t.service)}case"start-detached":{let o=process.argv[1];if(!o||!qm(o))return!1;let n=[o,"daemon","start","--detach",...t.configPath?["-c",t.configPath]:[]];return new Promise(s=>{let i=$l(process.execPath,n,{cwd:t.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function Xm(e){try{let{execFileSync:t}=await import("child_process"),o=t("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return o?/\bnode\b/.test(o)||/agentx|agentix|cli\.js/.test(o):!1}catch{return!0}}var Ze=new Ym().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ze.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 h="/tmp/agentx-daemon.log",w;try{w=g(h,"a")}catch($){console.error(T.red(` Failed to open ${h} for writing: ${$.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${h}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise($=>setTimeout($,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${h} for the error:`)),console.log(T.dim(` tail -n 40 ${h}`))}return}let{readFileSync:t,writeFileSync:o,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(t(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Xm(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}o(a,String(process.pid));try{Qm(i(process.cwd(),".env"))}catch{}await new $i(e.config).start()});function Qm(e){if(!Vm(e))return;let t=Km(e,"utf-8");for(let o of t.split(`
12
- `)){let n=o.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}}Ze.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:t,unlinkSync:o}=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(t(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-SNI2B4LI.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;vl(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(vl(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{o(r)}catch{}console.log(T.green(`Daemon stopped (PID: ${a})`));return}catch{try{o(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"))}});Ze.addCommand(kl);Ze.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 t=I(e.config),[o,n]=t.node.bind.split(":"),s=`http://${o||"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 ${Zm(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(t){if(t.cause?.code==="ECONNREFUSED"||t.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let o=I(e.config),n=Un(o);if(console.log(),console.log(T.bold(` ${o.node.name}`)+T.dim(` (${o.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.dim(` ${Object.keys(o.agents).length} agents, ${Object.keys(o.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(T.yellow(` \u26A0 ${s}`))}console.log()}catch(o){console.log(T.red(` ${o.message}`))}}});Ze.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:t,spawn:o}=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=o("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else t(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Ze.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
8
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{pl(g,{recursive:!0,force:!0})}});Eo.command("start").description("start the installed desktop assistant").action(()=>{ls(),hl(ds().keep),console.log("Desktop assistant started.")});Eo.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{ls(),await Ti(ds().keep),console.log("Desktop assistant stopped.")});Eo.command("status").description("show the desktop login service status").action(()=>{ls();let{keep:e}=ds();try{console.log(Ze("launchctl",["print",mn(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(ji(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Hm}from"commander";import{open as Gm}from"fs/promises";import{existsSync as ps,mkdirSync as Um,readFileSync as us,writeFileSync as yl}from"fs";import{homedir as qm}from"os";import{dirname as Wm,resolve as Oi}from"path";var Ii="/attach/",wl="/guard/check";function bl(e,t,o=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${t}${e}${o}`}' 2>/dev/null || true`}function gs(e,t,o){let n={hooks:[{type:"command",command:bl(e,t),timeout:10}]};return o!==void 0&&(n.matcher=o),n}function Bm(e){return{SessionStart:[gs("/attach/session-start",e,"")],UserPromptSubmit:[gs("/attach/prompt",e)],Stop:[gs("/attach/stop",e)],SessionEnd:[gs("/attach/session-end",e)]}}function Jm(e){let t=bl("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:t,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:t,timeout:10}]}]}function ms(e,t){return Array.isArray(e?.hooks)&&e.hooks.some(o=>typeof o?.command=="string"&&o.command.includes(t))}function pn(){return Oi(qm(),".claude/settings.json")}function Yt(e=process.cwd()){for(let t of[e,Oi(e,"..")]){let o=Oi(t,"agentx.json");if(ps(o))try{let n=JSON.parse(us(o,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function $l(e,t={}){let o=t.path??pn(),n=t.withGuard!==!1,s={};if(ps(o))try{s=JSON.parse(us(o,"utf-8"))}catch(g){throw new Error(`${o} 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(Bm(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!ms(f,Ii)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!ms(d,wl)):[];r.PreToolUse=[...g,...Jm(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(Um(Wm(o),{recursive:!0}),yl(o,`${JSON.stringify(s,null,2)}
9
+ `)),{path:o,changed:l,events:a,guardInstalled:c}}function kl(e={}){let t=e.path??pn();if(!ps(t))return{path:t,changed:!1,events:[],guardInstalled:!1};let o;try{o=JSON.parse(us(t,"utf-8"))}catch(a){throw new Error(`${t} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(o),s=o.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?wl:Ii;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!ms(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 o.hooks}let r=JSON.stringify(o)!==n;return r&&yl(t,`${JSON.stringify(o,null,2)}
10
+ `),{path:t,changed:r,events:i,guardInstalled:!1}}function un(e=pn()){if(!ps(e))return!1;try{return!!JSON.parse(us(e,"utf-8"))?.hooks?.Stop?.some?.(o=>ms(o,Ii))}catch{return!1}}var fs=new Hm("monitor").description("Register external CLI sessions and report ended runs to the briefing"),vl=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Yt()}`;async function xl(e,t,o){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+t,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(o),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}fs.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",vl).action(async e=>{try{await xl(e.url,"register",Fa.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(t){console.error(t.message),process.exitCode=1}});fs.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",vl).action(async e=>{try{let t=await Gm(e.transcript,"r"),o;try{let n=await t.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 t.read(i,0,s,Math.max(0,n.size-s));o=(n.size>s?`[Transcript truncated: last 90 KB only]
11
+ `:"")+i.subarray(0,r).toString("utf8")}finally{await t.close()}await xl(e.url,"ended",Ua.parse({sessionId:e.session,runId:e.run,transcript:o})),console.log("Run queued for review.")}catch(t){console.error(t.message),process.exitCode=1}});import{Command as cb}from"commander";import{Command as tp}from"commander";ne();import T from"chalk";import{existsSync as op,readFileSync as np}from"fs";ne();import{Command as zm}from"commander";import se from"chalk";import{spawn as El}from"child_process";import{existsSync as Ym,readFileSync as Vm,unlinkSync as Km}from"fs";import{resolve as Ci}from"path";var Ni=e=>new Promise(t=>setTimeout(t,e));function Ri(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ao(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(3e3)});return t.ok?await t.json():null}catch{return null}}async function Xm(e){let t=await Ao(`${e}/daemon/restart`);if(typeof t?.inflight?.total=="number")return t.inflight.total;let o=await Ao(`${e}/health`);return o?typeof o.inflight?.total=="number"?o.inflight.total:Array.isArray(o.agents)?o.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Qm(e){for(let t of[Ci(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let o=parseInt(Vm(t,"utf-8").trim(),10);if(Number.isFinite(o)&&Ri(o))return o}catch{}return null}function Zm(e){return new Promise(t=>{let o=El(e[0],e.slice(1),{stdio:"inherit"});o.on("error",()=>t(127)),o.on("exit",n=>t(n??1))})}var Al=new zm("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 t=I(e.config),[o,n]=t.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!o||o==="0.0.0.0"?"127.0.0.1":o}:${s}`,r=await Ao(`${i}/health`);r||(console.log(se.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(se.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await Ao(`${i}/daemon/restart`),c=a?.pid??vc(s)??Qm(process.cwd()),l=a?.service??(c?$c(c):{kind:"none"}),g=a?.cwd??process.cwd(),d=e.config??a?.configPath,u=process.getuid?.()===0,f=wc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?kc(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${se.bold(r.node?.name||r.node?.id||i)}${c?se.dim(` (PID ${c})`):""}`),console.log(` Run by: ${bc(l)}`),f.ok||(console.log(se.red(` ${f.reason}`)),console.log(se.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(se.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(se.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(se.dim(" Would run:"));for(let b of f.steps)console.log(se.dim(` ${Sl(b,c)}`));console.log();return}if(e.whenIdle){let b=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite(b)||b<0)&&(console.log(se.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await yc({read:()=>Xm(i),intervalMs:E*1e3,timeoutMs:b*6e4,onCheck:v=>{v!==S&&v!==null&&v>0&&console.log(se.dim(` Waiting: ${v} task(s) running...`)),S=v}});if(x.outcome==="unreachable"&&(console.log(se.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(se.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let v=x.inflight??"some";e.abortOnTimeout&&(console.log(se.yellow(` Still ${v} task(s) running after ${b} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(se.yellow(` Still ${v} task(s) running after ${b} min. Restarting anyway:`)),console.log(se.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(se.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=Ci(g,".agentx");try{hc(p,{by:"agentx daemon restart",pid:process.pid,at:new Date().toISOString()})}catch{}let h=Date.now(),w=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4;console.log(se.dim(" Restarting..."));for(let b of f.steps){if(await ep(b,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||b.kind==="exec"&&b.mayFail)continue;let S=b===f.steps[0];try{S&&Km(Ci(p,fc))}catch{}console.log(se.red(` Step failed: ${Sl(b,c)}`)),console.log(S?se.dim(` The daemon is still running. Restart it with: ${f.manual}`):se.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,$=Date.now();for(;Date.now()-$<k;){let b=await Ao(`${i}/health`);if(b&&typeof b.uptime=="number"&&b.uptime*1e3<=Date.now()-h+2e3){let E=await Ao(`${i}/daemon/restart`);console.log(se.green(` Daemon is back${E?.pid?` (PID ${E.pid})`:""} after ${Math.round((Date.now()-h)/1e3)}s.`)),console.log();return}await Ni(1e3)}console.log(se.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(se.dim(` Start it with: ${f.manual}`)),console.log(se.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function Sl(e,t){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${t??"<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 ep(e,t){switch(e.kind){case"exec":return await Zm(e.argv)===0;case"sigterm":if(!t.pid)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!t.pid)return!0;let o=Date.now(),n=!1;for(;Ri(t.pid)&&Date.now()-o<t.drainLimitMs;)!n&&Date.now()-o>3e3&&(console.log(se.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await Ni(500);return Ri(t.pid)?(console.log(se.yellow(` The old daemon (PID ${t.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(t.service.kind!=="launchd")return!0;let o=Date.now();for(;ui(t.service)&&Date.now()-o<3e4;)await Ni(500);return!ui(t.service)}case"start-detached":{let o=process.argv[1];if(!o||!Ym(o))return!1;let n=[o,"daemon","start","--detach",...t.configPath?["-c",t.configPath]:[]];return new Promise(s=>{let i=El(process.execPath,n,{cwd:t.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function sp(e){try{let{execFileSync:t}=await import("child_process"),o=t("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return o?/\bnode\b/.test(o)||/agentx|agentix|cli\.js/.test(o):!1}catch{return!0}}var et=new tp().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");et.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 h="/tmp/agentx-daemon.log",w;try{w=g(h,"a")}catch($){console.error(T.red(` Failed to open ${h} for writing: ${$.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${h}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise($=>setTimeout($,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${h} for the error:`)),console.log(T.dim(` tail -n 40 ${h}`))}return}let{readFileSync:t,writeFileSync:o,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(t(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await sp(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}o(a,String(process.pid));try{ip(i(process.cwd(),".env"))}catch{}await new Si(e.config).start()});function ip(e){if(!op(e))return;let t=np(e,"utf-8");for(let o of t.split(`
12
+ `)){let n=o.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}}et.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:t,unlinkSync:o}=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(t(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-SNI2B4LI.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;Tl(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(Tl(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{o(r)}catch{}console.log(T.green(`Daemon stopped (PID: ${a})`));return}catch{try{o(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"))}});et.addCommand(Al);et.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 t=I(e.config),[o,n]=t.node.bind.split(":"),s=`http://${o||"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 ${rp(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(t){if(t.cause?.code==="ECONNREFUSED"||t.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let o=I(e.config),n=Bn(o);if(console.log(),console.log(T.bold(` ${o.node.name}`)+T.dim(` (${o.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.dim(` ${Object.keys(o.agents).length} agents, ${Object.keys(o.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(T.yellow(` \u26A0 ${s}`))}console.log()}catch(o){console.log(T.red(` ${o.message}`))}}});et.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:t,spawn:o}=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=o("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else t(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});et.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."))}});Ze.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,t,o)=>{let n=t.join(" ");try{let s=I(o.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;o.peer?(c=`${a}/mesh/task`,l={peer:o.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(T.dim(` Sending to ${o.peer?`${o.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();o.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"))}});Ze.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,t)=>{let{execSync:o}=await import("child_process"),n=t.identity?`-e "ssh -i ${t.identity}"`:"",s=`${t.user}@${e}:${t.path}/dist/`;if(!t.skipChecks){try{console.log(T.dim(" Running tests...")),o("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...")),o("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${t.user}@${e}:${t.path}...`));try{if(o(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),t.restart){console.log(T.dim(" Restarting remote daemon once no task is running..."));let i=t.identity?`ssh -i ${t.identity}`:"ssh";o(`${i} -t ${t.user}@${e} "cd ${t.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}`))}});Ze.action(async e=>{await new $i(e.config).start()});function Zm(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 vl(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}import{Command as ep}from"commander";import et from"chalk";import{existsSync as pn,readFileSync as tp,writeFileSync as xl,mkdirSync as Sl}from"fs";import{hostname as El}from"os";import{resolve as Eo}from"path";var Al=new ep().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),o=Eo(t,"agentx.json"),n=Eo(t,".env"),s=Eo(t,".agentx/sessions");if(console.log(),console.log(et.bold(" agentx init")),console.log(),pn(o)&&!e.force){console.log(et.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Eo(t,"agentx.example.json"),Eo(t,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(pn(c)){r=tp(c,"utf-8");break}r||(r=JSON.stringify({node:{id:El().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:El(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:t,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)),xl(o,r),console.log(et.green(" \u2713 Created agentx.json")),pn(n)||(xl(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
- `)),console.log(et.green(" \u2713 Created .env template"))),pn(s)||(Sl(s,{recursive:!0}),console.log(et.green(" \u2713 Created .agentx/sessions/")));let a=Eo(t,".claude");pn(a)||(Sl(a,{recursive:!0}),console.log(et.green(" \u2713 Created .claude/"))),console.log(),console.log(et.bold(" Next steps:")),console.log(` 1. Edit ${et.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${et.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${et.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${et.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as op}from"commander";import Yt from"chalk";import{spawn as jl}from"child_process";import{existsSync as np}from"fs";import{dirname as sp,resolve as ip}from"path";import{fileURLToPath as rp}from"url";ie();var Ol=new op().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 t=Hc(),o=e.port?parseInt(e.port,10):ap(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(Yt.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Yt.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Yt.bold(` Opening ${n}`)),console.log(),await lp(n).catch(()=>!1))console.log(Yt.dim(" Dashboard is already running.")),e.open!==!1&&Tl(n);else{console.log(Yt.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=cp(),r=jl(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Tl(n),await new Promise(a=>r.on("exit",()=>a()))}});function ap(){try{return I().dashboard.port||4202}catch{return 4202}}function cp(){let e=ip(sp(rp(import.meta.url)),"cli.js");return np(e)?e:process.argv[1]||e}async function lp(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function Tl(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let o=jl(t,[e],{stdio:"ignore",detached:!0});o.once("error",()=>{console.log(Yt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),o.unref()}catch{console.log(Yt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as dp}from"commander";import Ie from"chalk";var un=new dp().name("token").description("scoped API tokens for external access (mesh peers, integrations)");un.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 t=new Et,o=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}=t.create({name:e.name,scopes:o,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(t){console.log(Ie.red(` ${t.message}`)),process.exit(1)}});un.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Et().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."))}});et.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,t,o)=>{let n=t.join(" ");try{let s=I(o.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;o.peer?(c=`${a}/mesh/task`,l={peer:o.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(T.dim(` Sending to ${o.peer?`${o.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();o.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"))}});et.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,t)=>{let{execSync:o}=await import("child_process"),n=t.identity?`-e "ssh -i ${t.identity}"`:"",s=`${t.user}@${e}:${t.path}/dist/`;if(!t.skipChecks){try{console.log(T.dim(" Running tests...")),o("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...")),o("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${t.user}@${e}:${t.path}...`));try{if(o(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),t.restart){console.log(T.dim(" Restarting remote daemon once no task is running..."));let i=t.identity?`ssh -i ${t.identity}`:"ssh";o(`${i} -t ${t.user}@${e} "cd ${t.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}`))}});et.action(async e=>{await new Si(e.config).start()});function rp(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 Tl(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}import{Command as ap}from"commander";import tt from"chalk";import{existsSync as fn,readFileSync as cp,writeFileSync as jl,mkdirSync as Ol}from"fs";import{hostname as Il}from"os";import{resolve as To}from"path";var Cl=new ap().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),o=To(t,"agentx.json"),n=To(t,".env"),s=To(t,".agentx/sessions");if(console.log(),console.log(tt.bold(" agentx init")),console.log(),fn(o)&&!e.force){console.log(tt.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[To(t,"agentx.example.json"),To(t,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(fn(c)){r=cp(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Il().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Il(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:t,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)),jl(o,r),console.log(tt.green(" \u2713 Created agentx.json")),fn(n)||(jl(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
+ `)),console.log(tt.green(" \u2713 Created .env template"))),fn(s)||(Ol(s,{recursive:!0}),console.log(tt.green(" \u2713 Created .agentx/sessions/")));let a=To(t,".claude");fn(a)||(Ol(a,{recursive:!0}),console.log(tt.green(" \u2713 Created .claude/"))),console.log(),console.log(tt.bold(" Next steps:")),console.log(` 1. Edit ${tt.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${tt.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${tt.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${tt.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as lp}from"commander";import Vt from"chalk";import{spawn as Rl}from"child_process";import{existsSync as dp}from"fs";import{dirname as gp,resolve as mp}from"path";import{fileURLToPath as pp}from"url";ne();var _l=new lp().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 t=Kc(),o=e.port?parseInt(e.port,10):up(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(Vt.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Vt.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Vt.bold(` Opening ${n}`)),console.log(),await hp(n).catch(()=>!1))console.log(Vt.dim(" Dashboard is already running.")),e.open!==!1&&Nl(n);else{console.log(Vt.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=fp(),r=Rl(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Nl(n),await new Promise(a=>r.on("exit",()=>a()))}});function up(){try{return I().dashboard.port||4202}catch{return 4202}}function fp(){let e=mp(gp(pp(import.meta.url)),"cli.js");return dp(e)?e:process.argv[1]||e}async function hp(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function Nl(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let o=Rl(t,[e],{stdio:"ignore",detached:!0});o.once("error",()=>{console.log(Vt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),o.unref()}catch{console.log(Vt.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as yp}from"commander";import Ie from"chalk";var hn=new yp().name("token").description("scoped API tokens for external access (mesh peers, integrations)");hn.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 t=new Tt,o=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}=t.create({name:e.name,scopes:o,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(t){console.log(Ie.red(` ${t.message}`)),process.exit(1)}});hn.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Tt().list();if(e.length===0){console.log(Ie.dim(`
17
17
  No tokens issued.
18
- `));return}console.log();for(let t of e){let o=t.revokedAt?Ie.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?Ie.red("expired"):Ie.green("active");console.log(` ${Ie.cyan(t.id)} ${o} ${t.name}`),console.log(Ie.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(Ie.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ie.red(` ${e.message}`)),process.exit(1)}});un.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Et().revoke(e);t||(console.log(Ie.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ie.green(`
18
+ `));return}console.log();for(let t of e){let o=t.revokedAt?Ie.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?Ie.red("expired"):Ie.green("active");console.log(` ${Ie.cyan(t.id)} ${o} ${t.name}`),console.log(Ie.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(Ie.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ie.red(` ${e.message}`)),process.exit(1)}});hn.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Tt().revoke(e);t||(console.log(Ie.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ie.green(`
19
19
  \u2713 Revoked ${e} (${t.name})
20
- `))}catch(t){console.log(Ie.red(` ${t.message}`)),process.exit(1)}});import{Command as gp}from"commander";import Ee from"chalk";import{execFileSync as Cl}from"child_process";import{existsSync as Il}from"fs";ie();var Ao=new gp().name("app").description("pair phones with the AgentX phone app and manage paired devices");Ao.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 t=fp(hp(),Ii());if(t.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${t.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:${Ii()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${Ii()}/api/app`].join(`
21
- `));let o=(e.url?String(e.url):pp()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(o))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${o}`);let{token:n,record:s}=new Et().create({name:String(e.name),scopes:["app"]}),{code:i}=new Yc().create({token:n,tokenId:s.id,name:s.name}),r=`${o}/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 mp({code:i,origin:o,deviceId:s.id,deviceName:s.name}))console.log(c);!Il("agentx.json")&&!Il(".agentx/config.json")&&console.log(Ee.yellow(" \u26A0 No agentx.json here. The dashboard only accepts phones paired from the folder that holds agentx.json.")),console.log()}catch(t){console.log(Ee.red(` ${t.message}`)),process.exit(1)}});Ao.command("devices").description("list paired phones").action(()=>{let e=new Et().list().filter(t=>t.scopes.includes("app"));if(e.length===0){console.log(Ee.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let t of e){let o=t.revokedAt?Ee.red("revoked"):Ee.green("active");console.log(` ${Ee.cyan(t.id)} ${o} ${t.name}`),console.log(Ee.dim(` paired: ${t.createdAt}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()});Ao.command("revoke <id>").description("unpair a phone immediately").action(e=>{let t=new Et,o=t.list().find(n=>n.id===e&&n.scopes.includes("app"));o||(console.log(Ee.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),t.revoke(e),console.log(Ee.green(`
20
+ `))}catch(t){console.log(Ie.red(` ${t.message}`)),process.exit(1)}});import{Command as wp}from"commander";import Ee from"chalk";import{execFileSync as Pl}from"child_process";import{existsSync as Dl}from"fs";ne();var jo=new wp().name("app").description("pair phones with the AgentX phone app and manage paired devices");jo.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 t=vp(xp(),_i());if(t.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${t.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 o=(e.url?String(e.url):$p()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(o))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${o}`);let{token:n,record:s}=new Tt().create({name:String(e.name),scopes:["app"]}),{code:i}=new Zc().create({token:n,tokenId:s.id,name:s.name}),r=`${o}/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 bp({code:i,origin:o,deviceId:s.id,deviceName:s.name}))console.log(c);!Dl("agentx.json")&&!Dl(".agentx/config.json")&&console.log(Ee.yellow(" \u26A0 No agentx.json here. The dashboard only accepts phones paired from the folder that holds agentx.json.")),console.log()}catch(t){console.log(Ee.red(` ${t.message}`)),process.exit(1)}});jo.command("devices").description("list paired phones").action(()=>{let e=new Tt().list().filter(t=>t.scopes.includes("app"));if(e.length===0){console.log(Ee.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let t of e){let o=t.revokedAt?Ee.red("revoked"):Ee.green("active");console.log(` ${Ee.cyan(t.id)} ${o} ${t.name}`),console.log(Ee.dim(` paired: ${t.createdAt}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()});jo.command("revoke <id>").description("unpair a phone immediately").action(e=>{let t=new Tt,o=t.list().find(n=>n.id===e&&n.scopes.includes("app"));o||(console.log(Ee.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),t.revoke(e),console.log(Ee.green(`
22
22
  \u2713 Unpaired ${e} (${o.name})
23
- `))});Ao.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 t=tc;try{t=I().channels.push.keysFile}catch{}let o=oc(t),n=nc(o);if(n&&!e.force){console.log(Ee.green(`
23
+ `))});jo.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 t=ic;try{t=I().channels.push.keysFile}catch{}let o=rc(t),n=ac(o);if(n&&!e.force){console.log(Ee.green(`
24
24
  \u2713 Keys already exist in ${o} (created ${n.createdAt}).`)),console.log(Ee.dim(` Replacing them cuts off every phone; pass --force if you really mean to.
25
- `));return}let{default:s}=await import("web-push");sc(o,s.generateVAPIDKeys()),console.log(Ee.green(`
25
+ `));return}let{default:s}=await import("web-push");cc(o,s.generateVAPIDKeys()),console.log(Ee.green(`
26
26
  \u2713 Saved new push keys to ${o}`)),console.log(Ee.dim(" Keep this file private. It is readable only by you, and agentx.json never contains it.")),n&&console.log(Ee.yellow(" \u26A0 Old keys replaced: open Alerts on each phone and turn notifications on again.")),console.log(Ee.dim(` Restart the daemon so it picks up the keys.
27
- `))});function mp(e){let t=Math.round(Gc/6e4),o=[` Pairing code: ${Ee.bold.cyan(zc(e.code))}`,Ee.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Ee.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Ee.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||o.push(Ee.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function pp(){let e;try{e=JSON.parse(Cl("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 t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var up=new Set(["/app","/api/app"]);function fp(e,t){let o=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of o)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])===t&&!up.has(g)&&n.push(`${i}${a}`)}return n}function hp(){try{return JSON.parse(Cl("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Ii(){try{return I().dashboard.port||4202}catch{return 4202}}ie();import{Command as gt}from"commander";import y from"chalk";import _e from"prompts";import{readFileSync as jt,writeFileSync as To,existsSync as fe,mkdirSync as dt,cpSync as Ci,readdirSync as Ri}from"fs";import{resolve as H,join as Tt,dirname as yp}from"path";import{fileURLToPath as wp}from"url";function le(){let e=H(process.cwd(),"agentx.json");if(!fe(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(jt(e,"utf-8"))}function Ue(e){return ye(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(y.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var Vt=new gt().name("agent").description("manage agents \u2014 add, list, remove");Vt.command("list").alias("ls").description("list configured agents").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${y.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(y.dim(` workspace: ${o.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});Vt.command("add").description("add a new agent interactively").action(async()=>{let e=le(),t=await _e([{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(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:Tt(t.workspace,t.id);dt(H(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(t.id,n,"19900",(...l)=>{console.log(y.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(yp(wp(import.meta.url)),"../wiki/SKILL.md"),c=fe(r)?r:a;fe(c)&&(dt(H(o,".claude/skills/wiki"),{recursive:!0}),Ci(c,H(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await Ue(e),console.log(y.green(`
28
- Agent "${t.id}" added`)),console.log(y.dim(` Workspace: ${o}`)),console.log(y.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Vt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=le();if(!t.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete t.agents[e],await Ue(t),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});Vt.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,t)=>{let o=le(),n=o.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let i=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(y.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(t.contextReferences!==void 0){let i=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(y.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(y.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let i=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Ue(o),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var fn=new gt().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");fn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=le().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(t.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(y.dim(`
27
+ `))});function bp(e){let t=Math.round(Xc/6e4),o=[` Pairing code: ${Ee.bold.cyan(Qc(e.code))}`,Ee.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Ee.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Ee.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||o.push(Ee.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function $p(){let e;try{e=JSON.parse(Pl("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 t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var kp=new Set(["/app","/api/app"]);function vp(e,t){let o=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of o)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])===t&&!kp.has(g)&&n.push(`${i}${a}`)}return n}function xp(){try{return JSON.parse(Pl("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function _i(){try{return I().dashboard.port||4202}catch{return 4202}}ne();import{Command as mt}from"commander";import y from"chalk";import De from"prompts";import{readFileSync as It,writeFileSync as Oo,existsSync as he,mkdirSync as gt,cpSync as Di,readdirSync as Mi}from"fs";import{resolve as H,join as Ot,dirname as Sp}from"path";import{fileURLToPath as Ep}from"url";function le(){let e=H(process.cwd(),"agentx.json");if(!he(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(It(e,"utf-8"))}function qe(e){return pe(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(y.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var Kt=new mt().name("agent").description("manage agents \u2014 add, list, remove");Kt.command("list").alias("ls").description("list configured agents").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${y.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(y.dim(` workspace: ${o.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});Kt.command("add").description("add a new agent interactively").action(async()=>{let e=le(),t=await De([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:H(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:Ot(t.workspace,t.id);gt(H(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(t.id,n,"19900",(...l)=>{console.log(y.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(Sp(Ep(import.meta.url)),"../wiki/SKILL.md"),c=he(r)?r:a;he(c)&&(gt(H(o,".claude/skills/wiki"),{recursive:!0}),Di(c,H(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await qe(e),console.log(y.green(`
28
+ Agent "${t.id}" added`)),console.log(y.dim(` Workspace: ${o}`)),console.log(y.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Kt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=le();if(!t.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete t.agents[e],await qe(t),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});Kt.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,t)=>{let o=le(),n=o.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let i=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(y.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(t.contextReferences!==void 0){let i=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(y.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(y.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let i=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await qe(o),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var yn=new mt().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");yn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=le().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(t.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(y.dim(`
29
29
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
30
- `));return}console.log(),console.log(y.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?y.cyan(i.kind.padEnd(14)):y.dim(i.kind.padEnd(14))} ${y.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),r||console.log(` ${y.dim("(disabled)")}`)}console.log()});fn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,t)=>{let o=le();o.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-X7BHZ75G.js"),i=String(t.kind||"").trim();!i&&n&&(i=((await _e({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(y.red(" --kind is required")),process.exit(1));let r=String(t.label||"").trim();!r&&n&&(r=((await _e({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(y.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await _e({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 _e({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 _e({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let u of String(t.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await _e({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...h]=f.split("=");p&&(g[p.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(y.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(y.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Ue(o),console.log(y.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});fn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=le(),n=o.agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===t);a===-1&&(console.log(y.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await Ue(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});fn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=le().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!i.length){console.log(y.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Vt.addCommand(fn);var ms=new gt().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");ms.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=le();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(y.bold(" Telegram:"));for(let[s,i]of Object.entries(t.accounts||{}))console.log(` ${y.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});ms.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=le(),t=Object.keys(e.agents||{});if(!t.length){console.log(y.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await _e({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 _e([{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:o}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(y.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(y.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Ue(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await _e([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{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 _e([{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:o},{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 Ue(e),dt(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await _e([{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 _e([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{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 Ue(e),console.log(y.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var jo=new gt().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");jo.command("list").alias("ls").description("list cron jobs").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(y.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});jo.command("add").description("add a cron job").action(async()=>{let e=le(),t=Object.keys(e.agents||{}),o=await _e([{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:t.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}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await Ue(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});jo.command("enable <id>").description("enable a cron job").action(async e=>{let t=le();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await Ue(t),console.log(y.green(` Cron "${e}" enabled`))});jo.command("disable <id>").description("disable a cron job").action(async e=>{let t=le();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await Ue(t),console.log(y.green(` Cron "${e}" disabled`))});var Kt=new gt().name("mesh").description("manage mesh peers \u2014 add, list, remove");Kt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=le();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=y.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(t.name)} ${y.dim(t.url)} ${o}`)}}console.log()});Kt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=le(),t=await _e([{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(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await Ue(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Kt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=le();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await Ue(t),console.log(y.green(` Peer "${e}" removed`)))});Kt.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 t=le();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(y.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(y.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Ue(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Kt.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,t)=>{let o=t.node||"";if(!o)try{o=I().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(y.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+y.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(y.red(` Could not reach the daemon at ${o}: ${i?.message||i}`)),process.exit(1)}});var Xt=new gt().name("skill").description("manage skills \u2014 add to agent(s), list");Xt.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,t)=>{let o=le(),n=H(e);if(!fe(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=fe(Tt(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(t.all)i=Object.keys(o.agents||{});else if(t.agent)i=t.agent;else{let r=Object.keys(o.agents||{});i=(await _e({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=o.agents[r];if(!a){console.log(y.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);dt(c,{recursive:!0}),fe(Tt(n,"SKILL.md"))?Ci(n,c,{recursive:!0}):n.endsWith(".md")&&Ci(n,Tt(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Xt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=H(o.workspace,".claude/skills"),s=fe(n)?Ri(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(t)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});Xt.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,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>fe(k));if(!i){console.log(y.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(y.dim(` ${k}`));return}let r=jt(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=I()}catch(k){console.log(y.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([k])=>k===t.agent):g;if(d.length===0){console.log(y.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${i}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,h=0;for(let[k,$]of d){let b=$.workspace;if(!b||!fe(b)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+(b||"undefined")+")")}`),h++;continue}let E=H(b,".claude/skills",e),S=H(E,"SKILL.md");if(!fe(S)){if(!t.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(dt(E,{recursive:!0}),To(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=jt(S,"utf-8");if(o("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${k.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||To(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=t.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),t.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Xt.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:t}=await import("./loader-YFVSSYSL.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=le().agents?.[e.workspace];f||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=le();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>t(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=o({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?y.green("PASS "):f.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${p} ${y.bold(f.name)}${f.skill?.path?y.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${u.PASS} PASS`)} ${y.yellow(`${u.REVIEW} REVIEW`)} ${y.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});Xt.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,t)=>{let o=le(),n=Object.entries(o.agents||{}),[s,i]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];i||(console.log(y.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-N6CIZF2S.js"),c=await r(i.workspace);if(c.length===0){console.log(y.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(t.min)||.6});if(t.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
30
+ `));return}console.log(),console.log(y.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?y.cyan(i.kind.padEnd(14)):y.dim(i.kind.padEnd(14))} ${y.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),r||console.log(` ${y.dim("(disabled)")}`)}console.log()});yn.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,t)=>{let o=le();o.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-6UXC7MPC.js"),i=String(t.kind||"").trim();!i&&n&&(i=((await De({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(y.red(" --kind is required")),process.exit(1));let r=String(t.label||"").trim();!r&&n&&(r=((await De({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(y.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await De({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await De({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await De({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let u of String(t.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await De({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...h]=f.split("=");p&&(g[p.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(y.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(y.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await qe(o),console.log(y.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});yn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=le(),n=o.agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===t);a===-1&&(console.log(y.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await qe(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});yn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=le().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!i.length){console.log(y.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Kt.addCommand(yn);var hs=new mt().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");hs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=le();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(y.bold(" Telegram:"));for(let[s,i]of Object.entries(t.accounts||{}))console.log(` ${y.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});hs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=le(),t=Object.keys(e.agents||{});if(!t.length){console.log(y.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await De({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await De([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(y.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(y.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await qe(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await De([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await De([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await qe(e),gt(H(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await De([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await De([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await qe(e),console.log(y.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Io=new mt().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Io.command("list").alias("ls").description("list cron jobs").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(y.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});Io.command("add").description("add a cron job").action(async()=>{let e=le(),t=Object.keys(e.agents||{}),o=await De([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.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}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await qe(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});Io.command("enable <id>").description("enable a cron job").action(async e=>{let t=le();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await qe(t),console.log(y.green(` Cron "${e}" enabled`))});Io.command("disable <id>").description("disable a cron job").action(async e=>{let t=le();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await qe(t),console.log(y.green(` Cron "${e}" disabled`))});var Xt=new mt().name("mesh").description("manage mesh peers \u2014 add, list, remove");Xt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=le();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=y.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(t.name)} ${y.dim(t.url)} ${o}`)}}console.log()});Xt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=le(),t=await De([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await qe(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Xt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=le();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await qe(t),console.log(y.green(` Peer "${e}" removed`)))});Xt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=le();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(y.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(y.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await qe(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Xt.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,t)=>{let o=t.node||"";if(!o)try{o=I().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(y.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+y.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(y.red(` Could not reach the daemon at ${o}: ${i?.message||i}`)),process.exit(1)}});var Qt=new mt().name("skill").description("manage skills \u2014 add to agent(s), list");Qt.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,t)=>{let o=le(),n=H(e);if(!he(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=he(Ot(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(t.all)i=Object.keys(o.agents||{});else if(t.agent)i=t.agent;else{let r=Object.keys(o.agents||{});i=(await De({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=o.agents[r];if(!a){console.log(y.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);gt(c,{recursive:!0}),he(Ot(n,"SKILL.md"))?Di(n,c,{recursive:!0}):n.endsWith(".md")&&Di(n,Ot(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Qt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=le();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=H(o.workspace,".claude/skills"),s=he(n)?Mi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(t)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});Qt.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,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>he(k));if(!i){console.log(y.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(y.dim(` ${k}`));return}let r=It(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=I()}catch(k){console.log(y.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([k])=>k===t.agent):g;if(d.length===0){console.log(y.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${i}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,h=0;for(let[k,$]of d){let b=$.workspace;if(!b||!he(b)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+(b||"undefined")+")")}`),h++;continue}let E=H(b,".claude/skills",e),S=H(E,"SKILL.md");if(!he(S)){if(!t.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(gt(E,{recursive:!0}),Oo(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=It(S,"utf-8");if(o("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${k.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Oo(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=t.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),t.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Qt.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:t}=await import("./loader-YFVSSYSL.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=le().agents?.[e.workspace];f||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=le();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>t(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=o({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?y.green("PASS "):f.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${p} ${y.bold(f.name)}${f.skill?.path?y.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${u.PASS} PASS`)} ${y.yellow(`${u.REVIEW} REVIEW`)} ${y.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});Qt.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,t)=>{let o=le(),n=Object.entries(o.agents||{}),[s,i]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];i||(console.log(y.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-GIDPNJAA.js"),c=await r(i.workspace);if(c.length===0){console.log(y.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(t.min)||.6});if(t.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
31
31
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(y.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(y.dim(`
32
- (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var hn=new gt().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");hn.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,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=H(t.cwd),n=H(o,"references/example"),s=H(o,"references/recipes/example.yaml");fe(n)||(console.log(y.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(o,".agentx/references",e),r=H(o,".agentx/references/recipes");dt(i,{recursive:!0}),dt(r,{recursive:!0});let a=Ri(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Tt(i,d);if(fe(u)&&!t.force){console.log(y.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=jt(Tt(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);To(u,p),console.log(y.green(` + ${u}`)),c++}let g=Tt(r,`${e}.yaml`);if(fe(g)&&!t.force)console.log(y.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(fe(s)){let d=jt(s,"utf-8").replaceAll("example.",`${e}.`);To(g,d),console.log(y.green(` + ${g}`)),c++}console.log(),console.log(y.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(y.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(y.dim(" 2. agentx skill audit # verify references resolve")),console.log(y.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});hn.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,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(t.cwd),r=t.from?String(t.from).split(",").map(h=>h.trim()).filter(Boolean):[e],a=await o(i),c=n(a,{namespace:e,filter:r,gitlabHost:t.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(y.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(y.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(y.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,w])=>[h,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(t.referencesCwd||t.cwd),u=H(d,".agentx/references",e);if(!t.write){console.log(),console.log(y.dim(` Dry-run \u2014 would write to ${u}/`));for(let[h,w]of Object.entries(g))console.log(y.cyan(`
32
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var wn=new mt().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");wn.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=H(t.cwd),n=H(o,"references/example"),s=H(o,"references/recipes/example.yaml");he(n)||(console.log(y.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(o,".agentx/references",e),r=H(o,".agentx/references/recipes");gt(i,{recursive:!0}),gt(r,{recursive:!0});let a=Mi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Ot(i,d);if(he(u)&&!t.force){console.log(y.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=It(Ot(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Oo(u,p),console.log(y.green(` + ${u}`)),c++}let g=Ot(r,`${e}.yaml`);if(he(g)&&!t.force)console.log(y.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(he(s)){let d=It(s,"utf-8").replaceAll("example.",`${e}.`);Oo(g,d),console.log(y.green(` + ${g}`)),c++}console.log(),console.log(y.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(y.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(y.dim(" 2. agentx skill audit # verify references resolve")),console.log(y.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});wn.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(t.cwd),r=t.from?String(t.from).split(",").map(h=>h.trim()).filter(Boolean):[e],a=await o(i),c=n(a,{namespace:e,filter:r,gitlabHost:t.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(y.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(y.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(y.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,w])=>[h,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(t.referencesCwd||t.cwd),u=H(d,".agentx/references",e);if(!t.write){console.log(),console.log(y.dim(` Dry-run \u2014 would write to ${u}/`));for(let[h,w]of Object.entries(g))console.log(y.cyan(`
33
33
  --- ${h} ---`)),console.log(w.split(`
34
34
  `).slice(0,30).map(k=>` ${k}`).join(`
35
35
  `)),w.split(`
36
36
  `).length>30&&console.log(y.dim(` \u2026 (${w.split(`
37
- `).length-30} more lines truncated in preview)`));console.log(),console.log(y.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}dt(u,{recursive:!0});let f=0,p=0;for(let[h,w]of Object.entries(g)){let k=Tt(u,h);if(fe(k)&&!t.force){console.log(y.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}To(k,w),console.log(y.green(` + ${k}`)),f++}console.log(),console.log(y.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(y.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});hn.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:t}=await import("./loader-KKMG24O5.js"),o=await t(H(e.cwd)),n=[...o.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(y.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=o.sourceById.get(s.id);console.log(` ${y.cyan(s.id)} ${y.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(y.dim(` ${i}`))}console.log(),console.log(y.dim(` ${n.length} reference(s) loaded.`)),console.log()});var _i=new gt().name("hook").description("manage hooks \u2014 add to agent workspace");_i.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=le().agents?.[e];if(!o){console.log(y.red(` Agent "${e}" not found`));return}let n=H(o.workspace,".claude/settings.json"),s=fe(n)?JSON.parse(jt(n,"utf-8")):{},i=await _e([{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),dt(H(o.workspace,".claude"),{recursive:!0}),To(n,JSON.stringify(s,null,2)),console.log(y.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Di=new gt().name("migrate").description("import configuration from OpenClaw or other tools");Di.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,t)=>{let o=[e,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&fe(f)){n=f;break}if(!n){console.log(y.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(y.dim(` Reading: ${n}`));let s=JSON.parse(jt(n,"utf-8")),i=fe(H(process.cwd(),"agentx.json"))?le():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(w=>w===p)||h.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){dt(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-42ARC42I.js");w(p,i.agents[p])}}console.log(` ${y.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let w=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:w},i.channels.telegram.enabled=!0,d++}console.log(` ${y.green(d)} Telegram accounts imported`);let u=H(n,"../cron/jobs.json");if(fe(u)){let f=JSON.parse(jt(u,"utf-8")),p=0;for(let h of f.jobs||[]){let w=h.name||h.id,k=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:k,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${y.green(p)} cron jobs imported`)}t.dryRun?(console.log(y.yellow(`
38
- Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Ue(i),console.log(y.green(`
39
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ot=new gt().name("config").description("validate and inspect configuration");Ot.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 t=I(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(y.dim(` Bind: ${t.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(y.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Un(t);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(t.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"))?Ri(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(y.red(` \u2717 ${t.message}`))}console.log()});Ot.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=I(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(y.red(t.message))}});function bp(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Ni(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ot.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,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-R2KBGTZJ.js"),{expandEnvVars:r}=await import("./config-X7BHZ75G.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:r(c),g=i(l,e);t.json?console.log(JSON.stringify(g)):console.log(Ni(g))});Ot.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,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-R2KBGTZJ.js"),r=bp(t,!!o.string),a=await n(l=>{s(l,e,r)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${Ni(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${Ni(c)}`)),a.reloaded?console.log(y.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(y.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Ot.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,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-R2KBGTZJ.js"),i=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(i.success||(console.log(y.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),i.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});Ot.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 t=!1,o=0,n;try{let d=I(e.config);t=!!d.business?.enabled,o=(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&&t,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):r?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${t?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${o}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as $p}from"commander";import It from"chalk";import{resolve as Ct}from"path";import{existsSync as kp}from"fs";var yt=new $p().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Qt(e){let t=Ct(e,".agentx/db.sqlite");kp(t)||(console.log(It.red(` No SQLite at ${t}`)),console.log(It.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=na({path:t});return o||(console.log(It.red(` Could not open ${t}`)),console.log(It.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Zt(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(It.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}yt.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 t=Qt(Ct(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
37
+ `).length-30} more lines truncated in preview)`));console.log(),console.log(y.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}gt(u,{recursive:!0});let f=0,p=0;for(let[h,w]of Object.entries(g)){let k=Ot(u,h);if(he(k)&&!t.force){console.log(y.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}Oo(k,w),console.log(y.green(` + ${k}`)),f++}console.log(),console.log(y.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(y.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});wn.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:t}=await import("./loader-KKMG24O5.js"),o=await t(H(e.cwd)),n=[...o.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(y.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=o.sourceById.get(s.id);console.log(` ${y.cyan(s.id)} ${y.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(y.dim(` ${i}`))}console.log(),console.log(y.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Li=new mt().name("hook").description("manage hooks \u2014 add to agent workspace");Li.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=le().agents?.[e];if(!o){console.log(y.red(` Agent "${e}" not found`));return}let n=H(o.workspace,".claude/settings.json"),s=he(n)?JSON.parse(It(n,"utf-8")):{},i=await De([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),gt(H(o.workspace,".claude"),{recursive:!0}),Oo(n,JSON.stringify(s,null,2)),console.log(y.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Fi=new mt().name("migrate").description("import configuration from OpenClaw or other tools");Fi.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,t)=>{let o=[e,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&he(f)){n=f;break}if(!n){console.log(y.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(y.dim(` Reading: ${n}`));let s=JSON.parse(It(n,"utf-8")),i=he(H(process.cwd(),"agentx.json"))?le():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(w=>w===p)||h.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){gt(H(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-42ARC42I.js");w(p,i.agents[p])}}console.log(` ${y.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let w=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:w},i.channels.telegram.enabled=!0,d++}console.log(` ${y.green(d)} Telegram accounts imported`);let u=H(n,"../cron/jobs.json");if(he(u)){let f=JSON.parse(It(u,"utf-8")),p=0;for(let h of f.jobs||[]){let w=h.name||h.id,k=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:k,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${y.green(p)} cron jobs imported`)}t.dryRun?(console.log(y.yellow(`
38
+ Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await qe(i),console.log(y.green(`
39
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ct=new mt().name("config").description("validate and inspect configuration");Ct.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 t=I(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(y.dim(` Bind: ${t.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(y.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Bn(t);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(t.agents)){let r=i.workspace,a=he(H(r,".claude")),c=he(H(r,"CLAUDE.md")),l=he(H(r,".claude/settings.json")),g=he(H(r,".claude/skills"))?Mi(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(y.red(` \u2717 ${t.message}`))}console.log()});Ct.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=I(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(y.red(t.message))}});function Ap(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Pi(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ct.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,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-QNTAKNI7.js"),{expandEnvVars:r}=await import("./config-6UXC7MPC.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:r(c),g=i(l,e);t.json?console.log(JSON.stringify(g)):console.log(Pi(g))});Ct.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,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-QNTAKNI7.js"),r=Ap(t,!!o.string),a=await n(l=>{s(l,e,r)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${Pi(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${Pi(c)}`)),a.reloaded?console.log(y.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(y.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Ct.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,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-QNTAKNI7.js"),i=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(i.success||(console.log(y.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),i.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});Ct.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 t=!1,o=0,n;try{let d=I(e.config);t=!!d.business?.enabled,o=(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&&t,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):r?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${t?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${o}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Tp}from"commander";import Nt from"chalk";import{resolve as Rt}from"path";import{existsSync as jp}from"fs";var wt=new Tp().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Zt(e){let t=Rt(e,".agentx/db.sqlite");jp(t)||(console.log(Nt.red(` No SQLite at ${t}`)),console.log(Nt.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=Jn({path:t});return o||(console.log(Nt.red(` Could not open ${t}`)),console.log(Nt.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function eo(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Nt.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}wt.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 t=Zt(Rt(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.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
  ${o.length?"WHERE "+o.join(" AND "):""}
46
46
  ORDER BY started_at DESC
47
47
  LIMIT @limit
48
- `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Zt(i,!!e.json)});yt.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 t=Qt(Ct(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(o.push("reason = @reason"),n.reason=e.reason);let s=o.length?"WHERE "+o.join(" AND "):"",i=e.summary?`
48
+ `,i=t.prepare(s).all({...n,limit:Number(e.limit)});eo(i,!!e.json)});wt.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 t=Zt(Rt(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(o.push("reason = @reason"),n.reason=e.reason);let s=o.length?"WHERE "+o.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=t.prepare(i).all({...n,limit:Number(e.limit)});Zt(r,!!e.json)});yt.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 t=Qt(Ct(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("day = @day"),n.day=e.day);let s=`
62
+ `,r=t.prepare(i).all({...n,limit:Number(e.limit)});eo(r,!!e.json)});wt.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 t=Zt(Rt(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.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
  ${o.length?"WHERE "+o.join(" AND "):""}
68
68
  ORDER BY day DESC, agent_id
69
- `,i=t.prepare(s).all(n);Zt(i,!!e.json)});yt.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 t=Qt(Ct(e.cwd)),o=[],n={};e.channel&&(o.push("channel = @channel"),n.channel=e.channel),e.kind&&(o.push("kind = @kind"),n.kind=e.kind);let s=o.length?"WHERE "+o.join(" AND "):"",i=e.summary?`
69
+ `,i=t.prepare(s).all(n);eo(i,!!e.json)});wt.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 t=Zt(Rt(e.cwd)),o=[],n={};e.channel&&(o.push("channel = @channel"),n.channel=e.channel),e.kind&&(o.push("kind = @kind"),n.kind=e.kind);let s=o.length?"WHERE "+o.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=t.prepare(i).all({...n,limit:Number(e.limit)});Zt(r,!!e.json)});yt.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 t=Qt(Ct(e.cwd)),o=["status = 'error'"],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent);let s=`
82
+ `,r=t.prepare(i).all({...n,limit:Number(e.limit)});eo(r,!!e.json)});wt.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 t=Zt(Rt(e.cwd)),o=["status = 'error'"],n={};e.agent&&(o.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 ${o.join(" AND ")}
88
88
  ORDER BY started_at DESC
89
89
  LIMIT @limit
90
- `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Zt(i,!!e.json)});yt.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let t=Qt(Ct(e.cwd)),n=t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:t.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Zt(n,!!e.json)});yt.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,t)=>{let o=Qt(Ct(t.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(It.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(It.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=o.prepare(e).all();Zt(n,!!t.json)}catch(n){console.log(It.red(` ${n.message}`)),process.exit(1)}});import{Command as Sp}from"commander";import z from"chalk";import{mkdtempSync as Ep}from"fs";import{tmpdir as Ap}from"os";import{resolve as Rl,join as _l}from"path";import{existsSync as Tp}from"fs";import jp from"better-sqlite3";function Nl(e,t,o,n=[]){let s=new Map;for(let c of t)s.set(c.id,c);let i=[];for(let c of o)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=vp(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=fa(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:xp(l,f)})}return{eventsCount:t.length,decisionsCount:a,divergences:r,skipped:[]}}function vp(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function xp(e,t){return e.outcome==="dispatched"&&t.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&t.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!==t.agentId?`agent-changed (recorded=${e.agentId} replayed=${t.agentId})`:e.outcome!==t.outcome?`outcome-changed (recorded=${e.outcome} replayed=${t.outcome})`:"unknown"}var Nt=new Sp().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Oo(e){let t=Rl(e.cwd??process.cwd()),o=Rl(t,e.path??".agentx/intent/ledger.sqlite");Tp(o)||(console.log(z.red(` No ledger at ${o}`)),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 jp(o,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${o}: ${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 eo(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}function Op(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function ps(e){if(!e)return;let t=Op(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}Nt.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 t=Oo(e),o=ps(e.since),n=o!==void 0?"WHERE ts >= @since":"",s=o!==void 0?"WHERE decided_at >= @since":"",i=n,r=t.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:o}),a=t.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:o}).n,c=t.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:o}),l=t.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:o}).n,g=t.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:o}),d=t.prepare(`
90
+ `,i=t.prepare(s).all({...n,limit:Number(e.limit)});eo(i,!!e.json)});wt.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let t=Zt(Rt(e.cwd)),n=t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:t.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));eo(n,!!e.json)});wt.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,t)=>{let o=Zt(Rt(t.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Nt.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Nt.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=o.prepare(e).all();eo(n,!!t.json)}catch(n){console.log(Nt.red(` ${n.message}`)),process.exit(1)}});import{Command as Cp}from"commander";import z from"chalk";import{mkdtempSync as Np}from"fs";import{tmpdir as Rp}from"os";import{resolve as Ll,join as Fl}from"path";import{existsSync as _p}from"fs";import Dp from"better-sqlite3";function Ml(e,t,o,n=[]){let s=new Map;for(let c of t)s.set(c.id,c);let i=[];for(let c of o)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=Op(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=ba(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:Ip(l,f)})}return{eventsCount:t.length,decisionsCount:a,divergences:r,skipped:[]}}function Op(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Ip(e,t){return e.outcome==="dispatched"&&t.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&t.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!==t.agentId?`agent-changed (recorded=${e.agentId} replayed=${t.agentId})`:e.outcome!==t.outcome?`outcome-changed (recorded=${e.outcome} replayed=${t.outcome})`:"unknown"}var _t=new Cp().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Co(e){let t=Ll(e.cwd??process.cwd()),o=Ll(t,e.path??".agentx/intent/ledger.sqlite");_p(o)||(console.log(z.red(` No ledger at ${o}`)),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 Dp(o,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${o}: ${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 to(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}function Pp(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function ys(e){if(!e)return;let t=Pp(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}_t.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 t=Co(e),o=ys(e.since),n=o!==void 0?"WHERE ts >= @since":"",s=o!==void 0?"WHERE decided_at >= @since":"",i=n,r=t.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:o}),a=t.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:o}).n,c=t.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:o}),l=t.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:o}).n,g=t.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:o}),d=t.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:o??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),eo(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),eo(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),eo(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});Nt.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 t=Oo(e),o=ps(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
95
+ `).get().n;if(e.json){console.log(JSON.stringify({since:o??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),to(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),to(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),to(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});_t.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 t=Co(e),o=ys(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
96
96
  SELECT
97
97
  datetime(ts/1000, 'unixepoch') AS at,
98
98
  source,
@@ -106,7 +106,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
106
106
  ${i}
107
107
  ORDER BY ts DESC
108
108
  LIMIT @limit
109
- `).all(s);eo(r,!!e.json)});Nt.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let t=Oo(e),o=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(o.push("e.source = @source"),n.source=e.source);let s=t.prepare(`
109
+ `).all(s);to(r,!!e.json)});_t.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let t=Co(e),o=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(o.push("e.source = @source"),n.source=e.source);let s=t.prepare(`
110
110
  SELECT
111
111
  datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
112
112
  e.source,
@@ -122,7 +122,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
122
122
  WHERE ${o.join(" AND ")}
123
123
  ORDER BY d.decided_at DESC
124
124
  LIMIT @limit
125
- `).all(n);eo(s,!!e.json)});Nt.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 t=Oo(e),o=ps(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),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
125
+ `).all(n);to(s,!!e.json)});_t.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 t=Co(e),o=ys(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),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
126
126
  SELECT
127
127
  datetime(ts/1000, 'unixepoch') AS at,
128
128
  source,
@@ -133,7 +133,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
133
133
  ${i}
134
134
  ORDER BY ts DESC
135
135
  LIMIT @limit
136
- `).all(s);eo(r,!!e.json)});Nt.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,t)=>{let o=Oo(t),n=null,s=null;if(t.bySubject){let d=e.indexOf(":");d<0&&(console.log(z.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=o.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(z.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(z.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(z.dim(` project: ${n}`)),s&&console.log(z.dim(` subject: ${s}`)),process.exit(1))}let i=o.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
136
+ `).all(s);to(r,!!e.json)});_t.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,t)=>{let o=Co(t),n=null,s=null;if(t.bySubject){let d=e.indexOf(":");d<0&&(console.log(z.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=o.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(z.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(z.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(z.dim(` project: ${n}`)),s&&console.log(z.dim(` subject: ${s}`)),process.exit(1))}let i=o.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
137
137
  FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(z.dim(` (no events for ${n}:${s})`));return}let r=i.map(d=>d.id),a=r.map((d,u)=>`@id${u}`).join(", "),c=Object.fromEntries(r.map((d,u)=>[`id${u}`,d])),l=o.prepare(`
138
138
  SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
139
139
  r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
@@ -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(t.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 h=p.outcome==="dispatched"?z.green(p.outcome):p.outcome==="dropped"?z.dim(p.outcome):z.yellow(p.outcome),w=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 ${h} ${w}${k}`),p.resolution_status){let $=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),b=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${$} ${z.dim(b)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});Nt.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 t=Oo(e),o=ps(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=t.prepare(`
145
+ `).all(c);if(t.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 h=p.outcome==="dispatched"?z.green(p.outcome):p.outcome==="dropped"?z.dim(p.outcome):z.yellow(p.outcome),w=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 ${h} ${w}${k}`),p.resolution_status){let $=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),b=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${$} ${z.dim(b)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});_t.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 t=Co(e),o=ys(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=t.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=Ep(_l(Ap(),"agentx-ledger-replay-")),f=new aa({path:_l(u,"target.sqlite")});try{let p=Nl(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`)),eo(p.divergences.map(h=>({event_id:h.eventId,decided_by:h.decidedBy,recorded:`${h.expected.outcome}/${h.expected.agentId??"-"}`,replayed:`${h.actual.outcome}/${h.actual.agentId??"-"}`,reason:h.reason.slice(0,80)})),!1))}finally{f.close()}});Ur();km();vm();xm();bm();Qr();on();import{Command as Ip}from"commander";import q from"chalk";import{existsSync as Dl}from"fs";import{resolve as Pi}from"path";import Cp from"better-sqlite3";var Be=new Ip().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),tt=".agentx/decisions/decisions.sqlite";function Np(e){return Pi(Pi(e.cwd??process.cwd()),e.path??tt)}function pt(e,t=!1){let o=Np(e);Dl(o)||(console.log(q.red(` No decision store at ${o}`)),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 Fn({path:o,readonly:!t})}catch(n){console.log(q.red(` Could not open ${o}: ${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 mt(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(q.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)));for(let i of e)console.log(s(o.map(r=>i[r])))}function Mi(e){if(!e)return;let t=e.match(/^(\d+)([dhm])$/);if(t){let n=Number(t[1]),s=t[2]==="d"?864e5:t[2]==="h"?36e5:6e4;return Date.now()-n*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}function Li(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Mi(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Be.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",tt).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let t=pt(e),o=Mi(e.since)??0,n=t.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=Np(Fl(Rp(),"agentx-ledger-replay-")),f=new ga({path:Fl(u,"target.sqlite")});try{let p=Ml(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`)),to(p.divergences.map(h=>({event_id:h.eventId,decided_by:h.decidedBy,recorded:`${h.expected.outcome}/${h.expected.agentId??"-"}`,replayed:`${h.actual.outcome}/${h.actual.agentId??"-"}`,reason:h.reason.slice(0,80)})),!1))}finally{f.close()}});Hr();jm();Om();Im();Am();na();sn();import{Command as Mp}from"commander";import q from"chalk";import{existsSync as Ul}from"fs";import{resolve as Ui}from"path";import Lp from"better-sqlite3";var Je=new Mp().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),ot=".agentx/decisions/decisions.sqlite";function Fp(e){return Ui(Ui(e.cwd??process.cwd()),e.path??ot)}function ut(e,t=!1){let o=Fp(e);Ul(o)||(console.log(q.red(` No decision store at ${o}`)),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 Wn({path:o,readonly:!t})}catch(n){console.log(q.red(` Could not open ${o}: ${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 pt(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(q.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)));for(let i of e)console.log(s(o.map(r=>i[r])))}function qi(e){if(!e)return;let t=e.match(/^(\d+)([dhm])$/);if(t){let n=Number(t[1]),s=t[2]==="d"?864e5:t[2]==="h"?36e5:6e4;return Date.now()-n*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}function Wi(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:qi(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Je.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",ot).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let t=ut(e),o=qi(e.since)??0,n=t.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,
@@ -166,16 +166,16 @@ The AgentX daemon and a speech transcription backend must also be available. Run
166
166
  FROM decision_calls
167
167
  WHERE ts >= ?
168
168
  GROUP BY seat, mode, backend, model, structure_mode
169
- ORDER BY calls DESC`).all(o);mt(n,e.json);let s=t.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
169
+ ORDER BY calls DESC`).all(o);pt(n,e.json);let s=t.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
170
170
  FROM decision_calls WHERE ts >= ? GROUP BY seat, mode, action, explored
171
171
  ORDER BY calls DESC`).all(o);!e.json&&s.length>0&&(console.log(q.bold(`
172
- policy`)),mt(s,!1),console.log(q.dim(`
172
+ policy`)),pt(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.`))),t.close()});Be.command("calls").description("recent calls").option("--path <file>","store path",tt).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let t=pt(e),o=["ts >= ?"],n=[Mi(e.since)??0];e.seat&&(o.push("seat = ?"),n.push(e.seat));let s=t.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.`))),t.close()});Je.command("calls").description("recent calls").option("--path <file>","store path",ot).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let t=ut(e),o=["ts >= ?"],n=[qi(e.since)??0];e.seat&&(o.push("seat = ?"),n.push(e.seat));let s=t.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 ${o.join(" AND ")}
177
- ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));mt(s,e.json),t.close()});Be.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",tt).option("--json").action((e,t)=>{let o=pt(t),n=o.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(q.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),o.close();return}mt(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),t.json),o.close()});Be.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",tt).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,t,o,n)=>{let s=pt(n,!0);s.label(e,t,o,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(q.green(` labeled ${e}.${t} = ${o}`)),s.close()});Be.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",tt).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let t=pt(e),o=t.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));mt(o.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),t.close()});Be.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",tt).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let t=pt(e,!0),o=Pi(process.cwd(),e.db);Dl(o)||(console.log(q.red(` No observability db at ${o}`)),t.close(),process.exit(1));let n=new Cp(o,{readonly:!0});try{let s=_a(n,t);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(),t.close()}});Be.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",tt).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 t=pt(e),o=t.gradedRows(Li(e)),n=Yr(o,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),t.close();return}if(console.log(q.bold(`
177
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));pt(s,e.json),t.close()});Je.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",ot).option("--json").action((e,t)=>{let o=ut(t),n=o.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(q.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),o.close();return}pt(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),t.json),o.close()});Je.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",ot).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,t,o,n)=>{let s=ut(n,!0);s.label(e,t,o,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(q.green(` labeled ${e}.${t} = ${o}`)),s.close()});Je.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",ot).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let t=ut(e),o=t.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));pt(o.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),t.close()});Je.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",ot).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let t=ut(e,!0),o=Ui(process.cwd(),e.db);Ul(o)||(console.log(q.red(` No observability db at ${o}`)),t.close(),process.exit(1));let n=new Lp(o,{readonly:!0});try{let s=La(n,t);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(),t.close()}});Je.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",ot).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 t=ut(e),o=t.gradedRows(Wi(e)),n=Zr(o,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),t.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}`)),t.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/o.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)`)),mt(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),t.close()});Be.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",tt).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 t=pt(e),o=t.gradedRows(Li(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=Vr(o,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),t.close();return}if(s.insufficient){console.log(q.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),t.close();return}console.log(q.bold(`
186
+ reliability (equal-width bins)`)),pt(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),t.close()});Je.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",ot).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 t=ut(e),o=t.gradedRows(Wi(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=ea(o,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),t.close();return}if(s.insufficient){console.log(q.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),t.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
- `)),mt(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(`
188
+ `)),pt(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.`)),t.close()});Be.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",tt).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 t=pt(e),o=t.gradedRows({...Li(e),labeledOnly:!0}),n=zr(o,Number(e.steps));if(n.length===0){console.log(q.yellow(` No labeled rows for seat "${e.seat}".`)),t.close();return}mt(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),t.close()});Be.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",tt).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=>{go();let t=pt(e),o=t.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.`)),t.close()});Je.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",ot).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 t=ut(e),o=t.gradedRows({...Wi(e),labeledOnly:!0}),n=Qr(o,Number(e.steps));if(n.length===0){console.log(q.yellow(` No labeled rows for seat "${e.seat}".`)),t.close();return}pt(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),t.close()});Je.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",ot).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=>{po();let t=ut(e),o=t.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(!o){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.")),t.close();return}let n=e.backend??o.backend,s=e.model??(n===o.backend?o.model:void 0),i=await Kr(n,JSON.parse(o.state_json),JSON.parse(o.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),t.close();return}console.log(q.bold(`
194
+ ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!o){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.")),t.close();return}let n=e.backend??o.backend,s=e.model??(n===o.backend?o.model:void 0),i=await ta(n,JSON.parse(o.state_json),JSON.parse(o.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),t.close();return}console.log(q.bold(`
195
195
  ${e.seat} on ${i.backend} (${i.model})`)),console.log(q.dim(` ${i.samples} samples of call ${o.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
196
- `)),mt(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(`
196
+ `)),pt(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.")),t.close()});Be.command("backends").description("registered decision backends and what they claim").action(()=>{go();let e=Fr().map(t=>{let o=ti(t).capabilities;return{backend:t,source:o.probabilitySource,calibrated:o.calibratedProbabilities?"yes":"no",maxOptions:o.maxChoiceOptions,maxStateChars:o.maxStateChars}});mt(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.")),t.close()});Je.command("backends").description("registered decision backends and what they claim").action(()=>{po();let e=Jr().map(t=>{let o=ii(t).capabilities;return{backend:t,source:o.probabilitySource,calibrated:o.calibratedProbabilities?"yes":"no",maxOptions:o.maxChoiceOptions,maxStateChars:o.maxStateChars}});pt(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\`.`))});Be.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=>{go();let t={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);t.answer=lo(s,"Which option fits this state?")}e.noul&&(t.verdict=ht(String(e.noul))),Object.keys(t).length===0&&(console.log(q.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await ti(e.backend).decide({state:e.state,questions:t,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Mp}from"commander";import j from"chalk";import{resolve as Wl}from"path";import{existsSync as Lp}from"fs";import Fp from"better-sqlite3";var Pl=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],Rp=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function Ll(e,t={}){let o=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...Rp,...Pl,"num_turns","injected_context"].map(d=>o.has(d)?d:`NULL AS ${d}`).join(", "),i=["status IN ('ok', 'error', 'timeout')"],r=[];t.since!==void 0&&(i.push("started_at >= ?"),r.push(t.since)),t.agentId&&(i.push("agent_id = ?"),r.push(t.agentId));let a=i.join(" AND "),c=e.prepare(`
208
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Je.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=>{po();let t={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);t.answer=mo(s,"Which option fits this state?")}e.noul&&(t.verdict=yt(String(e.noul))),Object.keys(t).length===0&&(console.log(q.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await ii(e.backend).decide({state:e.state,questions:t,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Jp}from"commander";import j from"chalk";import{resolve as zl}from"path";import{existsSync as Hp}from"fs";import Gp from"better-sqlite3";var ql=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],Up=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function Bl(e,t={}){let o=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...Up,...ql,"num_turns","injected_context"].map(d=>o.has(d)?d:`NULL AS ${d}`).join(", "),i=["status IN ('ok', 'error', 'timeout')"],r=[];t.since!==void 0&&(i.push("started_at >= ?"),r.push(t.since)),t.agentId&&(i.push("agent_id = ?"),r.push(t.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=Ma({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:[]}),h=Pl.map(w=>d[w]).filter(w=>typeof w=="number");return{taskId:u,agentId:f,cluster:p,startedAt:d.started_at,ok:d.status==="ok",tokens:h.length>0?h.reduce((w,k)=>w+k,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:ha(d.injected_context)}})}function Fi(e){return e.injected?[...e.injected.memory.map(t=>`memory:${t}`),...e.injected.procedures.map(t=>`procedure:${t}`),...e.injected.wiki?["wiki"]:[]]:[]}function Ui(e){let t=e.filter(n=>n!==null).sort((n,s)=>n-s);if(t.length===0)return null;let o=Math.floor(t.length/2);return t.length%2?t[o]:(t[o-1]+t[o])/2}function Ml(e){return{n:e.length,successRate:e.length?e.filter(t=>t.ok).length/e.length:0,medianTokens:Ui(e.map(t=>t.tokens)),medianTurns:Ui(e.map(t=>t.turns)),medianDurationMs:Ui(e.map(t=>t.durationMs))}}function Fl(e,t={}){let o=Math.max(1,t.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of Fi(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(Fi));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=>Fi(p).includes(g));u.length<o||f.length<o||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Ml(u),after:Ml(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Rt from"chalk";function _p(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 Pp(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function qi(e,t){if(e==null||t==null||e===0)return"";let o=Math.round((t-e)/e*100);return o===0?" (=)":` (${o>0?"+":""}${o}%)`}function Ul(e,t,o){let n=`${Math.round(t.successRate*100)}%`,s=o?` (${t.successRate>=o.successRate?"+":""}${Math.round((t.successRate-o.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(t.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${_p(t.medianTokens)}${o?qi(o.medianTokens,t.medianTokens):""}`,`turns ${Pp(t.medianTurns)}${o?qi(o.medianTurns,t.medianTurns):""}`,`time ${Dp(t.medianDurationMs)}${o?qi(o.medianDurationMs,t.medianDurationMs):""}`].join(" ")}function ql(e,t){if(e.length===0)return[Rt.dim(` No lesson has at least ${t.minSamples} recorded task(s) before and after it yet.`),Rt.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let o=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&o.push(""),o.push(`${Rt.bold(s.agentId)} ${Rt.cyan(s.cluster)}`),n=i),o.push(` ${Rt.yellow(s.lesson)} ${Rt.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),o.push(Rt.dim(Ul("before",s.before))),o.push(Ul("after",s.after,s.before))}return o.push(""),o.push(Rt.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),o}var Io=new Mp().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function fs(e){let t=Wl(e.cwd??process.cwd()),o=Wl(t,e.path??".agentx/db.sqlite");Lp(o)||(console.log(j.red(` No db at ${o}`)),console.log(j.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Fp(o,{readonly:!0})}catch(n){console.log(j.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(j.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Up(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Bl(e){if(!e)return;let t=Up(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(j.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}function qp(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s ago`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function Wi(e){return e==="ok"?j.green:e==="error"||e==="timeout"?j.red:e==="in-flight"?j.yellow:j.dim}Io.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 t=fs(e),o=ya(t,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Bl(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(j.dim(" (no traces)"));return}for(let n of o){let s=Wi(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?j.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?j.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${j.dim(n.taskId)} ${s} ${j.bold(n.agentId)}${j.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${j.dim("\xB7")} ${i}${a} ${j.dim(qp(n.startedAt))}`),n.error&&console.log(` ${j.red("error:")} ${n.error}`)}});Io.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,t)=>{let o=fs(t),n=ri(o,e);if(n||(console.log(j.red(` No trace at ${e}`)),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}Wp(n.task,n.steps)});function Wp(e,t){let o=Wi(e.status)(e.status);if(console.log(j.bold(`Trace ${e.taskId}`)),console.log(` ${j.dim("agent")} ${e.agentId}`),console.log(` ${j.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${j.dim("workflow")} ${j.cyan(e.workflowRunId)}${n?j.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${j.dim("intent")} ${e.intentEventId} ${j.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${j.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${j.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${j.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${j.dim("status")} ${o}`),e.durationMs!=null&&console.log(` ${j.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${j.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(` ${j.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(` ${j.dim("lessons")} ${r.length?r.join(" "):j.dim("none")}`)}if(e.error&&console.log(` ${j.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${j.dim("message")} ${e.messagePreview}`),console.log(),t.length===0){console.log(j.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(j.bold(`Steps (${t.length}):`));for(let n of t){let s=n.status?Wi(n.status)(n.status):j.dim("\u2014"),i=n.action?j.cyan(n.action):"";if(console.log(` ${j.dim(`#${n.seq}`)} ${j.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?j.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=qa({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:[]}),h=ql.map(w=>d[w]).filter(w=>typeof w=="number");return{taskId:u,agentId:f,cluster:p,startedAt:d.started_at,ok:d.status==="ok",tokens:h.length>0?h.reduce((w,k)=>w+k,0):null,turns:d.num_turns??null,durationMs:d.duration_ms??null,injected:$a(d.injected_context)}})}function Bi(e){return e.injected?[...e.injected.memory.map(t=>`memory:${t}`),...e.injected.procedures.map(t=>`procedure:${t}`),...e.injected.wiki?["wiki"]:[]]:[]}function Ji(e){let t=e.filter(n=>n!==null).sort((n,s)=>n-s);if(t.length===0)return null;let o=Math.floor(t.length/2);return t.length%2?t[o]:(t[o-1]+t[o])/2}function Wl(e){return{n:e.length,successRate:e.length?e.filter(t=>t.ok).length/e.length:0,medianTokens:Ji(e.map(t=>t.tokens)),medianTurns:Ji(e.map(t=>t.turns)),medianDurationMs:Ji(e.map(t=>t.durationMs))}}function Jl(e,t={}){let o=Math.max(1,t.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of Bi(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(Bi));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=>Bi(p).includes(g));u.length<o||f.length<o||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:Wl(u),after:Wl(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Dt from"chalk";function qp(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function Wp(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function Bp(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function Hi(e,t){if(e==null||t==null||e===0)return"";let o=Math.round((t-e)/e*100);return o===0?" (=)":` (${o>0?"+":""}${o}%)`}function Hl(e,t,o){let n=`${Math.round(t.successRate*100)}%`,s=o?` (${t.successRate>=o.successRate?"+":""}${Math.round((t.successRate-o.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(t.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${qp(t.medianTokens)}${o?Hi(o.medianTokens,t.medianTokens):""}`,`turns ${Bp(t.medianTurns)}${o?Hi(o.medianTurns,t.medianTurns):""}`,`time ${Wp(t.medianDurationMs)}${o?Hi(o.medianDurationMs,t.medianDurationMs):""}`].join(" ")}function Gl(e,t){if(e.length===0)return[Dt.dim(` No lesson has at least ${t.minSamples} recorded task(s) before and after it yet.`),Dt.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let o=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&o.push(""),o.push(`${Dt.bold(s.agentId)} ${Dt.cyan(s.cluster)}`),n=i),o.push(` ${Dt.yellow(s.lesson)} ${Dt.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),o.push(Dt.dim(Hl("before",s.before))),o.push(Hl("after",s.after,s.before))}return o.push(""),o.push(Dt.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),o}var No=new Jp().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function bs(e){let t=zl(e.cwd??process.cwd()),o=zl(t,e.path??".agentx/db.sqlite");Hp(o)||(console.log(j.red(` No db at ${o}`)),console.log(j.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Gp(o,{readonly:!0})}catch(n){console.log(j.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(j.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function zp(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Yl(e){if(!e)return;let t=zp(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(j.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}function Yp(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s ago`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function Gi(e){return e==="ok"?j.green:e==="error"||e==="timeout"?j.red:e==="in-flight"?j.yellow:j.dim}No.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 t=bs(e),o=ka(t,{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(o,null,2));return}if(o.length===0){console.log(j.dim(" (no traces)"));return}for(let n of o){let s=Gi(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?j.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?j.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${j.dim(n.taskId)} ${s} ${j.bold(n.agentId)}${j.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${j.dim("\xB7")} ${i}${a} ${j.dim(Yp(n.startedAt))}`),n.error&&console.log(` ${j.red("error:")} ${n.error}`)}});No.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,t)=>{let o=bs(t),n=di(o,e);if(n||(console.log(j.red(` No trace at ${e}`)),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}Vp(n.task,n.steps)});function Vp(e,t){let o=Gi(e.status)(e.status);if(console.log(j.bold(`Trace ${e.taskId}`)),console.log(` ${j.dim("agent")} ${e.agentId}`),console.log(` ${j.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${j.dim("workflow")} ${j.cyan(e.workflowRunId)}${n?j.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${j.dim("intent")} ${e.intentEventId} ${j.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${j.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${j.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${j.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${j.dim("status")} ${o}`),e.durationMs!=null&&console.log(` ${j.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${j.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(` ${j.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(` ${j.dim("lessons")} ${r.length?r.join(" "):j.dim("none")}`)}if(e.error&&console.log(` ${j.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${j.dim("message")} ${e.messagePreview}`),console.log(),t.length===0){console.log(j.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(j.bold(`Steps (${t.length}):`));for(let n of t){let s=n.status?Gi(n.status)(n.status):j.dim("\u2014"),i=n.action?j.cyan(n.action):"";if(console.log(` ${j.dim(`#${n.seq}`)} ${j.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?j.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
216
216
  `).slice(0,8);console.log(r.map(a=>` ${j.dim("\u2192")} ${a}`).join(`
217
217
  `)),n.inputSummary.split(`
218
218
  `).length>8&&console.log(` ${j.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
219
219
  `).slice(0,8);console.log(r.map(a=>` ${j.dim("\u2190")} ${a}`).join(`
220
220
  `)),n.outputSummary.split(`
221
- `).length>8&&console.log(` ${j.dim("\u2026")}`)}n.error&&console.log(` ${j.red("error:")} ${n.error}`)}}Io.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 t=fs(e),o=Math.max(1,parseInt(e.min,10)||2),n=Ll(t,{since:Bl(e.since),agentId:e.agent}),s=Fl(n,{minSamples:o});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of ql(s,{minSamples:o}))console.log(i)});Io.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,t)=>{let o=fs(t),n=ri(o,e);n||(console.log(j.red(` task not found: ${e}`)),console.log(j.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(j.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(j.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(j.bold(` replay ${j.cyan(e)}`)),console.log(j.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(j.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(t.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:t.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(j.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(j.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),t.diff){console.log(j.bold(" INPUT (replayed verbatim)")),console.log(),us(i),console.log(),console.log(j.bold(` ORIGINAL OUTPUT ${j.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?us(s.finalResponse):console.log(j.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(j.bold(` CURRENT OUTPUT ${j.dim(`status=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),us(d.content??"(empty reply)"),d.error&&console.log(j.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?j.dim(" outputs are identical"):j.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(j.green(` \u2713 replayed in ${u}ms`)),console.log(),us(d.content??"(empty reply)"),d.error&&console.log(j.red(`
222
- error: ${d.error}`)),console.log(),console.log(j.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function us(e){let t=e.split(`
223
- `),o=60,n=t.slice(0,o);for(let s of n)console.log(` ${j.dim("\u2502")} ${s}`);t.length>o&&console.log(` ${j.dim("\u2502")} ${j.dim(`\u2026+${t.length-o} more lines`)}`)}import{Command as Gp}from"commander";import pe from"chalk";import{existsSync as zp,mkdirSync as Yp,writeFileSync as Vp}from"fs";import{resolve as Gl,join as Hl,dirname as Kp}from"path";var Bp=`# AgentX destructive-action guardrails \u2014 global policy
221
+ `).length>8&&console.log(` ${j.dim("\u2026")}`)}n.error&&console.log(` ${j.red("error:")} ${n.error}`)}}No.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 t=bs(e),o=Math.max(1,parseInt(e.min,10)||2),n=Bl(t,{since:Yl(e.since),agentId:e.agent}),s=Jl(n,{minSamples:o});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of Gl(s,{minSamples:o}))console.log(i)});No.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,t)=>{let o=bs(t),n=di(o,e);n||(console.log(j.red(` task not found: ${e}`)),console.log(j.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(j.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(j.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(j.bold(` replay ${j.cyan(e)}`)),console.log(j.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(j.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(t.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:t.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(j.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(j.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),t.diff){console.log(j.bold(" INPUT (replayed verbatim)")),console.log(),ws(i),console.log(),console.log(j.bold(` ORIGINAL OUTPUT ${j.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?ws(s.finalResponse):console.log(j.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(j.bold(` CURRENT OUTPUT ${j.dim(`status=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),ws(d.content??"(empty reply)"),d.error&&console.log(j.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?j.dim(" outputs are identical"):j.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(j.green(` \u2713 replayed in ${u}ms`)),console.log(),ws(d.content??"(empty reply)"),d.error&&console.log(j.red(`
222
+ error: ${d.error}`)),console.log(),console.log(j.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function ws(e){let t=e.split(`
223
+ `),o=60,n=t.slice(0,o);for(let s of n)console.log(` ${j.dim("\u2502")} ${s}`);t.length>o&&console.log(` ${j.dim("\u2502")} ${j.dim(`\u2026+${t.length-o} more lines`)}`)}import{Command as Zp}from"commander";import ue from"chalk";import{existsSync as eu,mkdirSync as tu,writeFileSync as ou}from"fs";import{resolve as Xl,join as Kl,dirname as nu}from"path";var Kp=`# 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
- `,Jp=`# Production protected resources.
249
+ `,Xp=`# 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
- `,Hp=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
271
+ `,Qp=`# 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
- `,Jl=[{relPath:"policy.yaml",content:Bp},{relPath:"environments/production.yaml",content:Jp},{relPath:"agents/coder-agent.yaml",content:Hp}];var _t=new Gp().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function Bi(e){return e==="deny"?pe.red:e==="escalate"||e==="ask"?pe.yellow:e==="warn"?pe.magenta:pe.green}function hs(e){return e.root?Gl(e.root):xc()}_t.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 vc({root:hs(e),agentId:e.agent,env:e.env}),process.exit(0)});_t.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,t)=>{let o=hs(t),n=t.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=kc({tool:t.tool,command:e,cwd:t.cwd,agentId:t.agent,env:t.env},{root:o,agentId:t.agent,env:t.env,modeOverride:n,noAudit:!0});if(t.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}Xp(s,i,r)});function Xp(e,t,o){let n=Bi(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":pe.dim(" (no rule matched)")}`),console.log(` enforced as ${Bi(e.effectiveAction)(e.effectiveAction)} ${pe.dim(`(mode=${t})`)}`),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 ${o}ms`)}`),console.log()}_t.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 t=sa({root:hs(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(pe.dim(" (no guardrail decisions recorded yet)"));return}for(let o of t){let n=new Date(o.ts).toISOString().replace("T"," ").slice(0,19),s=Bi(o.verdict),i=o.effective_action!==o.verdict?pe.dim(`->${o.effective_action}`):"";console.log(` ${pe.dim(n)} ${s(o.verdict.toUpperCase().padEnd(8))}${i} ${pe.cyan((o.agent_id??"?").padEnd(16))} ${pe.dim((o.matched_rule??"-").padEnd(24))} ${(o.command??"").slice(0,70)}`),o.resolved_target&&console.log(pe.dim(` target: ${o.resolved_target}`))}});_t.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 t=Hl(Gl(e.root),bc),o=0;for(let n of Jl){let s=Hl(t,n.relPath);if(zp(s)&&!e.force){console.log(pe.dim(` skip (exists) ${n.relPath}`));continue}Yp(Kp(s),{recursive:!0}),Vp(s,n.content),console.log(pe.green(` created ${n.relPath}`)),o++}console.log(),console.log(` Guardrails scaffolded under ${pe.cyan(t)}`),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.'))});_t.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 t=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});t.ok?console.log(pe.green(` daemon reloaded (${e.url})`)):console.log(pe.yellow(` daemon reachable but returned ${t.status}`))}catch(t){console.log(pe.dim(` daemon not reachable (${t.message}). Policy files are still read live on each check.`))}});_t.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 t=$c(hs(e),e.agent);console.log(JSON.stringify(t,null,2))});nn();import{Command as Qp}from"commander";import{execFile as Zp}from"child_process";import{promisify as eu}from"util";import{existsSync as tu}from"fs";import ot from"chalk";on();var wn="ui-element";function ys(e){let t=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...t.length?{alreadyTried:t.map(o=>({control:yn(o.tried,80),screenChanged:o.changed,note:o.note?yn(o.note,120):null}))}:{},controls:e.candidates.map(o=>({id:String(o.id),role:zl(o.role),label:yn(o.label,120),value:o.value?yn(o.value,80):null,enabled:o.enabled}))}}function ws(e){let t={};for(let o of e){let n=o.label||o.value||"(unlabelled)";t[String(o.id)]=`${zl(o.role)}: ${yn(n,80)}`}return{target:lo(t,"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:ht("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 bs(e,t){let o=e.target,n=t.map(s=>({id:s.id,score:o.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(o.choice),confidence:o.confidence,present:e.present.noul,ranked:n}}function zl(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function yn(e,t){let o=String(e??"").replace(/\s+/g," ").trim();return o.length>t?o.slice(0,t):o}var Yl=eu(Zp),Vl=new Qp().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,t)=>{tu(Re)||(console.log(ot.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let o;try{o=await Zn({max:Number(t.max)||40})}catch(d){console.log(ot.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=o.candidates;if(n.length===0&&(console.log(ot.yellow(` ${o.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=ln(o,n[0].id);d&&(console.log(ot.yellow(` ${o.app} exposes exactly one target \u2014 pointing at it: `)+ot.bold(n[0].label)),await Yl(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 ct(wn,ys({request:e,app:o.app,window:o.window,candidates:n}),ws(n),{features:{app:o.app,candidates:n.length,ocr:o.usedOCR}});s||(console.log(ot.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${wn}.mode`)),process.exit(1));let i=bs(s.answers,n),r=ln(o,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=o.ocrRects.has(i.id),l=Number(t.minPresent)||.5;if((i.present<l||!r)&&(console.log(ot.yellow(` nothing on screen matches "${e}"`)+ot.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),t.json){console.log(JSON.stringify({app:o.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(` ${ot.green("\u2192")} ${ot.bold(g)} `+ot.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Yl(Re,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as xu}from"commander";import Je from"chalk";import{readFileSync as Kl}from"fs";import{homedir as ou}from"os";import{join as nu}from"path";var Xl=12e5,su="https://openrouter.ai/api/v1/chat/completions",iu=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function ru(e={kind:"window"},t=Xl,o={}){let n={...o.deps,maxPixels:t,settings:o.screen??o.deps?.settings};if(!o.settle)return vo(e,{},n);try{return await vo(e,{untilStable:!0},n)}catch(s){if(s instanceof Bc)return vo(e,{},n);throw s}}var au=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
280
+ `,Vl=[{relPath:"policy.yaml",content:Kp},{relPath:"environments/production.yaml",content:Xp},{relPath:"agents/coder-agent.yaml",content:Qp}];var Pt=new Zp().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function zi(e){return e==="deny"?ue.red:e==="escalate"||e==="ask"?ue.yellow:e==="warn"?ue.magenta:ue.green}function $s(e){return e.root?Xl(e.root):Tc()}Pt.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:$s(e),agentId:e.agent,env:e.env}),process.exit(0)});Pt.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,t)=>{let o=$s(t),n=t.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Ec({tool:t.tool,command:e,cwd:t.cwd,agentId:t.agent,env:t.env},{root:o,agentId:t.agent,env:t.env,modeOverride:n,noAudit:!0});if(t.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}su(s,i,r)});function su(e,t,o){let n=zi(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ue.dim(" (no rule matched)")}`),console.log(` enforced as ${zi(e.effectiveAction)(e.effectiveAction)} ${ue.dim(`(mode=${t})`)}`),e.ruleId&&console.log(` rule ${ue.cyan(e.ruleId)}${e.severity?ue.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ue.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ue.dim(`evaluated in ${o}ms`)}`),console.log()}Pt.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 t=ca({root:$s(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ue.dim(" (no guardrail decisions recorded yet)"));return}for(let o of t){let n=new Date(o.ts).toISOString().replace("T"," ").slice(0,19),s=zi(o.verdict),i=o.effective_action!==o.verdict?ue.dim(`->${o.effective_action}`):"";console.log(` ${ue.dim(n)} ${s(o.verdict.toUpperCase().padEnd(8))}${i} ${ue.cyan((o.agent_id??"?").padEnd(16))} ${ue.dim((o.matched_rule??"-").padEnd(24))} ${(o.command??"").slice(0,70)}`),o.resolved_target&&console.log(ue.dim(` target: ${o.resolved_target}`))}});Pt.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 t=Kl(Xl(e.root),xc),o=0;for(let n of Vl){let s=Kl(t,n.relPath);if(eu(s)&&!e.force){console.log(ue.dim(` skip (exists) ${n.relPath}`));continue}tu(nu(s),{recursive:!0}),ou(s,n.content),console.log(ue.green(` created ${n.relPath}`)),o++}console.log(),console.log(` Guardrails scaffolded under ${ue.cyan(t)}`),console.log(ue.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ue.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});Pt.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 t=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});t.ok?console.log(ue.green(` daemon reloaded (${e.url})`)):console.log(ue.yellow(` daemon reachable but returned ${t.status}`))}catch(t){console.log(ue.dim(` daemon not reachable (${t.message}). Policy files are still read live on each check.`))}});Pt.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 t=Sc($s(e),e.agent);console.log(JSON.stringify(t,null,2))});rn();import{Command as iu}from"commander";import{execFile as ru}from"child_process";import{promisify as au}from"util";import{existsSync as cu}from"fs";import nt from"chalk";sn();var $n="ui-element";function ks(e){let t=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...t.length?{alreadyTried:t.map(o=>({control:bn(o.tried,80),screenChanged:o.changed,note:o.note?bn(o.note,120):null}))}:{},controls:e.candidates.map(o=>({id:String(o.id),role:Ql(o.role),label:bn(o.label,120),value:o.value?bn(o.value,80):null,enabled:o.enabled}))}}function vs(e){let t={};for(let o of e){let n=o.label||o.value||"(unlabelled)";t[String(o.id)]=`${Ql(o.role)}: ${bn(n,80)}`}return{target:mo(t,"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:yt("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 xs(e,t){let o=e.target,n=t.map(s=>({id:s.id,score:o.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(o.choice),confidence:o.confidence,present:e.present.noul,ranked:n}}function Ql(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function bn(e,t){let o=String(e??"").replace(/\s+/g," ").trim();return o.length>t?o.slice(0,t):o}var Zl=au(ru),ed=new iu().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,t)=>{cu(_e)||(console.log(nt.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let o;try{o=await ns({max:Number(t.max)||40})}catch(d){console.log(nt.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=o.candidates;if(n.length===0&&(console.log(nt.yellow(` ${o.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=gn(o,n[0].id);d&&(console.log(nt.yellow(` ${o.app} exposes exactly one target \u2014 pointing at it: `)+nt.bold(n[0].label)),await Zl(_e,["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 lt($n,ks({request:e,app:o.app,window:o.window,candidates:n}),vs(n),{features:{app:o.app,candidates:n.length,ocr:o.usedOCR}});s||(console.log(nt.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${$n}.mode`)),process.exit(1));let i=xs(s.answers,n),r=gn(o,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=o.ocrRects.has(i.id),l=Number(t.minPresent)||.5;if((i.present<l||!r)&&(console.log(nt.yellow(` nothing on screen matches "${e}"`)+nt.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),t.json){console.log(JSON.stringify({app:o.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(` ${nt.green("\u2192")} ${nt.bold(g)} `+nt.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Zl(_e,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Iu}from"commander";import He from"chalk";import{readFileSync as td}from"fs";import{homedir as lu}from"os";import{join as du}from"path";var od=12e5,gu="https://openrouter.ai/api/v1/chat/completions",mu=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function pu(e={kind:"window"},t=od,o={}){let n={...o.deps,maxPixels:t,settings:o.screen??o.deps?.settings};if(!o.settle)return So(e,{},n);try{return await So(e,{untilStable:!0},n)}catch(s){if(s instanceof Yc)return So(e,{},n);throw s}}var uu=`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 cu(e,t,o,n){let s=du();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=Kl(t.path).toString("base64"),r={model:o,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 fu(e,t,o,n){let s=yu();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=td(t.path).toString("base64"),r={model:o,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
289
289
 
290
- The image is the region ${lu(t)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:au,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(su,{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:o,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function $s(e,t={}){let o=Date.now(),n=await ru(t.region??{kind:"window"},t.maxPixels??Xl,{settle:t.settle,screen:t.screen}),s=await cu(e,n,t.model??iu,t.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-o,usage:s.usage}}function lu(e){let{x:t,y:o,width:n,height:s}=e.region;return o<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(t)} y=${Math.round(o)} ${Math.round(n)}x${Math.round(s)} points`}var bn;function du(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(bn!==void 0)return bn??void 0;try{let e=Kl(nu(ou(),".agentx","openrouter-key.txt"),"utf-8").trim();bn=e.length>0?e:null}catch{bn=null}return bn??void 0}import{execFile as gu}from"child_process";import{promisify as mu}from"util";var pu=mu(gu),uu=["screencapture"],fu=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Zl(e){let t=e.toLowerCase(),o=[];return/record|recording|capturing|screen ?capture|screencast/.test(t)&&o.push(await hu()),o}async function hu(){let e=await Ql(uu);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 t=await Ql(fu);return t.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${t.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 Ql(e){let t=[];for(let o of e)try{let{stdout:n}=await pu("pgrep",["-x",o]),s=n.trim().split(`
291
- `)[0];s&&t.push(`${o} (pid ${s})`)}catch{}return t}nn();on();var ed="screen-state",td={observable:ht("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:ht("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 od(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 nd(e){return{observable:e.observable.noul,holds:e.holds.noul}}var yu=.6,wu=.7,bu=.3;async function $n(e,t={}){let[o,n]=await Promise.all([$s(e,t),Zl(e).catch(()=>[])]),s=t.observableFloor??yu,i=await ct(ed,od({claim:e,observation:o.observation,evidence:o.evidence,reading:o.reading,region:vu(o),treeNote:t.treeNote,probes:n}),td,{incumbent:{holds:o.reading==="yes"?1:0},features:{model:o.model,region:o.shot.region.height<=40?"menubar":"window"}});if(!i){let l=o.reading==="yes"?"confirmed":o.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:ku(l,o),sighting:o,probes:n}}let{observable:r,holds:a}=nd(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 (${ks(r)} that the evidence settles it). Seen: ${o.observation||"nothing conclusive"}`,sighting:o,probes:n};let c=a>=wu?"confirmed":a<=bu?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:$u(c,a,o),sighting:o,probes:n}}function $u(e,t,o){let n=o.evidence||o.observation||"no specific detail";return e==="confirmed"?`Confirmed (${ks(t)}). ${n}`:e==="refuted"?`Not true (${ks(1-t)} it is false). ${n}`:`Inconclusive (${ks(t)}, between the thresholds). ${n}`}function ku(e,t){let o=t.evidence||t.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${o}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${o}`}function vu(e){let t=e.shot.region;return t.y<=1&&t.height<=40?"the macOS menu bar":`a ${Math.round(t.width)}x${Math.round(t.height)} region of the screen`}var ks=e=>`${Math.round(e*100)}%`;var sd=new xu().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,t)=>{let o={kind:"window"};if(t.menubar)o={kind:"menubar"};else if(t.screen)o={kind:"screen"};else if(t.rect){let n=String(t.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(Je.red(" --rect wants x,y,w,h")),process.exit(1)),o={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(t.verify){let s=await $n(e,{region:o,model:t.model,settle:t.settle,screen:t.settle?lt():void 0});if(t.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"?Je.green("\u2713"):s.outcome==="refuted"?Je.red("\u2717"):Je.yellow("?");console.log(` ${i} ${Je.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Je.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Je.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 $s(e,{region:o,model:t.model,settle:t.settle,screen:t.settle?lt():void 0});if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Je.bold(n.observation)}`),n.evidence&&console.log(Je.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Su(n.reading)}`),console.log(Je.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Je.red(` ${n?.message??n}`)),process.exit(1)}});function Su(e){return e==="yes"?Je.green(e):e==="no"?Je.red(e):Je.yellow(e)}import{Command as Eu}from"commander";import nt from"chalk";import{spawn as Au}from"child_process";function Dt(e){console.log(nt.red(` ${e}`)),process.exit(1)}function id(e,t,o={}){if(t){console.log(JSON.stringify({...e,...o},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?nt.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(nt.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(t=>{let o=Au(e[0],e.slice(1),{stdio:"inherit"});o.on("error",()=>t(127)),o.on("close",n=>t(n??1))})}var kn=new Eu("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");kn.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,t)=>{let o=lt(t.config),n;try{n=es(t.region,o)}catch(r){Dt(r.message)}let s=t.maxPixels===void 0?void 0:Number(t.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Dt("--max-pixels must be a whole number above 0");let i={settings:o,maxPixels:s};try{if(e.length){let r=t.untilStable||!t.untilChanged,{result:a,shot:c,error:l}=await ts(()=>Tu(e),n,{out:t.out,untilStable:r},i);c||(console.log(nt.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),id(c,t.json,{exitCode:a}),a!==0&&process.exit(a);return}id(await vo(n,{untilChanged:t.untilChanged,untilStable:t.untilStable,out:t.out},i),t.json)}catch(r){Dt(r?.message??String(r))}});kn.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:${zt()}`).option("--json","print the result as JSON").action(async e=>{let t=process.env.MESH_TOKEN,o=e.seconds?`?seconds=${encodeURIComponent(e.seconds)}`:"";try{let n=await fetch(`${String(e.url).replace(/\/$/,"")}/screen/recent${o}`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));if(n.ok||Dt(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(nt.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${nt.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Dt(`could not reach the daemon: ${n?.message??n}`)}});kn.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,t)=>[...t,e],[]).option("--remove-region <name>","remove a named region",(e,t)=>[...t,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 t={};e.maxPixels!==void 0&&(t.maxPixels=e.maxPixels),e.timeout!==void 0&&(t.timeoutMs=e.timeout),e.interval!==void 0&&(t.intervalMs=e.interval),e.threshold!==void 0&&(t.changeThreshold=e.threshold),e.stableMs!==void 0&&(t.stableMs=e.stableMs);let o={};for(let s of e.region){let i=s.indexOf("=");i<1&&Dt(`--region wants name=x,y,w,h, got "${s}"`),o[s.slice(0,i)]=s.slice(i+1)}for(let s of e.removeRegion)o[s]=null;Object.keys(o).length&&(t.regions=o);let n={};if(e.buffer!==void 0){let s=String(e.buffer).toLowerCase();["on","off"].includes(s)||Dt("--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&&(t.buffer=n),Object.keys(t).length===0){let s=lt(e.config);console.log(`
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(" "):nt.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":nt.dim("off")} ${nt.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
293
- `);return}try{let{summary:s,backupPath:i}=Ke(r=>{let a=Wc(r.screen,t);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(nt.green(`
294
- \u2713 ${s}`)),i&&console.log(nt.dim(` Backup: ${i}`)),console.log()}catch(s){Dt(s?.message??String(s))}});nn();import{Command as Iu}from"commander";import{execFile as pd}from"child_process";import{promisify as Cu}from"util";import{existsSync as Nu,readFileSync as Ru,writeFileSync as ud,mkdirSync as _u}from"fs";import{homedir as Du}from"os";import{join as Pu,dirname as Mu}from"path";import Pe from"chalk";on();var Ji="paste-transform";function rd(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function ad(e){let t={};for(let o of e)t[o.id]=o.criterion;return{worthChanging:ht("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:lo(t,"What shape should this paste arrive in?")}}function cd(e){let t=e.worthChanging,o=e.shape,n=Object.entries(o.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:t.noul,id:o.choice,confidence:o.confidence,ranked:n}}var ju=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"]),Ou=e=>/^https?:\/\/\S+$/i.test(e.trim()),Hi=[{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 t=e.split(`
290
+ The image is the region ${hu(t)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:uu,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(gu,{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:o,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Ss(e,t={}){let o=Date.now(),n=await pu(t.region??{kind:"window"},t.maxPixels??od,{settle:t.settle,screen:t.screen}),s=await fu(e,n,t.model??mu,t.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-o,usage:s.usage}}function hu(e){let{x:t,y:o,width:n,height:s}=e.region;return o<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(t)} y=${Math.round(o)} ${Math.round(n)}x${Math.round(s)} points`}var kn;function yu(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(kn!==void 0)return kn??void 0;try{let e=td(du(lu(),".agentx","openrouter-key.txt"),"utf-8").trim();kn=e.length>0?e:null}catch{kn=null}return kn??void 0}import{execFile as wu}from"child_process";import{promisify as bu}from"util";var $u=bu(wu),ku=["screencapture"],vu=["Screen Studio","OBS","QuickTime Player","Zoom"];async function sd(e){let t=e.toLowerCase(),o=[];return/record|recording|capturing|screen ?capture|screencast/.test(t)&&o.push(await xu()),o}async function xu(){let e=await nd(ku);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 t=await nd(vu);return t.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${t.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 nd(e){let t=[];for(let o of e)try{let{stdout:n}=await $u("pgrep",["-x",o]),s=n.trim().split(`
291
+ `)[0];s&&t.push(`${o} (pid ${s})`)}catch{}return t}rn();sn();var id="screen-state",rd={observable:yt("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:yt("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 ad(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 cd(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Su=.6,Eu=.7,Au=.3;async function vn(e,t={}){let[o,n]=await Promise.all([Ss(e,t),sd(e).catch(()=>[])]),s=t.observableFloor??Su,i=await lt(id,ad({claim:e,observation:o.observation,evidence:o.evidence,reading:o.reading,region:Ou(o),treeNote:t.treeNote,probes:n}),rd,{incumbent:{holds:o.reading==="yes"?1:0},features:{model:o.model,region:o.shot.region.height<=40?"menubar":"window"}});if(!i){let l=o.reading==="yes"?"confirmed":o.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:ju(l,o),sighting:o,probes:n}}let{observable:r,holds:a}=cd(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 (${Es(r)} that the evidence settles it). Seen: ${o.observation||"nothing conclusive"}`,sighting:o,probes:n};let c=a>=Eu?"confirmed":a<=Au?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Tu(c,a,o),sighting:o,probes:n}}function Tu(e,t,o){let n=o.evidence||o.observation||"no specific detail";return e==="confirmed"?`Confirmed (${Es(t)}). ${n}`:e==="refuted"?`Not true (${Es(1-t)} it is false). ${n}`:`Inconclusive (${Es(t)}, between the thresholds). ${n}`}function ju(e,t){let o=t.evidence||t.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${o}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${o}`}function Ou(e){let t=e.shot.region;return t.y<=1&&t.height<=40?"the macOS menu bar":`a ${Math.round(t.width)}x${Math.round(t.height)} region of the screen`}var Es=e=>`${Math.round(e*100)}%`;var ld=new Iu().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,t)=>{let o={kind:"window"};if(t.menubar)o={kind:"menubar"};else if(t.screen)o={kind:"screen"};else if(t.rect){let n=String(t.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(He.red(" --rect wants x,y,w,h")),process.exit(1)),o={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(t.verify){let s=await vn(e,{region:o,model:t.model,settle:t.settle,screen:t.settle?dt():void 0});if(t.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"?He.green("\u2713"):s.outcome==="refuted"?He.red("\u2717"):He.yellow("?");console.log(` ${i} ${He.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(He.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(He.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 Ss(e,{region:o,model:t.model,settle:t.settle,screen:t.settle?dt():void 0});if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${He.bold(n.observation)}`),n.evidence&&console.log(He.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Cu(n.reading)}`),console.log(He.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(He.red(` ${n?.message??n}`)),process.exit(1)}});function Cu(e){return e==="yes"?He.green(e):e==="no"?He.red(e):He.yellow(e)}import{Command as Nu}from"commander";import st from"chalk";import{spawn as Ru}from"child_process";function Mt(e){console.log(st.red(` ${e}`)),process.exit(1)}function dd(e,t,o={}){if(t){console.log(JSON.stringify({...e,...o},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?st.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(st.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function _u(e){return new Promise(t=>{let o=Ru(e[0],e.slice(1),{stdio:"inherit"});o.on("error",()=>t(127)),o.on("close",n=>t(n??1))})}var xn=new Nu("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");xn.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,t)=>{let o=dt(t.config),n;try{n=ss(t.region,o)}catch(r){Mt(r.message)}let s=t.maxPixels===void 0?void 0:Number(t.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Mt("--max-pixels must be a whole number above 0");let i={settings:o,maxPixels:s};try{if(e.length){let r=t.untilStable||!t.untilChanged,{result:a,shot:c,error:l}=await is(()=>_u(e),n,{out:t.out,untilStable:r},i);c||(console.log(st.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),dd(c,t.json,{exitCode:a}),a!==0&&process.exit(a);return}dd(await So(n,{untilChanged:t.untilChanged,untilStable:t.untilStable,out:t.out},i),t.json)}catch(r){Mt(r?.message??String(r))}});xn.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:${Yt()}`).option("--json","print the result as JSON").action(async e=>{let t=process.env.MESH_TOKEN,o=e.seconds?`?seconds=${encodeURIComponent(e.seconds)}`:"";try{let n=await fetch(`${String(e.url).replace(/\/$/,"")}/screen/recent${o}`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));if(n.ok||Mt(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(st.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${st.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Mt(`could not reach the daemon: ${n?.message??n}`)}});xn.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,t)=>[...t,e],[]).option("--remove-region <name>","remove a named region",(e,t)=>[...t,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 t={};e.maxPixels!==void 0&&(t.maxPixels=e.maxPixels),e.timeout!==void 0&&(t.timeoutMs=e.timeout),e.interval!==void 0&&(t.intervalMs=e.interval),e.threshold!==void 0&&(t.changeThreshold=e.threshold),e.stableMs!==void 0&&(t.stableMs=e.stableMs);let o={};for(let s of e.region){let i=s.indexOf("=");i<1&&Mt(`--region wants name=x,y,w,h, got "${s}"`),o[s.slice(0,i)]=s.slice(i+1)}for(let s of e.removeRegion)o[s]=null;Object.keys(o).length&&(t.regions=o);let n={};if(e.buffer!==void 0){let s=String(e.buffer).toLowerCase();["on","off"].includes(s)||Mt("--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&&(t.buffer=n),Object.keys(t).length===0){let s=dt(e.config);console.log(`
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(" "):st.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":st.dim("off")} ${st.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
293
+ `);return}try{let{summary:s,backupPath:i}=Xe(r=>{let a=zc(r.screen,t);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(st.green(`
294
+ \u2713 ${s}`)),i&&console.log(st.dim(` Backup: ${i}`)),console.log()}catch(s){Mt(s?.message??String(s))}});rn();import{Command as Mu}from"commander";import{execFile as wd}from"child_process";import{promisify as Lu}from"util";import{existsSync as Fu,readFileSync as Uu,writeFileSync as bd,mkdirSync as qu}from"fs";import{homedir as Wu}from"os";import{join as Bu,dirname as Ju}from"path";import Me from"chalk";sn();var Yi="paste-transform";function gd(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function md(e){let t={};for(let o of e)t[o.id]=o.criterion;return{worthChanging:yt("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:mo(t,"What shape should this paste arrive in?")}}function pd(e){let t=e.worthChanging,o=e.shape,n=Object.entries(o.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:t.noul,id:o.choice,confidence:o.confidence,ranked:n}}var Du=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"]),Pu=e=>/^https?:\/\/\S+$/i.test(e.trim()),Vi=[{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 t=e.split(`
295
295
  `);if(t.length<3)return null;let o=0;for(let n=0;n<t.length-1;n++){let s=t[n].trim(),i=t[n+1].trim();s.length>40&&i.length>0&&!/[.!?:;]$/.test(s)&&o++}return o<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,28 +299,28 @@ The image is the region ${lu(t)}.`},{type:"image_url",image_url:{url:`data:image
299
299
  `).map(o=>o.trim()).filter(Boolean);return t.length<2||t.every(o=>/^([-*+]|\d+[.)])\s/.test(o))?null:t.map(o=>`- ${o}`).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 t=e.split(`
301
301
  `);return t.every(o=>o.startsWith(">")||!o.trim())?null:t.map(o=>o.trim()?`> ${o}`:">").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 t=e.trim();if(!/^[[{]/.test(t))return null;try{let o=JSON.parse(t),n=JSON.stringify(o,null,2);return n===t?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 t=e.trim();if(!Ou(t))return null;try{let o=new URL(t),n=0;for(let s of[...o.searchParams.keys()])ju.has(s.toLowerCase())&&(o.searchParams.delete(s),n++);return n===0?null:o.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 t=e.trim();if(t.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 t=e.trim();if(!/^[[{]/.test(t))return null;try{let o=JSON.parse(t),n=JSON.stringify(o,null,2);return n===t?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 t=e.trim();if(!Pu(t))return null;try{let o=new URL(t),n=0;for(let s of[...o.searchParams.keys()])Du.has(s.toLowerCase())&&(o.searchParams.delete(s),n++);return n===0?null:o.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 t=e.trim();if(t.includes(`
303
303
  `)||t.length>90||t.length<3)return null;let o=t.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return o&&o!==t?o: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 t=e.replace(/[ \t]+/g," ").replace(/\s*\n\s*/g,`
304
- `).trim();return t===e?null:t}}];function ld(e){let t=[];for(let o of Hi){let n=o.apply(e);n!==null&&(o.id!=="asIs"&&n===e||t.push({transform:o,result:n}))}return t}function dd(e,t=320){if(e.length<=t)return e;let o=Math.floor(t*.7),n=t-o;return`${e.slice(0,o)}
304
+ `).trim();return t===e?null:t}}];function ud(e){let t=[];for(let o of Vi){let n=o.apply(e);n!==null&&(o.id!=="asIs"&&n===e||t.push({transform:o,result:n}))}return t}function fd(e,t=320){if(e.length<=t)return e;let o=Math.floor(t*.7),n=t-o;return`${e.slice(0,o)}
305
305
  \u2026[${e.length-t} more characters]\u2026
306
- ${e.slice(-n)}`}function gd(e){let t=e.trim();return t.includes(`
307
- `)||t.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(t)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(t)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(t)||t.length>=20&&!/\s/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/\d/.test(t)&&!/^https?:\/\//i.test(t)&&!/\.(com|org|net|io|ai|tn)$/i.test(t)}var Gi=Cu(pd),fd=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 (${Hi.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=Fu();c===null&&(console.log(Pe.yellow(" nothing to undo")),process.exit(2)),await yd(c),console.log(` ${Pe.green("\u2192")} clipboard restored`);return}let t=await Uu();if(t||(console.log(Pe.yellow(" clipboard is empty")),process.exit(2)),gd(t)){hd(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let o=ld(t),n=await qu();if(e.as){let c=o.find(l=>l.transform.id===e.as);c||(console.log(Pe.red(` "${e.as}" does not apply to this clipboard`)),console.log(Pe.dim(` available: ${o.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Co(e,c.transform.id,c.result,t,"forced",1);return}if(o.length<2){await Co(e,"asIs",t,t,"nothing else applies",0);return}let s=await ct(Ji,rd({preview:dd(t),length:t.length,lineCount:t.split(`
308
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),ad(o.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:o.length,chars:t.length}});if(!s){await Co(e,"asIs",t,t,`seat unavailable \u2014 set decisions.seats.${Ji}.mode`,0);return}let i=cd(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Co(e,"asIs",t,t,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=o.find(c=>c.transform.id===i.id);if(!a){await Co(e,"asIs",t,t,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Co(e,a.transform.id,a.result,t,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Co(e,t,o,n,s,i){let r=o!==n;r&&(e.apply||e.paste)&&(Lu(n),await yd(o)),hd(e,{applied:t,reason:s,worthChanging:i,result:o,original:n,changed:r}),e.paste&&await Gi(Re,["key","--name","v","--mod","command"]).catch(a=>{console.log(Pe.red(` could not paste: ${a?.message??a}`))})}function hd(e,t){if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.changed){console.log(` ${Pe.dim("\u2192")} ${Pe.bold("unchanged")} ${Pe.dim(`\xB7 ${t.reason}`)}`);return}console.log(` ${Pe.green("\u2192")} ${Pe.bold(t.applied)} ${Pe.dim(`\xB7 ${t.reason}`)}`),console.log(Pe.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Pe.dim(md(t.original))),console.log(Pe.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(md(t.result)),!e.apply&&!e.paste&&console.log(Pe.dim(`
309
- (dry run \u2014 pass --apply to write it back)`))}var md=(e,t=400)=>(e.length>t?`${e.slice(0,t)}\u2026`:e).split(`
306
+ ${e.slice(-n)}`}function hd(e){let t=e.trim();return t.includes(`
307
+ `)||t.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(t)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(t)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(t)||t.length>=20&&!/\s/.test(t)&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/\d/.test(t)&&!/^https?:\/\//i.test(t)&&!/\.(com|org|net|io|ai|tn)$/i.test(t)}var Ki=Lu(wd),$d=new Mu().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 (${Vi.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=Gu();c===null&&(console.log(Me.yellow(" nothing to undo")),process.exit(2)),await vd(c),console.log(` ${Me.green("\u2192")} clipboard restored`);return}let t=await zu();if(t||(console.log(Me.yellow(" clipboard is empty")),process.exit(2)),hd(t)){kd(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let o=ud(t),n=await Yu();if(e.as){let c=o.find(l=>l.transform.id===e.as);c||(console.log(Me.red(` "${e.as}" does not apply to this clipboard`)),console.log(Me.dim(` available: ${o.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Ro(e,c.transform.id,c.result,t,"forced",1);return}if(o.length<2){await Ro(e,"asIs",t,t,"nothing else applies",0);return}let s=await lt(Yi,gd({preview:fd(t),length:t.length,lineCount:t.split(`
308
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),md(o.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:o.length,chars:t.length}});if(!s){await Ro(e,"asIs",t,t,`seat unavailable \u2014 set decisions.seats.${Yi}.mode`,0);return}let i=pd(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Ro(e,"asIs",t,t,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=o.find(c=>c.transform.id===i.id);if(!a){await Ro(e,"asIs",t,t,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Ro(e,a.transform.id,a.result,t,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Ro(e,t,o,n,s,i){let r=o!==n;r&&(e.apply||e.paste)&&(Hu(n),await vd(o)),kd(e,{applied:t,reason:s,worthChanging:i,result:o,original:n,changed:r}),e.paste&&await Ki(_e,["key","--name","v","--mod","command"]).catch(a=>{console.log(Me.red(` could not paste: ${a?.message??a}`))})}function kd(e,t){if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.changed){console.log(` ${Me.dim("\u2192")} ${Me.bold("unchanged")} ${Me.dim(`\xB7 ${t.reason}`)}`);return}console.log(` ${Me.green("\u2192")} ${Me.bold(t.applied)} ${Me.dim(`\xB7 ${t.reason}`)}`),console.log(Me.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Me.dim(yd(t.original))),console.log(Me.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(yd(t.result)),!e.apply&&!e.paste&&console.log(Me.dim(`
309
+ (dry run \u2014 pass --apply to write it back)`))}var yd=(e,t=400)=>(e.length>t?`${e.slice(0,t)}\u2026`:e).split(`
310
310
  `).map(o=>` ${o}`).join(`
311
- `),vs=Pu(Du(),".agentx","paste-undo.txt");function Lu(e){try{_u(Mu(vs),{recursive:!0}),ud(vs,e,{mode:384})}catch{}}function Fu(){try{let e=Ru(vs,"utf-8");return ud(vs,"",{mode:384}),e.length?e:null}catch{return null}}async function Uu(){let{stdout:e}=await Gi("pbpaste",[],{maxBuffer:16777216});return e}async function yd(e){await new Promise((t,o)=>{pd("pbcopy",[],s=>s?o(s):t()).stdin?.end(e)})}async function qu(){if(!Nu(Re))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Gi(Re,["focused"]),t=JSON.parse(e);return t.ok===!1||!t.role?{app:"unknown",role:"an unknown control",label:null}:{app:t.app??"unknown",role:Wu(t.role??"",t.editable),label:t.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Wu(e,t){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]??(t?"an editable control":`a ${e||"unknown"} control`)}import{Command as Bu}from"commander";import qe from"chalk";ie();function wd(e,t,o={}){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 ts(()=>e(s,i),t,{},o);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 Ju=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Hu(e,t){return async({title:o,message:n,channel:s,chatId:i})=>{let r=o&&!n.startsWith(o)?`${o}
312
- ${n}`:n,a=await fetch(`${Ju}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??t,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function Gu(e){let t;try{t=I(e.config)}catch{t=void 0}let o=Yn(t?.notifications.local);e.sound||(o.sound=!1),e.banner||(o.banner=!1);let n=e.channel??Vn(t);return{alert:Xa(o),banner:o.banner,channel:n}}var bd=new Bu().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,t)=>{let o=new qa,n=ka(),{alert:s,banner:i,channel:r}=Gu(t),a=s,c;if(t.proof&&!i)c=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(t.proof){let g=lt(t.config),d=wd(s,es("notifications",g),{settings:g});a=d.alert,c=d.proof}if(t.status){let g=o.list();if(t.json){console.log(JSON.stringify({focus:n,held:g},null,2));return}console.log(` ${n.active?qe.yellow("\u25D0"):qe.green("\u25CB")} ${va(n)} ${qe.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(qe.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=Hu(r,t.chatId);if(t.flush){let g=await ec(l,{queue:o,alert:s});console.log(g?qe.green(` delivered ${g} held notification(s)`):qe.dim(" nothing was held"));return}e?.trim()||(console.log(qe.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await Za({message:e.trim(),from:t.from,title:t.title,priority:Number(t.priority)||4,urgent:!!t.urgent,channel:r,chatId:t.chatId},l,{queue:o,alert:a,focus:n}),d=c?.();if(t.json){console.log(JSON.stringify(d?{...g,proof:d}:g,null,2));return}let u=g.delivered?qe.green("\u2192"):qe.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(qe.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?qe.yellow("?"):qe.green("\u2713")} banner: ${d.shot.path}${qe.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(qe.yellow(` ${d.error}`))}catch(g){console.log(qe.red(` ${g?.message??g}`)),await s(t.title,e.trim()),process.exit(1)}});import{Command as No}from"commander";import st from"chalk";var $d=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function xs(e,t,o,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${$d}${t}`,{method:e,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...n},body:o===void 0?void 0:JSON.stringify(o)}).catch(a=>{throw new Error(`daemon not reachable at ${$d}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function zu(e,t,o){e.calls=e.calls??{};let n=Array.isArray(e.calls.allow)?e.calls.allow:[],s=n.includes(t);return o===s?`${t} is ${o?"already":"not"} in calls.allow`:(e.calls.allow=o?[...n,t]:n.filter(i=>i!==t),o?`${t} may now call you`:`${t} may no longer call you`)}function Yi(e){let t=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),o=e.status==="missed"?st.yellow("missed"):e.status==="ringing"?st.green("ringing"):st.dim(e.status),n=e.note?st.dim(` (${e.note})`):"";return` ${st.dim(e.id)} ${t} ${e.agentId} ${o}${n}
313
- ${e.reason}${e.summary?st.dim(`
314
- summary: ${e.summary}`):""}`}async function vn(e){try{await e()}catch(t){console.log(st.red(` ${t?.message??t}`)),process.exit(1)}}var Yu=new No("request").description("ask the owner for a live voice call (rings AgentX Voice); runs inside an agent's turn").requiredOption("--reason <text>","why, in one line: said aloud when they answer").option("--urgent","ring even during Focus").option("--json","print the call as JSON").action(e=>vn(async()=>{let t=process.env.AGENTX_AGENT_ID;if(!t)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let o=await xs("POST","/calls",{agentId:t,reason:e.reason,urgency:e.urgent?"urgent":"normal"},xa());if(e.json){console.log(JSON.stringify(o,null,2));return}let n=o.rang==="widget"?"ringing on AgentX Voice":o.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${o.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${o.rang?st.green("\u260E"):st.yellow("\u23F8")} ${o.call.id} ${n}`)})),Vu=new No("list").description("recent calls, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed, later (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>vn(async()=>{let t=new URLSearchParams({limit:String(e.limit)});e.status&&t.set("status",e.status);let{calls:o}=await xs("GET",`/calls?${t}`);if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(st.dim(" no calls"));return}for(let n of o)console.log(Yi(n))}));function zi(e,t){return new No(e).description(t).argument("<id>","call id, from `agentx call list`").action(o=>vn(async()=>{let{call:n}=await xs("POST",`/calls/${encodeURIComponent(o)}/${e}`,{});console.log(Yi(n))}))}var Ku=new No("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,t)=>vn(async()=>{let{call:o}=await xs("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(t)});console.log(Yi(o))}));function kd(e,t){return new No(e).description(t?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((o,n)=>vn(()=>{let{summary:s}=Ke(i=>zu(i,o,t),{configPath:n.config});console.log(st.green(` ${s}`))}))}var vd=new No("call").description("agents ring you for a live voice call").addCommand(Yu).addCommand(Vu).addCommand(zi("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(zi("decline","decline a ringing call")).addCommand(Ku).addCommand(zi("hangup","end an answered call")).addCommand(kd("allow",!0)).addCommand(kd("disallow",!1));nn();Qr();Ur();on();import{Command as Xu}from"commander";import{readFileSync as Qu}from"fs";var xd=new Xu().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 t;try{t=e.file?Qu(e.file,"utf8"):await Zu()}catch(r){to(`could not read the spec: ${r?.message??r}`);return}if(!t.trim())return to("no spec given \u2014 pipe JSON on stdin or pass --file");let o;try{o=JSON.parse(t)}catch(r){return to(`spec is not valid JSON: ${r?.message??r}`)}if(!o.state)return to("spec needs a `state`");if(!o.questions||Object.keys(o.questions).length===0)return to("spec needs at least one entry in `questions`");try{Gr(o.questions)}catch(r){return to(r?.message??String(r))}let n=o.seat||e.seat;go(),process.env[ea(n)]="active";let s=null;if(e.record!==!1)try{s=new Fn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
315
- `)}Zr({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await ct(n,o.state,o.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return to(`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 to(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Zu(){if(process.stdin.isTTY)return"";let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}nn();import{Command as Cf}from"commander";import{execFile as Nf,spawn as Ld}from"child_process";import{promisify as Rf}from"util";import{existsSync as _f,statSync as Df}from"fs";import{join as Fd}from"path";import{tmpdir as Pf}from"os";import te from"chalk";var ef={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."}]},tf={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."}]},of={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."}]},Vi=[ef,tf,of];ie();ie();import it from"chalk";import{execFile as nf}from"child_process";import{promisify as sf}from"util";import{createInterface as rf}from"readline";var Sd=sf(nf);function af(e){e.type==="step"?console.log(`${it.cyan(` ${e.n}. ${e.action}`)}${e.target?it.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(it.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?it.red(` failed: ${e.error}`):it.dim(" done it")):e.type==="replanned"?console.log(it.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(it.cyan(` you: ${e.text}`)):e.type==="error"?console.log(it.red(` error: ${e.error}`)):e.type==="end"&&console.log(it.dim(` \xB7 ended (${e.reason})`))}async function cf(e,t){let o=Date.now()+t;for(let n=0;Date.now()<o;n++){n&&n%10===0&&await Sd("open",["-a",e]).catch(()=>{});try{let s=(await hi()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function Ed(e,t){let o=I(t.config),n=t.agent||process.env.AGENTX_VOICE_AGENT||o.node.defaultAgent;if(!n||!o.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(t.mode??"")?t.mode:"teach",i;if(t.app&&(await Sd("open",["-a",t.app]),i=await cf(t.app,15e3)??void 0,!i))throw new Error(`${t.app} did not come to the front`);let r=Xn(n,o.agents,!1),a=o.voice.listener??_c,c=bo(n,o.agents[n]),l=new Mc({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(t.steps)||void 0,listener:a},{readScreen:hi,presence:new Qn(c,Re,n),speech:new $o,model:ko({system:Pc(r.persona,a)}),act:Lc});l.on(af),console.log(it.bold(`
316
- ${c.name} teaches: ${e}`)+it.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
317
- `));let g=rf({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}ie();import rt from"chalk";import{execFile as vf}from"child_process";import{existsSync as Qi,writeFileSync as xf}from"fs";import{homedir as Sf}from"os";import{join as Pd,resolve as Ef}from"path";import{promisify as Af}from"util";var We={w:1e3,h:640},Ki=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],jd=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Ad=["none","semi","solid","fill","pattern"],Xi=180,Od=48,lf=["s","m","l","xl"],df=["draw","sans","serif","mono"];function Id(){return[`You are an illustrator drawing on a tldraw canvas ${We.w} wide and ${We.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 ${Xi}. 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 ${Od} 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: ${jd.join(", ")}.`,`color is one of: ${Ki.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(`
318
- `)}function Ro(e,t,o){return typeof e=="string"&&t.includes(e)?e:o}function oo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var no=(e,t,o)=>Math.min(o,Math.max(t,e)),Td=e=>no(oo(e)??1,.1,1),gf=/^#[0-9a-f]{6}$/i;function mf(e){if(!e||typeof e!="object")return null;let t={};for(let[o,n]of Object.entries(e))Ki.includes(o)&&typeof n=="string"&&gf.test(n)&&(t[o]=n);return Object.keys(t).length?t:null}function pf(e){if(!Array.isArray(e))return null;let t=[];for(let o of e.slice(0,Od)){if(!Array.isArray(o))return null;let n=oo(o[0]),s=oo(o[1]);if(n===null||s===null)return null;t.push([no(n,0,We.w),no(s,0,We.h)])}return t.length>=2?t:null}function Cd(e,t){let o=e.trim().replace(/,$/,"");if(!o.startsWith("{"))return null;let n;try{n=JSON.parse(o)}catch{return null}if("palette"in n){let l=mf(n.palette);return!l||t.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||t.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Ro(n.color,Ki,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!t.has(l)||!t.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=pf(n.path),g=Ro(n.fill,Ad,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Td(n.opacity)}}let a=oo(n.x),c=oo(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:no(a,0,We.w-20),y:no(c,0,We.h-20),size:Ro(n.size,lf,"l"),color:r,font:Ro(n.font,df,"draw")};if(typeof n.geo=="string"){let l=oo(n.w),g=oo(n.h);if(l===null||g===null||l<4||g<4)return null;let d=no(a,0,We.w-4),u=no(c,0,We.h-4);return{kind:"geo",id:s,say:i,geo:Ro(n.geo,jd,"rectangle"),x:d,y:u,w:Math.min(l,We.w-d),h:Math.min(g,We.h-u),color:r,fill:Ro(n.fill,Ad,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Td(n.opacity)}}return null}var Ss=class{buf="";push(t){this.buf+=t;let o=this.buf.split(`
319
- `);return this.buf=o.pop()??"",o}flush(){let t=this.buf;return this.buf="",t.trim()?[t]:[]}};var uf=500,ff=e=>`
320
- editor.zoomToBounds({ x: 0, y: 0, w: ${We.w}, h: ${We.h} }, { inset: ${e}, immediate: true })
321
- const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${We.w}, y: 0 })
311
+ `),As=Bu(Wu(),".agentx","paste-undo.txt");function Hu(e){try{qu(Ju(As),{recursive:!0}),bd(As,e,{mode:384})}catch{}}function Gu(){try{let e=Uu(As,"utf-8");return bd(As,"",{mode:384}),e.length?e:null}catch{return null}}async function zu(){let{stdout:e}=await Ki("pbpaste",[],{maxBuffer:16777216});return e}async function vd(e){await new Promise((t,o)=>{wd("pbcopy",[],s=>s?o(s):t()).stdin?.end(e)})}async function Yu(){if(!Fu(_e))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await Ki(_e,["focused"]),t=JSON.parse(e);return t.ok===!1||!t.role?{app:"unknown",role:"an unknown control",label:null}:{app:t.app??"unknown",role:Vu(t.role??"",t.editable),label:t.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Vu(e,t){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]??(t?"an editable control":`a ${e||"unknown"} control`)}import{Command as Ku}from"commander";import We from"chalk";ne();function xd(e,t,o={}){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 is(()=>e(s,i),t,{},o);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 Xu=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Qu(e,t){return async({title:o,message:n,channel:s,chatId:i})=>{let r=o&&!n.startsWith(o)?`${o}
312
+ ${n}`:n,a=await fetch(`${Xu}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??t,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function Zu(e){let t;try{t=I(e.config)}catch{t=void 0}let o=Qn(t?.notifications.local);e.sound||(o.sound=!1),e.banner||(o.banner=!1);let n=e.channel??Zn(t);return{alert:tc(o),banner:o.banner,channel:n}}var Sd=new Ku().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,t)=>{let o=new Ha,n=Ea(),{alert:s,banner:i,channel:r}=Zu(t),a=s,c;if(t.proof&&!i)c=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(t.proof){let g=dt(t.config),d=xd(s,ss("notifications",g),{settings:g});a=d.alert,c=d.proof}if(t.status){let g=o.list();if(t.json){console.log(JSON.stringify({focus:n,held:g},null,2));return}console.log(` ${n.active?We.yellow("\u25D0"):We.green("\u25CB")} ${Aa(n)} ${We.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(We.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=Qu(r,t.chatId);if(t.flush){let g=await sc(l,{queue:o,alert:s});console.log(g?We.green(` delivered ${g} held notification(s)`):We.dim(" nothing was held"));return}e?.trim()||(console.log(We.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await nc({message:e.trim(),from:t.from,title:t.title,priority:Number(t.priority)||4,urgent:!!t.urgent,channel:r,chatId:t.chatId},l,{queue:o,alert:a,focus:n}),d=c?.();if(t.json){console.log(JSON.stringify(d?{...g,proof:d}:g,null,2));return}let u=g.delivered?We.green("\u2192"):We.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(We.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?We.yellow("?"):We.green("\u2713")} banner: ${d.shot.path}${We.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(We.yellow(` ${d.error}`))}catch(g){console.log(We.red(` ${g?.message??g}`)),await s(t.title,e.trim()),process.exit(1)}});import{Command as _o}from"commander";import it from"chalk";var Ed=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function Ts(e,t,o,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${Ed}${t}`,{method:e,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...n},body:o===void 0?void 0:JSON.stringify(o)}).catch(a=>{throw new Error(`daemon not reachable at ${Ed}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function ef(e,t,o){e.calls=e.calls??{};let n=Array.isArray(e.calls.allow)?e.calls.allow:[],s=n.includes(t);return o===s?`${t} is ${o?"already":"not"} in calls.allow`:(e.calls.allow=o?[...n,t]:n.filter(i=>i!==t),o?`${t} may now call you`:`${t} may no longer call you`)}function Qi(e){let t=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),o=e.status==="missed"?it.yellow("missed"):e.status==="ringing"?it.green("ringing"):it.dim(e.status),n=e.note?it.dim(` (${e.note})`):"";return` ${it.dim(e.id)} ${t} ${e.agentId} ${o}${n}
313
+ ${e.reason}${e.summary?it.dim(`
314
+ summary: ${e.summary}`):""}`}async function Sn(e){try{await e()}catch(t){console.log(it.red(` ${t?.message??t}`)),process.exit(1)}}var tf=new _o("request").description("ask the owner for a live voice call (rings AgentX Voice); runs inside an agent's turn").requiredOption("--reason <text>","why, in one line: said aloud when they answer").option("--urgent","ring even during Focus").option("--json","print the call as JSON").action(e=>Sn(async()=>{let t=process.env.AGENTX_AGENT_ID;if(!t)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let o=await Ts("POST","/calls",{agentId:t,reason:e.reason,urgency:e.urgent?"urgent":"normal"},Ta());if(e.json){console.log(JSON.stringify(o,null,2));return}let n=o.rang==="widget"?"ringing on AgentX Voice":o.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${o.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${o.rang?it.green("\u260E"):it.yellow("\u23F8")} ${o.call.id} ${n}`)})),of=new _o("list").description("recent calls, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed, later (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Sn(async()=>{let t=new URLSearchParams({limit:String(e.limit)});e.status&&t.set("status",e.status);let{calls:o}=await Ts("GET",`/calls?${t}`);if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(it.dim(" no calls"));return}for(let n of o)console.log(Qi(n))}));function Xi(e,t){return new _o(e).description(t).argument("<id>","call id, from `agentx call list`").action(o=>Sn(async()=>{let{call:n}=await Ts("POST",`/calls/${encodeURIComponent(o)}/${e}`,{});console.log(Qi(n))}))}var nf=new _o("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,t)=>Sn(async()=>{let{call:o}=await Ts("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(t)});console.log(Qi(o))}));function Ad(e,t){return new _o(e).description(t?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((o,n)=>Sn(()=>{let{summary:s}=Xe(i=>ef(i,o,t),{configPath:n.config});console.log(it.green(` ${s}`))}))}var Td=new _o("call").description("agents ring you for a live voice call").addCommand(tf).addCommand(of).addCommand(Xi("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(Xi("decline","decline a ringing call")).addCommand(nf).addCommand(Xi("hangup","end an answered call")).addCommand(Ad("allow",!0)).addCommand(Ad("disallow",!1));rn();na();Hr();sn();import{Command as sf}from"commander";import{readFileSync as rf}from"fs";var jd=new sf().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 t;try{t=e.file?rf(e.file,"utf8"):await af()}catch(r){oo(`could not read the spec: ${r?.message??r}`);return}if(!t.trim())return oo("no spec given \u2014 pipe JSON on stdin or pass --file");let o;try{o=JSON.parse(t)}catch(r){return oo(`spec is not valid JSON: ${r?.message??r}`)}if(!o.state)return oo("spec needs a `state`");if(!o.questions||Object.keys(o.questions).length===0)return oo("spec needs at least one entry in `questions`");try{Xr(o.questions)}catch(r){return oo(r?.message??String(r))}let n=o.seat||e.seat;po(),process.env[ia(n)]="active";let s=null;if(e.record!==!1)try{s=new Wn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
315
+ `)}sa({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await lt(n,o.state,o.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return oo(`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 oo(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function af(){if(process.stdin.isTTY)return"";let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}rn();import{Command as Lf}from"commander";import{execFile as Ff,spawn as Bd}from"child_process";import{promisify as Uf}from"util";import{existsSync as qf,statSync as Wf}from"fs";import{join as Jd}from"path";import{tmpdir as Bf}from"os";import te from"chalk";var cf={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."}]},lf={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."}]},df={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."}]},Zi=[cf,lf,df];ne();ne();import rt from"chalk";import{execFile as gf}from"child_process";import{promisify as mf}from"util";import{createInterface as pf}from"readline";var Od=mf(gf);function uf(e){e.type==="step"?console.log(`${rt.cyan(` ${e.n}. ${e.action}`)}${e.target?rt.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(rt.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?rt.red(` failed: ${e.error}`):rt.dim(" done it")):e.type==="replanned"?console.log(rt.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(rt.cyan(` you: ${e.text}`)):e.type==="error"?console.log(rt.red(` error: ${e.error}`)):e.type==="end"&&console.log(rt.dim(` \xB7 ended (${e.reason})`))}async function ff(e,t){let o=Date.now()+t;for(let n=0;Date.now()<o;n++){n&&n%10===0&&await Od("open",["-a",e]).catch(()=>{});try{let s=(await $i()).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,t){let o=I(t.config),n=t.agent||process.env.AGENTX_VOICE_AGENT||o.node.defaultAgent;if(!n||!o.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(t.mode??"")?t.mode:"teach",i;if(t.app&&(await Od("open",["-a",t.app]),i=await ff(t.app,15e3)??void 0,!i))throw new Error(`${t.app} did not come to the front`);let r=ts(n,o.agents,!1),a=o.voice.listener??Fc,c=ko(n,o.agents[n]),l=new Wc({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(t.steps)||void 0,listener:a},{readScreen:$i,presence:new os(c,_e,n),speech:new vo,model:xo({system:qc(r.persona,a)}),act:Bc});l.on(uf),console.log(rt.bold(`
316
+ ${c.name} teaches: ${e}`)+rt.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
317
+ `));let g=pf({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}ne();import at from"chalk";import{execFile as Of}from"child_process";import{existsSync as or,writeFileSync as If}from"fs";import{homedir as Cf}from"os";import{join as qd,resolve as Nf}from"path";import{promisify as Rf}from"util";var Be={w:1e3,h:640},er=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Rd=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Cd=["none","semi","solid","fill","pattern"],tr=180,_d=48,hf=["s","m","l","xl"],yf=["draw","sans","serif","mono"];function Dd(){return[`You are an illustrator drawing on a tldraw canvas ${Be.w} wide and ${Be.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 ${tr}. 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 ${_d} 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: ${Rd.join(", ")}.`,`color is one of: ${er.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(`
318
+ `)}function Do(e,t,o){return typeof e=="string"&&t.includes(e)?e:o}function no(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var so=(e,t,o)=>Math.min(o,Math.max(t,e)),Nd=e=>so(no(e)??1,.1,1),wf=/^#[0-9a-f]{6}$/i;function bf(e){if(!e||typeof e!="object")return null;let t={};for(let[o,n]of Object.entries(e))er.includes(o)&&typeof n=="string"&&wf.test(n)&&(t[o]=n);return Object.keys(t).length?t:null}function $f(e){if(!Array.isArray(e))return null;let t=[];for(let o of e.slice(0,_d)){if(!Array.isArray(o))return null;let n=no(o[0]),s=no(o[1]);if(n===null||s===null)return null;t.push([so(n,0,Be.w),so(s,0,Be.h)])}return t.length>=2?t:null}function Pd(e,t){let o=e.trim().replace(/,$/,"");if(!o.startsWith("{"))return null;let n;try{n=JSON.parse(o)}catch{return null}if("palette"in n){let l=bf(n.palette);return!l||t.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||t.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Do(n.color,er,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!t.has(l)||!t.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=$f(n.path),g=Do(n.fill,Cd,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Nd(n.opacity)}}let a=no(n.x),c=no(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:so(a,0,Be.w-20),y:so(c,0,Be.h-20),size:Do(n.size,hf,"l"),color:r,font:Do(n.font,yf,"draw")};if(typeof n.geo=="string"){let l=no(n.w),g=no(n.h);if(l===null||g===null||l<4||g<4)return null;let d=so(a,0,Be.w-4),u=so(c,0,Be.h-4);return{kind:"geo",id:s,say:i,geo:Do(n.geo,Rd,"rectangle"),x:d,y:u,w:Math.min(l,Be.w-d),h:Math.min(g,Be.h-u),color:r,fill:Do(n.fill,Cd,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Nd(n.opacity)}}return null}var js=class{buf="";push(t){this.buf+=t;let o=this.buf.split(`
319
+ `);return this.buf=o.pop()??"",o}flush(){let t=this.buf;return this.buf="",t.trim()?[t]:[]}};var kf=500,vf=e=>`
320
+ editor.zoomToBounds({ x: 0, y: 0, w: ${Be.w}, h: ${Be.h} }, { inset: ${e}, immediate: true })
321
+ const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${Be.w}, y: 0 })
322
322
  const chrome = window.outerHeight - window.innerHeight
323
- return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${We.w} }`;function Nd(e,t,o,n=0,s=0){return{x:e.ox+t*e.scale,y:e.oy+o*e.scale,width:n*e.scale,height:s*e.scale}}function Rd(e){let t={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*t*.6,h:t*1.3}}function hf(e){let t=e.map(i=>i[0]),o=e.map(i=>i[1]),n=Math.min(...t),s=Math.min(...o);return{x:n,y:s,w:Math.max(...t)-n,h:Math.max(...o)-s}}function _d(e){return`const hex = ${JSON.stringify(e.colors)}
323
+ return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${Be.w} }`;function Md(e,t,o,n=0,s=0){return{x:e.ox+t*e.scale,y:e.oy+o*e.scale,width:n*e.scale,height:s*e.scale}}function Ld(e){let t={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*t*.6,h:t*1.3}}function xf(e){let t=e.map(i=>i[0]),o=e.map(i=>i[1]),n=Math.min(...t),s=Math.min(...o);return{x:n,y:s,w:Math.max(...t)-n,h:Math.max(...o)-s}}function Fd(e){return`const hex = ${JSON.stringify(e.colors)}
324
324
  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('')
325
325
  const th = editor.getTheme('default')
326
326
  const colors = structuredClone(th.colors)
@@ -328,9 +328,9 @@ for (const mode of Object.keys(colors)) for (const [name, v] of Object.entries(h
328
328
  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 })
329
329
  }
330
330
  editor.updateTheme({ ...th, colors })
331
- return true`}function yf(e,t){if(e.kind==="palette")return _d(e);let o=s=>JSON.stringify(`${t}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
331
+ return true`}function Sf(e,t){if(e.kind==="palette")return Fd(e);let o=s=>JSON.stringify(`${t}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
332
332
  const el = ${JSON.stringify(e)}
333
- const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(uf/10)}))
333
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(kf/10)}))
334
334
  const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
335
335
  const id = createShapeId(${o(e.id)})
336
336
  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' } })
@@ -370,82 +370,82 @@ return id`:`${n}
370
370
  const arrow = helpers.createArrowBetweenShapes(createShapeId(${o(e.from)}), createShapeId(${o(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
371
371
  const aid = typeof arrow === 'string' ? arrow : arrow?.id
372
372
  if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
373
- return aid ?? null`}function wf(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[wt(s[0][0],s[0][1]),wt(i[0],i[1])]}if(e.kind==="geo")return[wt(e.x,e.y),wt(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Rd(e);return[wt(s.x,s.y+s.h/2),wt(s.x+s.w,s.y+s.h/2)]}let o=t.get(e.from),n=t.get(e.to);return[wt(o.x+o.w/2,o.y+o.h/2),wt(n.x+n.w/2,n.y+n.h/2)]}var wt=(e,t)=>({x:e,y:t,w:0,h:0});async function Dd(e,t,o,n=()=>{}){let s=t.sleep??(x=>new Promise(v=>setTimeout(v,x))),i=t.now??Date.now,r=o.stepMs??1500,a=o.runTag??i().toString(36),c=i(),l=await t.api.exec(o.docId,ff(60)),g=new Set,d=new Map,u=[],f=!1,p=0,h=null,w=null,k=null,$=()=>{k?.(),k=null},b=x=>{if(g.size>=Xi)return;let v=Cd(x,g);if(!v){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add(v.id),h??=i()-c,u.push(v),n({type:"planned",n:g.size,el:v,atMs:i()-c}),$()},E=(async()=>{let x=new Ss;try{for await(let v of t.model.reply(`Draw: ${e}`,o.signal))x.push(v).forEach(b);x.flush().forEach(b)}catch(v){w=v?.message??String(v)}finally{p=i()-c,f=!0,$()}})(),S=0;for(;!o.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let v=i();if(x.kind==="palette"){x.say&&t.presence.say(x.say);try{await t.api.exec(o.docId,_d(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-v});continue}let[R,C]=wf(x,d);x.say&&t.presence.say(x.say),t.presence.moveTo(Nd(l,R.x,R.y)),await s(250),t.presence.moveTo(Nd(l,C.x,C.y));try{await t.api.exec(o.docId,yf(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"?Rd(x):x.kind==="path"?hf(x.pts):wt(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-v});let O=(x.say?r:0)-(i()-v);O>0&&await s(O)}return await E,w&&n({type:"error",error:`plan: ${w}`}),t.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:h,planMs:p}}import{readFileSync as bf}from"fs";import{homedir as $f}from"os";import{join as kf}from"path";var xn=kf($f(),"Library","Application Support","tldraw","server.json"),Es=class{constructor(t=xn,o=fetch){this.serverJson=t;this.fetchFn=o}server(){let t;try{t=bf(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:o,token:n}=JSON.parse(t);return{port:o,token:n}}async post(t,o){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(o)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${t}: ${r.error??i.status}`);return r.result}createDoc(t,o){return this.post("/api/docs/create",{name:t,...o?{directory:o}:{}})}exec(t,o){return this.post(`/api/doc/${t}/exec`,{code:o})}search(t){return this.post("/api/search",{code:t})}};var Tf=Af(vf),jf="claude-sonnet-5";function Of(e){e.type==="planned"?console.log(rt.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${rt.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${rt.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(rt.yellow(` skipped: ${e.line}`)):console.log(rt.red(` error: ${e.error}`))}async function If(){if(!Qi(xn)){await Tf("open",["-a","tldraw offline"]);for(let e=0;e<40&&!Qi(xn);e++)await new Promise(t=>setTimeout(t,500));if(!Qi(xn))throw new Error("tldraw offline did not start")}}async function Md(e,t){let o=I(t.config),n=t.agent||process.env.AGENTX_VOICE_AGENT||o.node.defaultAgent;if(!n||!o.agents[n])throw new Error(`Unknown agent: ${n}`);let s=t.model||jf,i=Ef(t.out||Pd(Sf(),"Documents")),r=bo(n,o.agents[n]),a=ko({system:Id(),model:s}),c=new Qn(r,Re,n),l=new Es;try{await If();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(rt.bold(`
374
- ${r.name} draws: ${e}`)+rt.dim(` (${s}, ${d.filePath})
375
- `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Dd(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Of);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"),h=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):Pd(i,`agentx-draw-${g}.png`);xf(h,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(rt.bold(`
376
- ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+rt.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`));let w=a.lastUsage;w&&console.log(rt.dim(` tokens: ${w.inputTokens} in, ${w.outputTokens} out, ${w.cacheReadTokens} cache read, ${w.cacheWriteTokens} cache write; cost ${w.costUsd===null?"not reported":`$${w.costUsd.toFixed(4)}`}`)),console.log(rt.dim(` ${d.filePath}
373
+ return aid ?? null`}function Ef(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[bt(s[0][0],s[0][1]),bt(i[0],i[1])]}if(e.kind==="geo")return[bt(e.x,e.y),bt(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=Ld(e);return[bt(s.x,s.y+s.h/2),bt(s.x+s.w,s.y+s.h/2)]}let o=t.get(e.from),n=t.get(e.to);return[bt(o.x+o.w/2,o.y+o.h/2),bt(n.x+n.w/2,n.y+n.h/2)]}var bt=(e,t)=>({x:e,y:t,w:0,h:0});async function Ud(e,t,o,n=()=>{}){let s=t.sleep??(x=>new Promise(v=>setTimeout(v,x))),i=t.now??Date.now,r=o.stepMs??1500,a=o.runTag??i().toString(36),c=i(),l=await t.api.exec(o.docId,vf(60)),g=new Set,d=new Map,u=[],f=!1,p=0,h=null,w=null,k=null,$=()=>{k?.(),k=null},b=x=>{if(g.size>=tr)return;let v=Pd(x,g);if(!v){x.trim()&&n({type:"skipped",line:x.slice(0,120)});return}g.add(v.id),h??=i()-c,u.push(v),n({type:"planned",n:g.size,el:v,atMs:i()-c}),$()},E=(async()=>{let x=new js;try{for await(let v of t.model.reply(`Draw: ${e}`,o.signal))x.push(v).forEach(b);x.flush().forEach(b)}catch(v){w=v?.message??String(v)}finally{p=i()-c,f=!0,$()}})(),S=0;for(;!o.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let v=i();if(x.kind==="palette"){x.say&&t.presence.say(x.say);try{await t.api.exec(o.docId,Fd(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-v});continue}let[R,C]=Ef(x,d);x.say&&t.presence.say(x.say),t.presence.moveTo(Md(l,R.x,R.y)),await s(250),t.presence.moveTo(Md(l,C.x,C.y));try{await t.api.exec(o.docId,Sf(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"?Ld(x):x.kind==="path"?xf(x.pts):bt(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-v});let O=(x.say?r:0)-(i()-v);O>0&&await s(O)}return await E,w&&n({type:"error",error:`plan: ${w}`}),t.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:h,planMs:p}}import{readFileSync as Af}from"fs";import{homedir as Tf}from"os";import{join as jf}from"path";var En=jf(Tf(),"Library","Application Support","tldraw","server.json"),Os=class{constructor(t=En,o=fetch){this.serverJson=t;this.fetchFn=o}server(){let t;try{t=Af(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:o,token:n}=JSON.parse(t);return{port:o,token:n}}async post(t,o){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(o)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${t}: ${r.error??i.status}`);return r.result}createDoc(t,o){return this.post("/api/docs/create",{name:t,...o?{directory:o}:{}})}exec(t,o){return this.post(`/api/doc/${t}/exec`,{code:o})}search(t){return this.post("/api/search",{code:t})}};var _f=Rf(Of),Df="claude-sonnet-5";function Pf(e){e.type==="planned"?console.log(at.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${at.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${at.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(at.yellow(` skipped: ${e.line}`)):console.log(at.red(` error: ${e.error}`))}async function Mf(){if(!or(En)){await _f("open",["-a","tldraw offline"]);for(let e=0;e<40&&!or(En);e++)await new Promise(t=>setTimeout(t,500));if(!or(En))throw new Error("tldraw offline did not start")}}async function Wd(e,t){let o=I(t.config),n=t.agent||process.env.AGENTX_VOICE_AGENT||o.node.defaultAgent;if(!n||!o.agents[n])throw new Error(`Unknown agent: ${n}`);let s=t.model||Df,i=Nf(t.out||qd(Cf(),"Documents")),r=ko(n,o.agents[n]),a=xo({system:Dd(),model:s}),c=new os(r,_e,n),l=new Os;try{await Mf();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(at.bold(`
374
+ ${r.name} draws: ${e}`)+at.dim(` (${s}, ${d.filePath})
375
+ `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await Ud(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},Pf);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"),h=d.filePath?d.filePath.replace(/\.tldraw$/,".png"):qd(i,`agentx-draw-${g}.png`);If(h,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(at.bold(`
376
+ ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+at.dim(` (first shape planned at ${f.firstLineMs===null?"\u2013":(f.firstLineMs/1e3).toFixed(1)} s, plan done at ${(f.planMs/1e3).toFixed(1)} s)`));let w=a.lastUsage;w&&console.log(at.dim(` tokens: ${w.inputTokens} in, ${w.outputTokens} out, ${w.cacheReadTokens} cache read, ${w.cacheWriteTokens} cache write; cost ${w.costUsd===null?"not reported":`$${w.costUsd.toFixed(4)}`}`)),console.log(at.dim(` ${d.filePath}
377
377
  ${h}
378
- `))}finally{a.close(),c.close()}}var er=Rf(Nf),Ud=new Cf().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, "${At}" 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,t)=>{if(t.live)try{t.mode==="draw"?await Md(String(t.live),t):await Ed(String(t.live),t),process.exit(0)}catch(g){console.log(te.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(te.bold(`
378
+ `))}finally{a.close(),c.close()}}var sr=Uf(Ff),Hd=new Lf().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, "${jt}" 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,t)=>{if(t.live)try{t.mode==="draw"?await Wd(String(t.live),t):await Id(String(t.live),t),process.exit(0)}catch(g){console.log(te.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(te.bold(`
379
379
  lessons
380
- `));for(let g of Vi)console.log(` ${te.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${te.dim(g.appHint)}
381
- `);return}let o=Vi.find(g=>g.id===e);o||(console.log(te.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),_f(Re)||(console.log(te.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=t.speak===!1?void 0:Ff(t.voice,t.agent);console.log(te.bold(`
380
+ `));for(let g of Zi)console.log(` ${te.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${te.dim(g.appHint)}
381
+ `);return}let o=Zi.find(g=>g.id===e);o||(console.log(te.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),qf(_e)||(console.log(te.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=t.speak===!1?void 0:Gf(t.voice,t.agent);console.log(te.bold(`
382
382
  ${o.title}`)),console.log(te.dim(` ${o.appHint}
383
- `));try{o.start&&(await er("/usr/bin/open",Mf(o.start)),await Pt(2e3),await As(o.start.ready))}catch(g){console.log(te.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;t.record&&(i=Fd(t.recordDir||process.cwd(),`teach-${o.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(te.dim(` recording \u2192 ${i}`)),s=Ld("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Pt(2e3));let r=t.hud===!1?null:Ld(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})+`
384
- `)}catch{}},c=[],l=!1;try{for(let[g,d]of o.steps.entries()){if(console.log(` ${te.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${o.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 As(d.before)}let u=t.speak===!1?Promise.resolve():qf(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 ${o.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await er(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:h}=await Zi(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:h!==!1,note:p??void 0}),h===!1&&console.log(te.yellow(" \xB7 clicked, but the screen did not change")),await Pt(d.afterClickWaitMs??1500)}if(d.type){await As(d.before),a(`Step ${g+1} of ${o.steps.length}`,d.type,"typing");let{error:p}=await Zi(["type","--text",d.type]);if(p)throw console.log(te.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 As(d.before),a(`Step ${g+1} of ${o.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Zi(["key","--name",d.key]);if(p)throw console.log(te.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 Pt((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Pt(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${o.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),h;try{h=await $n(d.verify,p?{settle:!0,screen:lt()}:{})}catch(w){h=null,console.log(te.yellow(` ? could not check: ${w?.message??w}`))}if(!h&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(h){let w=h.outcome==="confirmed"?te.green("\u2713"):h.outcome==="refuted"?te.red("\u2717"):te.yellow("?");if(console.log(` ${w} ${te.dim(h.reason)}`),!h.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(te.red(`
385
- stopping: could not confirm \u2014 ${d.verify}`)),console.log(te.dim(` ${h.reason}`)),console.log(te.dim(` screenshot: ${h.sighting.shot.path}`)),await Pt(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(te.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",o.title,"done"),await Pt(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Pt(2500);try{let{size:g}=Df(i);console.log(te.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(te.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(te.red(` lesson stopped before the end.
383
+ `));try{o.start&&(await sr("/usr/bin/open",Jf(o.start)),await Lt(2e3),await Is(o.start.ready))}catch(g){console.log(te.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;t.record&&(i=Jd(t.recordDir||process.cwd(),`teach-${o.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(te.dim(` recording \u2192 ${i}`)),s=Bd("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Lt(2e3));let r=t.hud===!1?null:Bd(_e,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
384
+ `)}catch{}},c=[],l=!1;try{for(let[g,d]of o.steps.entries()){if(console.log(` ${te.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${o.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 Is(d.before)}let u=t.speak===!1?Promise.resolve():Yf(d.say,n),f=d.find?await Hf(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 ${o.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await sr(_e,["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:h}=await nr(["click"]);if(p)throw new Error(p);c.push({tried:d.label??d.find??"control",changed:h!==!1,note:p??void 0}),h===!1&&console.log(te.yellow(" \xB7 clicked, but the screen did not change")),await Lt(d.afterClickWaitMs??1500)}if(d.type){await Is(d.before),a(`Step ${g+1} of ${o.steps.length}`,d.type,"typing");let{error:p}=await nr(["type","--text",d.type]);if(p)throw console.log(te.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 Is(d.before),a(`Step ${g+1} of ${o.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await nr(["key","--name",d.key]);if(p)throw console.log(te.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 Lt((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Lt(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${o.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),h;try{h=await vn(d.verify,p?{settle:!0,screen:dt()}:{})}catch(w){h=null,console.log(te.yellow(` ? could not check: ${w?.message??w}`))}if(!h&&!d.verifyOptional)throw new Error(`Could not verify: ${d.verify}`);if(h){let w=h.outcome==="confirmed"?te.green("\u2713"):h.outcome==="refuted"?te.red("\u2717"):te.yellow("?");if(console.log(` ${w} ${te.dim(h.reason)}`),!h.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(te.red(`
385
+ stopping: could not confirm \u2014 ${d.verify}`)),console.log(te.dim(` ${h.reason}`)),console.log(te.dim(` screenshot: ${h.sighting.shot.path}`)),await Lt(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(te.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",o.title,"done"),await Lt(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Lt(2500);try{let{size:g}=Wf(i);console.log(te.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(te.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(te.red(` lesson stopped before the end.
386
386
  `)),process.exitCode=3;return}console.log(te.green(`
387
387
  done.
388
- `))});function Mf(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Fd(Pf(),"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 As(e){let t=await $n(e);if(!t.ok)throw new Error(`Not ready: ${e}. ${t.reason}`)}async function Zi(e){try{let{stdout:t}=await er(Re,e),o=JSON.parse(t||"{}");return o.ok===!1?{error:String(o.error??"refused")}:{error:null,changed:o.changed}}catch(t){try{let o=JSON.parse(t?.stdout||"{}");if(o.error)return{error:String(o.error)}}catch{}return{error:t?.message??"failed"}}}async function Lf(e,t=[]){try{let o=await Zn({max:45});if(o.candidates.length<2)return null;let n=await ct(wn,ys({request:e,app:o.app,window:o.window,candidates:o.candidates,priorAttempts:t}),ws(o.candidates),{features:{app:o.app,via:"teach",ocr:o.usedOCR}});if(!n)return null;let s=bs(n.answers,o.candidates);return s.present<.5?null:ln(o,s.id)}catch{return null}}function Ff(e,t){if(e?.trim().toLowerCase()===At)return{provider:"system",elevenlabs:cn(),system:null,fallback:!0};let o=e?Kn(e,an()):null;if(o)return{provider:"system",elevenlabs:cn(),system:o.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=I(),s=t||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(te.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Tc(Ec(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:cn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(te.dim(` no agent voice (${String(n?.message??n).split(`
389
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:cn(),system:null,fallback:!0}}}var Uf=new $o;async function qf(e,t){t&&await Uf.say({voice:t,text:e})}var Pt=e=>new Promise(t=>setTimeout(t,e));ie();import{Command as qd}from"commander";import He from"chalk";import{createInterface as Wd}from"readline";var Wf=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function _o(e,t,o){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Wf()+t,{method:e,headers:n,body:o?JSON.stringify(o):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Bf(e){e.type==="line"?console.log(`${He.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(He.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(He.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(He.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(He.dim(" \xB7 hushed")):e.type==="error"?console.log(He.red(` error: ${e.error}`)):e.type==="end"&&console.log(He.dim(` \xB7 ended (${e.reason})`))}function Bd(e){if(!e.length)return"no hand-overs measured";let t=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${t[Math.floor(t.length/2)]} ms, max ${t.at(-1)} ms over ${e.length} hand-overs`}async function Jf(e,t,o){let n=I(o.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await _o("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Cc(()=>n,()=>d),i.usePool(await Ic(Sc()))}let r=e.map(d=>s[d]?Xn(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 Dc({topic:t,context:o.context,maxTurns:Number(o.turns)||10,speakers:r,speech:new $o,listener:n.voice.listener,model:(d,u)=>ko({system:u})});l.on(Bf),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(He.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=Wd({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(He.dim(` ${Bd(l.gaps)}`))}async function Hf(e,t,o){let n=await _o("POST","/talk",{agents:e,topic:t,context:o.context,maxTurns:Number(o.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=Wd({input:process.stdin});s.on("line",a=>{a.trim()&&_o("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void _o("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await _o("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${He.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(He.dim(` ${Bd(r)}`))}var Jd=new qd().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,t,o,n)=>{let s=o.join(" ");try{await(n.local?Jf:Hf)([e,t],s,n),process.exit(0)}catch(i){console.error(He.red(` ${i?.message??i}`)),process.exit(1)}}),Hd=new qd().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,t,o)=>{let n=t==="on"?!0:t==="off"?!1:t==="default"?null:void 0;n===void 0&&(console.error(He.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await _o("POST","/narration",{[o.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(He.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ie();import{Command as Gf}from"commander";import X from"chalk";import{existsSync as zf,readFileSync as zd,writeFileSync as Yd}from"fs";import{resolve as Gd}from"path";$m();var Do=new Gf().name("voice").description("list installed system voices and pick each agent's voice");function tr(e){let t=e?[e]:[Gd(process.cwd(),"agentx.json"),Gd(process.cwd(),".agentx/config.json")],o=t.find(n=>zf(n));if(!o)throw new Error(`No config found. Searched: ${t.join(", ")}`);return o}function Yf(e,t,o,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[t];if(!c)throw new Error(`No agent "${t}" 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&&!o)throw new Error("--lang needs a voice");if(!o&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=h=>{if(!a){l.system=h;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:h}},f=a?` for ${a}`:"";if(o){let h=o.trim().toLowerCase()===At,w=h?null:Kn(o,s,a??e?.voice?.locale),k=w?`system voice ${mi(w)}`:"the OS default voice";if((w||h)&&g==="system")u(h?At:o),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!h&&!a)l.elevenlabsVoiceId=o,d.push(`ElevenLabs voice ${o}`);else if(w||h)u(h?At:o),d.push(`fallback ${k}${f}`);else throw new Error(`"${o}" 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,[t]:{...c,voice:l}}},summary:p}}Do.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 t=an(),o;try{o=I(e.config)}catch{}let n=o?.voice.locale??"en",s=new Map,i=o?Ac(o.agents,o.voice,t):new Map;if(o)for(let[a,c]of Object.entries(o.agents)){let l=i.get(a),g=Object.values(pi(a,c.voice?.system,c.voice?.gender,o.voice,t));for(let d of new Set([l,...g]))d&&s.set(d.id,[...s.get(d.id)??[],a])}if(!t.length)console.log(X.yellow(`
388
+ `))});function Jf(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${Jd(Bf(),"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 Is(e){let t=await vn(e);if(!t.ok)throw new Error(`Not ready: ${e}. ${t.reason}`)}async function nr(e){try{let{stdout:t}=await sr(_e,e),o=JSON.parse(t||"{}");return o.ok===!1?{error:String(o.error??"refused")}:{error:null,changed:o.changed}}catch(t){try{let o=JSON.parse(t?.stdout||"{}");if(o.error)return{error:String(o.error)}}catch{}return{error:t?.message??"failed"}}}async function Hf(e,t=[]){try{let o=await ns({max:45});if(o.candidates.length<2)return null;let n=await lt($n,ks({request:e,app:o.app,window:o.window,candidates:o.candidates,priorAttempts:t}),vs(o.candidates),{features:{app:o.app,via:"teach",ocr:o.usedOCR}});if(!n)return null;let s=xs(n.answers,o.candidates);return s.present<.5?null:gn(o,s.id)}catch{return null}}function Gf(e,t){if(e?.trim().toLowerCase()===jt)return{provider:"system",elevenlabs:dn(),system:null,fallback:!0};let o=e?es(e,ln()):null;if(o)return{provider:"system",elevenlabs:dn(),system:o.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=I(),s=t||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(te.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Cc(Oc(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:dn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(te.dim(` no agent voice (${String(n?.message??n).split(`
389
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:dn(),system:null,fallback:!0}}}var zf=new vo;async function Yf(e,t){t&&await zf.say({voice:t,text:e})}var Lt=e=>new Promise(t=>setTimeout(t,e));ne();import{Command as Gd}from"commander";import Ge from"chalk";import{createInterface as zd}from"readline";var Vf=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Po(e,t,o){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Vf()+t,{method:e,headers:n,body:o?JSON.stringify(o):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Kf(e){e.type==="line"?console.log(`${Ge.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ge.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ge.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ge.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ge.dim(" \xB7 hushed")):e.type==="error"?console.log(Ge.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ge.dim(` \xB7 ended (${e.reason})`))}function Yd(e){if(!e.length)return"no hand-overs measured";let t=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${t[Math.floor(t.length/2)]} ms, max ${t.at(-1)} ms over ${e.length} hand-overs`}async function Xf(e,t,o){let n=I(o.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await Po("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Pc(()=>n,()=>d),i.usePool(await Dc(jc()))}let r=e.map(d=>s[d]?ts(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 Uc({topic:t,context:o.context,maxTurns:Number(o.turns)||10,speakers:r,speech:new vo,listener:n.voice.listener,model:(d,u)=>xo({system:u})});l.on(Kf),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ge.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=zd({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(Ge.dim(` ${Yd(l.gaps)}`))}async function Qf(e,t,o){let n=await Po("POST","/talk",{agents:e,topic:t,context:o.context,maxTurns:Number(o.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=zd({input:process.stdin});s.on("line",a=>{a.trim()&&Po("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Po("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Po("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ge.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(Ge.dim(` ${Yd(r)}`))}var Vd=new Gd().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,t,o,n)=>{let s=o.join(" ");try{await(n.local?Xf:Qf)([e,t],s,n),process.exit(0)}catch(i){console.error(Ge.red(` ${i?.message??i}`)),process.exit(1)}}),Kd=new Gd().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,t,o)=>{let n=t==="on"?!0:t==="off"?!1:t==="default"?null:void 0;n===void 0&&(console.error(Ge.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await Po("POST","/narration",{[o.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ge.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ne();import{Command as Zf}from"commander";import X from"chalk";import{existsSync as eh,readFileSync as Qd,writeFileSync as Zd}from"fs";import{resolve as Xd}from"path";Tm();var Mo=new Zf().name("voice").description("list installed system voices and pick each agent's voice");function ir(e){let t=e?[e]:[Xd(process.cwd(),"agentx.json"),Xd(process.cwd(),".agentx/config.json")],o=t.find(n=>eh(n));if(!o)throw new Error(`No config found. Searched: ${t.join(", ")}`);return o}function th(e,t,o,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[t];if(!c)throw new Error(`No agent "${t}" 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&&!o)throw new Error("--lang needs a voice");if(!o&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=h=>{if(!a){l.system=h;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:h}},f=a?` for ${a}`:"";if(o){let h=o.trim().toLowerCase()===jt,w=h?null:es(o,s,a??e?.voice?.locale),k=w?`system voice ${hi(w)}`:"the OS default voice";if((w||h)&&g==="system")u(h?jt:o),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!h&&!a)l.elevenlabsVoiceId=o,d.push(`ElevenLabs voice ${o}`);else if(w||h)u(h?jt:o),d.push(`fallback ${k}${f}`);else throw new Error(`"${o}" 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,[t]:{...c,voice:l}}},summary:p}}Mo.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 t=ln(),o;try{o=I(e.config)}catch{}let n=o?.voice.locale??"en",s=new Map,i=o?Ic(o.agents,o.voice,t):new Map;if(o)for(let[a,c]of Object.entries(o.agents)){let l=i.get(a),g=Object.values(yi(a,c.voice?.system,c.voice?.gender,o.voice,t));for(let d of new Set([l,...g]))d&&s.set(d.id,[...s.get(d.id)??[],a])}if(!t.length)console.log(X.yellow(`
390
390
  No system voices found (system voices need macOS).
391
- `));else{let a=e.all?gi(t,""):gi(t,n);console.log(X.bold(`
391
+ `));else{let a=e.all?fi(t,""):fi(t,n);console.log(X.bold(`
392
392
  System voices${e.all?"":` (${n})`}, best first
393
393
  `));for(let c of a){let l=c.siri?X.magenta("siri"):c.quality==="standard"?X.dim("standard"):X.green(c.quality),g=s.get(c.id)?.join(", ");console.log(` ${(c.siri?`siri:${c.name.toLowerCase()}`:c.name).padEnd(12)} ${c.locale.padEnd(6)} ${l.padEnd(18)} ${X.dim((c.gender??"").padEnd(7))} ${g?X.cyan(g):""}`)}t.some(c=>c.quality!=="standard")||(console.log(X.dim(`
394
- More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(X.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}let r=o?Oc(o,t):[];if(r.length){console.log(X.bold.yellow(`
394
+ More natural voices are free: System Settings \u2192 Accessibility \u2192 Spoken Content \u2192`)),console.log(X.dim(" System Voice \u2192 Manage Voices, then download a Premium or Enhanced voice.")))}let r=o?Rc(o,t):[];if(r.length){console.log(X.bold.yellow(`
395
395
  Not installed
396
- `));for(let a of r)console.log(` ${ui(a.voice).padEnd(24)} ${X.cyan(a.agents.join(", "))}`);console.log(X.dim(`
397
- Reinstall in ${jc}.`)),console.log(X.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(o){console.log(X.bold(`
396
+ `));for(let a of r)console.log(` ${wi(a.voice).padEnd(24)} ${X.cyan(a.agents.join(", "))}`);console.log(X.dim(`
397
+ Reinstall in ${Nc}.`)),console.log(X.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(o){console.log(X.bold(`
398
398
  Agents
399
- `));for(let[a,c]of Object.entries(o.agents)){let l=c.voice?.provider??o.voice.provider,g=h=>h?mi(h):X.dim("system default"),d=Object.entries(pi(a,c.voice?.system,c.voice?.gender,o.voice,t)).filter(([,h])=>(h?.id??null)!==(i.get(a)?.id??null)).map(([h,w])=>`${X.dim(`${h}:`)} ${g(w)}`).join(X.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??X.dim("(default voice)")}`:`system ${g(i.get(a))}${d?X.dim(" \xB7 ")+d:""}`,f=r.filter(h=>h.agents.includes(a)).map(h=>ui(h.voice)),p=f.length?X.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?X.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});Do.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${At}" 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,t,o)=>{try{let n=tr(o.config),{raw:s,summary:i}=Yf(JSON.parse(zd(n,"utf8")),e,t,o,an());Yd(n,JSON.stringify(s,null,2)+`
400
- `),console.log(X.green(` ${e}: ${i}`)),console.log(X.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});function Vd(e,t){let o=Nc(t,I(e));if(o.length)throw new Error(o.map(s=>s.message).join(`
401
- `));let n=JSON.parse(zd(e,"utf8"));Rc(n,t),Yd(e,JSON.stringify(n,null,2)+`
402
- `)}Do.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${Wr.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,t,o)=>{try{let n=tr(o.config);if(e&&t){let i=t==="default"?null:t;Vd(n,{agents:{[e]:{palette:i}}}),console.log(X.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(X.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=I(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(X.bold(`
399
+ `));for(let[a,c]of Object.entries(o.agents)){let l=c.voice?.provider??o.voice.provider,g=h=>h?hi(h):X.dim("system default"),d=Object.entries(yi(a,c.voice?.system,c.voice?.gender,o.voice,t)).filter(([,h])=>(h?.id??null)!==(i.get(a)?.id??null)).map(([h,w])=>`${X.dim(`${h}:`)} ${g(w)}`).join(X.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??X.dim("(default voice)")}`:`system ${g(i.get(a))}${d?X.dim(" \xB7 ")+d:""}`,f=r.filter(h=>h.agents.includes(a)).map(h=>wi(h.voice)),p=f.length?X.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?X.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});Mo.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${jt}" 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,t,o)=>{try{let n=ir(o.config),{raw:s,summary:i}=th(JSON.parse(Qd(n,"utf8")),e,t,o,ln());Zd(n,JSON.stringify(s,null,2)+`
400
+ `),console.log(X.green(` ${e}: ${i}`)),console.log(X.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});function eg(e,t){let o=Mc(t,I(e));if(o.length)throw new Error(o.map(s=>s.message).join(`
401
+ `));let n=JSON.parse(Qd(e,"utf8"));Lc(n,t),Zd(e,JSON.stringify(n,null,2)+`
402
+ `)}Mo.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${zr.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,t,o)=>{try{let n=ir(o.config);if(e&&t){let i=t==="default"?null:t;eg(n,{agents:{[e]:{palette:i}}}),console.log(X.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(X.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=I(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(X.bold(`
403
403
  Orb palettes
404
- `));for(let i of qr)console.log(` ${i.id.padEnd(10)} ${X.dim(i.colors.join(" "))}`);console.log(X.bold(`
404
+ `));for(let i of Gr)console.log(` ${i.id.padEnd(10)} ${X.dim(i.colors.join(" "))}`);console.log(X.bold(`
405
405
  Agents
406
- `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=bo(i,r).color,c=Br(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${X.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});Do.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, ${fi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${fi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let t=tr(e.config),o={};e.timeout!==void 0&&(o.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(o.maxHeight=Number(e.maxHeight)),Object.keys(o).length&&Vd(t,{general:{card:o}});let n=I(t).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(o).length&&console.log(X.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(t){console.log(X.red(` ${t.message}`)),process.exit(1)}});import{Command as Vf}from"commander";import N from"chalk";var Mt=new Vf().name("attach").description("wear an agentx agent identity in this Claude Code session"),Ts=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${zt()}`;function js(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Os(e,t,o){let n=await fetch(`${e}${t}`,{method:o?"POST":"GET",headers:{"Content-Type":"application/json"},body:o?JSON.stringify(o):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 Is(e){let t=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(t)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:t}function Xd(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function Kf(e,t=!1){let o=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=t?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(o)} ${Xd(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function Xf(e){let t=e.filter(n=>n.agentIds.length>0),o=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:t,watching:o,idle:e.length-t.length-o.length}}function Qf(e,t=!1){let o=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=t?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(o)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Mt.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${si.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Ts).action(async(e,t)=>{let o=js(t.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>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),la(t.mode)||(console.error(N.red(`Invalid mode "${t.mode}". Expected one of: ${si.join(", ")}`)),process.exit(1)),mn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Os(t.url,"/attach/bind",{sessionId:o,agentId:e,mode:t.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${Xd(t.mode)(t.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(t.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":t.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: ${Is(n)}`)),process.exit(1)}});function Kd(e){let t=(e??"").split(",").map(o=>o.trim()).filter(Boolean);return t.length?t:void 0}function Zf(e){let t=Kd(e.kinds),o=Kd(e.agents);if(!t&&!o&&!e.match)return;let n={kinds:t??["*"]};return o&&(n.agents=o),e.match&&(n.match=e.match),[n]}Mt.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",Ts).action(async e=>{let t=js(e.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>")}.`),process.exit(1)),mn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await Os(e.url,"/attach/watch",{sessionId:t,cwd:process.cwd(),subscriptions:Zf(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(o){console.error(N.red(`Watch failed: ${Is(o)}`)),process.exit(1)}});Mt.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",Ts).action(async e=>{let t=js(e.session);t||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Os(e.url,"/attach/detach",{sessionId:t,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(o){console.error(N.red(`Detach failed: ${Is(o)}`)),process.exit(1)}});Mt.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Ts).option("--json","raw JSON output").action(async e=>{let t=js();try{let n=(await Os(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:mn(),sessions:n},null,2));return}console.log(),console.log(mn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(gn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=Xf(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)Kf(a,a.sessionId===t);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)Qf(a,a.sessionId===t)}r>0&&console.log(N.gray(`
407
- ${r} registered session(s) with no binding.`)),console.log()}catch(o){console.error(N.red(`Could not read attach state: ${Is(o)}`)),process.exit(1)}});Mt.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 t=String(e.port||zt()),o=fl(t,{path:e.path,withGuard:e.guard});console.log(o.changed?`${N.green("\u2713")} Installed attach hooks in ${N.gray(o.path)}`:`${N.green("\u2713")} Attach hooks already up to date in ${N.gray(o.path)}`),console.log(N.gray(` Events: ${o.events.join(", ")} \u2192 127.0.0.1:${t}`)),o.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
406
+ `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=ko(i,r).color,c=Yr(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${X.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});Mo.command("card").description("the answer shown in the pill: how long it stays open and how tall it grows").option("--timeout <seconds>",`seconds it stays open once spoken, ${bi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${bi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let t=ir(e.config),o={};e.timeout!==void 0&&(o.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(o.maxHeight=Number(e.maxHeight)),Object.keys(o).length&&eg(t,{general:{card:o}});let n=I(t).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(o).length&&console.log(X.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(t){console.log(X.red(` ${t.message}`)),process.exit(1)}});import{Command as oh}from"commander";import N from"chalk";var Ft=new oh().name("attach").description("wear an agentx agent identity in this Claude Code session"),Cs=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Yt()}`;function Ns(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Rs(e,t,o){let n=await fetch(`${e}${t}`,{method:o?"POST":"GET",headers:{"Content-Type":"application/json"},body:o?JSON.stringify(o):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 _s(e){let t=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(t)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:t}function og(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function nh(e,t=!1){let o=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=t?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(o)} ${og(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function sh(e){let t=e.filter(n=>n.agentIds.length>0),o=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:t,watching:o,idle:e.length-t.length-o.length}}function ih(e,t=!1){let o=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=t?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(o)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Ft.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${ci.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Cs).action(async(e,t)=>{let o=Ns(t.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>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),pa(t.mode)||(console.error(N.red(`Invalid mode "${t.mode}". Expected one of: ${ci.join(", ")}`)),process.exit(1)),un()||(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 Rs(t.url,"/attach/bind",{sessionId:o,agentId:e,mode:t.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${og(t.mode)(t.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(t.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":t.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: ${_s(n)}`)),process.exit(1)}});function tg(e){let t=(e??"").split(",").map(o=>o.trim()).filter(Boolean);return t.length?t:void 0}function rh(e){let t=tg(e.kinds),o=tg(e.agents);if(!t&&!o&&!e.match)return;let n={kinds:t??["*"]};return o&&(n.agents=o),e.match&&(n.match=e.match),[n]}Ft.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",Cs).action(async e=>{let t=Ns(e.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>")}.`),process.exit(1)),un()||(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 Rs(e.url,"/attach/watch",{sessionId:t,cwd:process.cwd(),subscriptions:rh(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(o){console.error(N.red(`Watch failed: ${_s(o)}`)),process.exit(1)}});Ft.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",Cs).action(async e=>{let t=Ns(e.session);t||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Rs(e.url,"/attach/detach",{sessionId:t,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(o){console.error(N.red(`Detach failed: ${_s(o)}`)),process.exit(1)}});Ft.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Cs).option("--json","raw JSON output").action(async e=>{let t=Ns();try{let n=(await Rs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:un(),sessions:n},null,2));return}console.log(),console.log(un()?`${N.green("\u2713")} Attach hooks installed ${N.gray(pn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=sh(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)nh(a,a.sessionId===t);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)ih(a,a.sessionId===t)}r>0&&console.log(N.gray(`
407
+ ${r} registered session(s) with no binding.`)),console.log()}catch(o){console.error(N.red(`Could not read attach state: ${_s(o)}`)),process.exit(1)}});Ft.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 t=String(e.port||Yt()),o=$l(t,{path:e.path,withGuard:e.guard});console.log(o.changed?`${N.green("\u2713")} Installed attach hooks in ${N.gray(o.path)}`:`${N.green("\u2713")} Attach hooks already up to date in ${N.gray(o.path)}`),console.log(N.gray(` Events: ${o.events.join(", ")} \u2192 127.0.0.1:${t}`)),o.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
408
408
  settings \u2014 without this an attached production identity would be less
409
- 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(t){console.error(N.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});Mt.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 t=hl({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(t.path)} (${t.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(t){console.error(N.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});ie();import{Command as eh}from"commander";import we from"chalk";var Cs=new eh().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Zd(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=I(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function eg(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function Qd(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function th(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}Cs.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:t,token:o}=Zd(e),n;try{n=await fetch(`${t}/api/processes`,{headers:eg(o)})}catch(r){console.log(we.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${t}/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=th(r.state)(r.state.padEnd(9)),c=Qd(r.spawnedAt),l=r.lastTurnAt?Qd(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}`)}});Cs.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,t,o,n)=>{let{baseUrl:s,token:i}=Zd(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:eg(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,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}:${t}:${o}`))});import{Command as oh}from"commander";import Me from"chalk";import{existsSync as or,rmSync as nh}from"fs";import{resolve as nr}from"path";var Po=new oh().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Po.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,t,o)=>{t.length===0&&(console.log(Me.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await pa(e,t,{verbose:n}),r=Date.now()-s;console.log(Me.green(` \u2713 indexed ${i.docs} doc(s) for ${Me.bold(e)} in ${r}ms`)),console.log(Me.dim(` \u2192 ${i.path}`))});Po.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=nr(e.cwd,".agentx","rag");if(!or(t)){console.log(Me.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>or(nr(t,s,"index.json")));if(n.length===0){console.log(Me.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ii(s);console.log(` ${Me.bold(s)} ${i.docs} doc(s) ${Me.dim(i.path)}`)}});Po.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,t,o)=>{let n=parseInt(o.k,10)||5,s=ua(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ii(e);i.exists?console.log(Me.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Me.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Me.bold(i.title)} ${Me.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Me.dim(i.path)}`),console.log(` ${Me.dim(i.snippet.slice(0,200))}`)});Po.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=nr(process.cwd(),".agentx","rag",e);if(!or(t)){console.log(Me.dim(` no index for ${e} \u2014 nothing to clear`));return}nh(t,{recursive:!0,force:!0}),console.log(Me.green(` \u2713 cleared index for ${e}`))});ie();import{Command as sh}from"commander";import Q from"chalk";import Mo from"prompts";var so=new sh().name("backlog").description("manage the local backlog used by business workSource=backlog");function Sn(e){let t=I(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new Fc(n)}}function ih(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function rh(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}so.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:t}=Sn(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(Q.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${rh(n.status).padEnd(7)} ${ih(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});so.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=Sn(o.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Uc([t],i.source,n.config),a=await wi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Q.dim(" sync:"),...c));console.log(a.ok?Q.dim(` synced -> ${a.url??i.source.type}`):Q.yellow(` sync failed: ${a.error}`))}});so.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,t)=>{let o=Sn(t.config);o.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await wi(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});so.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=Sn(t.config);o.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});so.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 t=Sn(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(Q.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let w=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Mo({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?ch(t.config):lh(t.config);w.length?(i=(await Mo({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Mo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Mo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Mo({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Q.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await dh(t.config,i,a):await gh(t.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let k=yi({type:s,project:l,iid:w.iid,url:w.url}),$=g.has(k),b=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${b}${$?Q.dim(" (already imported)"):""}`,value:w,disabled:$}}),f=(await Mo({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(Q.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?ah(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:yi(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=t.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function ah(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function ch(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function lh(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function dh(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/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 gh(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;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(tg)}i=`https://api.github.com/repos/${t}/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(tg):[]}function tg(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as mh}from"commander";import W from"chalk";import{existsSync as ph,readFileSync as uh}from"fs";import{resolve as fh}from"path";import hh from"prompts";ie();function og(e){let t=e||fh(process.cwd(),"agentx.json");return ph(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(uh(t,"utf-8"))}async function yh(e,t){if(!e)return;if(e==="me"){let n=t?.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 hh([{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 o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var bt=new mh().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');bt.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: ${ci})`,ci).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,t)=>{if(!e){bt.help();return}t.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let o=ai(e);o||(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=og(t.config),s=Hr(n);n.agents?.[t.agent]||(console.log(W.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await yh(t.notify,s),r=t.id||Sa(o.matched,t.agent),a=Aa({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:Ea(t.onError),enabled:!t.disabled}),c=a.onError,l=await ye(d=>Oe(d,`crons.${r}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(W.dim(` Agent: ${t.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});bt.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 o=og(e.config).crons||{},n=Object.entries(o);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=ja(Ta(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,t]of[["on",!0],["off",!1]])bt.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await Ca(o,t);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});bt.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ye(o=>{if(!wo(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);wa(o,`crons.${e}`)});t.success||(console.log(W.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",Oa,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Ia,"reject an agent's pending create/delete request (drops the request)"]])bt.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await t(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."))});bt.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ai(t);o||(console.log(W.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(W.green(` "${t}"`)),console.log(W.dim(` \u2192 ${o.cron}`)),console.log(W.dim(` \u2192 ${o.human}`))});import{Command as wh}from"commander";import xe from"chalk";var Lt=new wh("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),bh={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function ng(){return{root:process.cwd()}}function sr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function $h(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${bh[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${sr(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 ${sr(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}`:""}`))}Lt.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 t=cc(ng(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(xe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(xe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)$h(o),console.log();console.log(xe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function ir(e,t,o){let n=os(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await lc(ng(),e,t,{force:o.force,note:o.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Lt.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,t)=>ir(e,"yes",t));Lt.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,t)=>ir(e,"no",t));Lt.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,t)=>ir(e,"later",t));Lt.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: ${rc.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 t=os(),o=ac(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:t});if(!o.ok){console.error(xe.red(` ${o.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${o.card.id} raised; expires ${sr(o.card.expires)}, then: ${o.card.if_silent}`))});Lt.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 t={},o=(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(t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),t.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let a=Xc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(t).some(a=>a!==void 0)){let a=await Qc(t);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=os(),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 Bh}from"commander";import Lo from"chalk";import se from"chalk";import An from"prompts";import{readFileSync as kh,writeFileSync as vh,existsSync as xh}from"fs";import{resolve as sg}from"path";var Sh=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Eh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function rr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function ig(e=".env"){let t=sg(e);if(!xh(t))return[];let o=kh(t,"utf-8"),n=[];for(let s of o.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(Sh);i?n.push({kind:"kv",key:i[1],value:Eh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Ah(e){return e.map(t=>t.kind==="kv"?`${t.key}=${rr(t.value)}`:t.raw).join(`
409
+ 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(t){console.error(N.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});Ft.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 t=kl({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(t.path)} (${t.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(t){console.error(N.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});ne();import{Command as ah}from"commander";import we from"chalk";var Ds=new ah().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function sg(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=I(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function ig(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function ng(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function ch(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}Ds.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:t,token:o}=sg(e),n;try{n=await fetch(`${t}/api/processes`,{headers:ig(o)})}catch(r){console.log(we.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${t}/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=ch(r.state)(r.state.padEnd(9)),c=ng(r.spawnedAt),l=r.lastTurnAt?ng(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}`)}});Ds.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,t,o,n)=>{let{baseUrl:s,token:i}=sg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:ig(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,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}:${t}:${o}`))});import{Command as lh}from"commander";import Le from"chalk";import{existsSync as rr,rmSync as dh}from"fs";import{resolve as ar}from"path";var Lo=new lh().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Lo.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,t,o)=>{t.length===0&&(console.log(Le.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await ya(e,t,{verbose:n}),r=Date.now()-s;console.log(Le.green(` \u2713 indexed ${i.docs} doc(s) for ${Le.bold(e)} in ${r}ms`)),console.log(Le.dim(` \u2192 ${i.path}`))});Lo.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=ar(e.cwd,".agentx","rag");if(!rr(t)){console.log(Le.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>rr(ar(t,s,"index.json")));if(n.length===0){console.log(Le.dim(" (no indexes)"));return}for(let s of n.sort()){let i=li(s);console.log(` ${Le.bold(s)} ${i.docs} doc(s) ${Le.dim(i.path)}`)}});Lo.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,t,o)=>{let n=parseInt(o.k,10)||5,s=wa(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=li(e);i.exists?console.log(Le.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Le.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Le.bold(i.title)} ${Le.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Le.dim(i.path)}`),console.log(` ${Le.dim(i.snippet.slice(0,200))}`)});Lo.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=ar(process.cwd(),".agentx","rag",e);if(!rr(t)){console.log(Le.dim(` no index for ${e} \u2014 nothing to clear`));return}dh(t,{recursive:!0,force:!0}),console.log(Le.green(` \u2713 cleared index for ${e}`))});ne();import{Command as gh}from"commander";import Q from"chalk";import Fo from"prompts";var io=new gh().name("backlog").description("manage the local backlog used by business workSource=backlog");function An(e){let t=I(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new Jc(n)}}function mh(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function ph(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}io.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:t}=An(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(Q.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${ph(n.status).padEnd(7)} ${mh(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});io.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=An(o.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Hc([t],i.source,n.config),a=await vi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Q.dim(" sync:"),...c));console.log(a.ok?Q.dim(` synced -> ${a.url??i.source.type}`):Q.yellow(` sync failed: ${a.error}`))}});io.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,t)=>{let o=An(t.config);o.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await vi(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});io.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=An(t.config);o.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});io.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 t=An(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(Q.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let w=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Fo({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?fh(t.config):hh(t.config);w.length?(i=(await Fo({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Fo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Fo({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Fo({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Q.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await yh(t.config,i,a):await wh(t.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let k=ki({type:s,project:l,iid:w.iid,url:w.url}),$=g.has(k),b=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${b}${$?Q.dim(" (already imported)"):""}`,value:w,disabled:$}}),f=(await Fo({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(Q.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?uh(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:ki(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=t.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function uh(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function fh(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function hh(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function yh(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/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 wh(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;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(rg)}i=`https://api.github.com/repos/${t}/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(rg):[]}function rg(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as bh}from"commander";import W from"chalk";import{existsSync as $h,readFileSync as kh}from"fs";import{resolve as vh}from"path";import xh from"prompts";ne();function ag(e){let t=e||vh(process.cwd(),"agentx.json");return $h(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(kh(t,"utf-8"))}async function Sh(e,t){if(!e)return;if(e==="me"){let n=t?.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 xh([{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 o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var $t=new bh().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');$t.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: ${mi})`,mi).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,t)=>{if(!e){$t.help();return}t.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let o=gi(e);o||(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=ag(t.config),s=Kr(n);n.agents?.[t.agent]||(console.log(W.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Sh(t.notify,s),r=t.id||ja(o.matched,t.agent),a=Ia({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:Oa(t.onError),enabled:!t.disabled}),c=a.onError,l=await pe(d=>Oe(d,`crons.${r}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(W.dim(` Agent: ${t.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});$t.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 o=ag(e.config).crons||{},n=Object.entries(o);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=Na(Ca(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,t]of[["on",!0],["off",!1]])$t.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await Da(o,t);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});$t.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await pe(o=>{if(!$o(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);va(o,`crons.${e}`)});t.success||(console.log(W.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",Ra,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",_a,"reject an agent's pending create/delete request (drops the request)"]])$t.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await t(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."))});$t.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=gi(t);o||(console.log(W.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(W.green(` "${t}"`)),console.log(W.dim(` \u2192 ${o.cron}`)),console.log(W.dim(` \u2192 ${o.human}`))});import{Command as Eh}from"commander";import xe from"chalk";var Ut=new Eh("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Ah={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp"};function cg(){return{root:process.cwd()}}function cr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Th(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Ah[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${cr(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 ${cr(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}`:""}`))}Ut.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 t=mc(cg(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(xe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(xe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)Th(o),console.log();console.log(xe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function lr(e,t,o){let n=rs(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await pc(cg(),e,t,{force:o.force,note:o.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Ut.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,t)=>lr(e,"yes",t));Ut.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,t)=>lr(e,"no",t));Ut.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,t)=>lr(e,"later",t));Ut.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: ${dc.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 t=rs(),o=gc(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:t});if(!o.ok){console.error(xe.red(` ${o.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${o.card.id} raised; expires ${cr(o.card.expires)}, then: ${o.card.if_silent}`))});Ut.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 t={},o=(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(t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),t.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let a=ol(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(t).some(a=>a!==void 0)){let a=await nl(t);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=rs(),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 Kh}from"commander";import Uo from"chalk";import ie from"chalk";import jn from"prompts";import{readFileSync as jh,writeFileSync as Oh,existsSync as Ih}from"fs";import{resolve as lg}from"path";var Ch=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Nh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function dr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function dg(e=".env"){let t=lg(e);if(!Ih(t))return[];let o=jh(t,"utf-8"),n=[];for(let s of o.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(Ch);i?n.push({kind:"kv",key:i[1],value:Nh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Rh(e){return e.map(t=>t.kind==="kv"?`${t.key}=${dr(t.value)}`:t.raw).join(`
410
410
  `)+`
411
- `}function En(e,t,o=".env"){let n=sg(o),s=ig(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${rr(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${rr(t)}`})),vh(n,Ah(s))}function ar(e,t=".env"){return ig(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var rg="https://t.me/BotFather";async function Th(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function jh(e,t){let o=Date.now()+t,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()<o;)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 ag(e={}){console.log(),console.log(se.bold(" Connect Telegram")),console.log(),console.log(se.dim(` 1. Open ${rg}`)),console.log(se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await An({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:$}=await import("child_process"),b=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$(b,[rg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await An({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:$=>/^\d+:[A-Za-z0-9_-]{20,}$/.test($.trim())||"That doesn't look like a Telegram token"});o||(console.log(se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Th(o.trim());n||(console.log(se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(se.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(se.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(se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await An({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(b=>({title:b,value:b})),initial:0})).agent),g||(console.log(se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await An({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:b=>/^[a-z0-9-]+$/i.test(b)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(se.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;En(f,o.trim()),process.env[f]=o.trim();let p=await ye($=>{Oe($,"channels.telegram.enabled",!0),Oe($,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let b=wo($,`agents.${g}.mentions`)||[],E=`@${n.username}`;b.includes(E)||(b.push(E),Oe($,`agents.${g}.mentions`,b))},{configPath:e.configPath});if(p.success||(console.log(se.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(se.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(se.dim(` Token stored in .env as ${f}`)),console.log(se.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(se.dim(" Daemon hot-reloaded.")):console.log(se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await An({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(se.dim(" Waiting up to 90s..."));let w=await jh(o.trim(),9e4);if(!w){console.log(se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(se.dim(" agentx config set notifications.destination.channel telegram")),console.log(se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(se.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ye($=>{Oe($,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(se.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(se.green(" \u2713 Default --notify target set")),console.log(se.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(se.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(se.dim(" Daemon hot-reloaded."))}import be from"chalk";import cr from"prompts";import{existsSync as dr,mkdirSync as Oh,readdirSync as Ih,readFileSync as cg}from"fs";import{resolve as lr}from"path";var Ch=".agentx/whatsapp-sessions";function Nh(){let e=lr(process.cwd(),".agentx/daemon.pid");if(!dr(e))return!1;try{let t=parseInt(cg(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Rh(e){if(!dr(e))return!1;try{return Ih(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function _h(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;Oh(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.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(()=>{t(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){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(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),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function lg(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 cr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||lr(process.cwd(),"agentx.json");dr(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(cg(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Ch,s=lr(process.cwd(),n),i=Object.keys(o.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 cr({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(Rh(s)&&a){let{keep:l}=await cr({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 _h(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 Dh}from"crypto";import Ae from"chalk";import dg from"prompts";var Ns="agentx-mesh:",Rs="//join/";function Ph(e){return Buffer.from(e,"utf-8").toString("base64url")}function Mh(e){return Buffer.from(e,"base64url").toString("utf-8")}function Lh(e){return`${Ns}${Rs}${Ph(JSON.stringify(e))}`}function Fh(e){if(!e.startsWith(`${Ns}${Rs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ns}${Rs}\u2026`);let t=e.slice(Ns.length+Rs.length),o=JSON.parse(Mh(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function Uh(){return Dh(32).toString("hex")}function qh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Wh(e){return e?.node?.name||e?.node?.id||"node"}async function gg(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=ar("MESH_TOKEN");r||(r=Uh(),En("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||qh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await dg({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=Lh({url:a,token:r,name:Wh(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function mg(e,t={}){let o;try{o=Fh(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=ar("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await dg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}En("MESH_TOKEN",o.token);let s=await ye(i=>{Oe(i,"mesh.enabled",!0);let r=wo(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Oe(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Fo=new Bh().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Fo.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 ag({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Fo.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 lg({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var pg=Fo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");pg.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 gg({url:e.url,configPath:e.config})});pg.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await mg(e,{configPath:t.config})});Fo.action(()=>{console.log(),console.log(Lo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Lo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Lo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Lo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Lo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Lo.dim(" GitLab connect is the next slice.")),console.log()});ie();import{Command as Jh}from"commander";import ue from"chalk";var Tn=new Jh().name("usage").description("token usage analysis and reporting");Tn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/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}`))}});Tn.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:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(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{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});Tn.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:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-6C3G65YA.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 Gh}from"fs";import{resolve as zh}from"path";ie();var Ft=new Hh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ft.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{ta(zh(process.cwd(),".env"))}catch{}let t=Yh(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-J34PSEJS.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function Yh(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}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.
412
- `)),{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:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Ft.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log($e.dim(`
411
+ `}function Tn(e,t,o=".env"){let n=lg(o),s=dg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${dr(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${dr(t)}`})),Oh(n,Rh(s))}function gr(e,t=".env"){return dg(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var gg="https://t.me/BotFather";async function _h(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function Dh(e,t){let o=Date.now()+t,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()<o;)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 mg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${gg}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await jn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:$}=await import("child_process"),b=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$(b,[gg],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await jn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:$=>/^\d+:[A-Za-z0-9_-]{20,}$/.test($.trim())||"That doesn't look like a Telegram token"});o||(console.log(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await _h(o.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ie.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await jn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(b=>({title:b,value:b})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await jn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:b=>/^[a-z0-9-]+$/i.test(b)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Tn(f,o.trim()),process.env[f]=o.trim();let p=await pe($=>{Oe($,"channels.telegram.enabled",!0),Oe($,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let b=$o($,`agents.${g}.mentions`)||[],E=`@${n.username}`;b.includes(E)||(b.push(E),Oe($,`agents.${g}.mentions`,b))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await jn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ie.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ie.dim(" Waiting up to 90s..."));let w=await Dh(o.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe($=>{Oe($,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import be from"chalk";import mr from"prompts";import{existsSync as ur,mkdirSync as Ph,readdirSync as Mh,readFileSync as pg}from"fs";import{resolve as pr}from"path";var Lh=".agentx/whatsapp-sessions";function Fh(){let e=pr(process.cwd(),".agentx/daemon.pid");if(!ur(e))return!1;try{let t=parseInt(pg(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Uh(e){if(!ur(e))return!1;try{return Mh(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function qh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;Ph(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.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(()=>{t(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){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(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),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function ug(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),Fh()){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 mr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||pr(process.cwd(),"agentx.json");ur(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(pg(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Lh,s=pr(process.cwd(),n),i=Object.keys(o.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 mr({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(Uh(s)&&a){let{keep:l}=await mr({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 qh(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{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 Wh}from"crypto";import Ae from"chalk";import fg from"prompts";var Ps="agentx-mesh:",Ms="//join/";function Bh(e){return Buffer.from(e,"utf-8").toString("base64url")}function Jh(e){return Buffer.from(e,"base64url").toString("utf-8")}function Hh(e){return`${Ps}${Ms}${Bh(JSON.stringify(e))}`}function Gh(e){if(!e.startsWith(`${Ps}${Ms}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ps}${Ms}\u2026`);let t=e.slice(Ps.length+Ms.length),o=JSON.parse(Jh(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function zh(){return Wh(32).toString("hex")}function Yh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Vh(e){return e?.node?.name||e?.node?.id||"node"}async function hg(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=gr("MESH_TOKEN");r||(r=zh(),Tn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Yh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await fg({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=Hh({url:a,token:r,name:Vh(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function yg(e,t={}){let o;try{o=Gh(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=gr("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await fg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}Tn("MESH_TOKEN",o.token);let s=await pe(i=>{Oe(i,"mesh.enabled",!0);let r=$o(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Oe(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var qo=new Kh().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");qo.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 mg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});qo.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 ug({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var wg=qo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");wg.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 hg({url:e.url,configPath:e.config})});wg.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await yg(e,{configPath:t.config})});qo.action(()=>{console.log(),console.log(Uo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Uo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Uo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Uo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Uo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Uo.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as Xh}from"commander";import fe from"chalk";var On=new Xh().name("usage").description("token usage analysis and reporting");On.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});On.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:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});On.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:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-3DYKSCIY.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(fe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${fe.dim("\xB7")} ${d}`);console.log(),console.log(fe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(fe.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(fe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(fe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(fe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(fe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=fe.dim(`${i.days}d`);console.log(` ${fe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(fe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Qh}from"commander";import $e from"chalk";import{readFileSync as Zh}from"fs";import{resolve as ey}from"path";ne();var qt=new Qh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");qt.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{ra(ey(process.cwd(),".env"))}catch{}let t=ty(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-GNMELVCM.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function ty(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}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.
412
+ `)),{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:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}qt.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log($e.dim(`
413
413
  No boards configured.
414
- `));return}console.log();for(let t of e.boards){console.log(` ${$e.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log($e.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log($e.dim(` primary label: ${t.primaryToolLabel}`)),console.log($e.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});Ft.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,t)=>{try{jn(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.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:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});Ft.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,t)=>{try{jn(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(t.name&&(s.name=t.name,i.push(`name="${t.name}"`)),t.projects){let r=String(t.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(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=t.label,i.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.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(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});var gr=Ft.command("column").description("manage a board's columns (add / remove / edit / list)");gr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(Gh("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.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(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});gr.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,t,o)=>{try{jn(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===t))throw new Error(`column "${t}" already exists on board "${e}"`);let r={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");r.mapsToLabel=o.label}return o.accent&&(r.accent=o.accent),i.columns.push(r),`column "${t}" added to board "${e}"`})}catch(n){console.log($e.red(` ${n.message}`)),process.exit(1)}});gr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{jn(o=>{let s=(Array.isArray(o.boards)?o.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!==t),s.columns.length===i)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});Ft.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{jn(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});function jn(e){let{summary:t,backupPath:o}=Ke(n=>e(n));console.log($e.green(`
414
+ `));return}console.log();for(let t of e.boards){console.log(` ${$e.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log($e.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log($e.dim(` primary label: ${t.primaryToolLabel}`)),console.log($e.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});qt.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,t)=>{try{In(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.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:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});qt.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,t)=>{try{In(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(t.name&&(s.name=t.name,i.push(`name="${t.name}"`)),t.projects){let r=String(t.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(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=t.label,i.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.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(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});var fr=qt.command("column").description("manage a board's columns (add / remove / edit / list)");fr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(Zh("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.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(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});fr.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,t,o)=>{try{In(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===t))throw new Error(`column "${t}" already exists on board "${e}"`);let r={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");r.mapsToLabel=o.label}return o.accent&&(r.accent=o.accent),i.columns.push(r),`column "${t}" added to board "${e}"`})}catch(n){console.log($e.red(` ${n.message}`)),process.exit(1)}});fr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{In(o=>{let s=(Array.isArray(o.boards)?o.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!==t),s.columns.length===i)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});qt.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{In(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});function In(e){let{summary:t,backupPath:o}=Xe(n=>e(n));console.log($e.green(`
415
415
  \u2713 ${t}
416
416
  `)),o&&console.log($e.dim(` Backup: ${o}`)),console.log($e.dim(` Restart the dashboard to pick up the change if not auto-reloading.
417
- `))}import{Command as Xh}from"commander";import m from"chalk";import Se from"chalk";import{resolve as Vh}from"path";var Kh=e=>e||Vh(process.cwd(),".agentx/wiki");async function Uo(e){let{FactLedger:t}=await import("./ledger-CH7R756S.js");return new t(Kh(e))}function qo(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(Se.red(` ${o?.message??o}`)),process.exitCode=1}}}function ug(e){let t=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");t.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(qo(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await Uo(n.dir)).list().filter(r=>!n.stale||s(r));if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Se.dim(" no facts recorded"));return}for(let r of i){let a=r.undated?Se.yellow(" UNCHECKED"):s(r)?Se.yellow(" STALE"):"";console.log(` ${Se.cyan(r.id)} ${Se.bold(r.subject)} \xB7 ${r.attribute}: ${r.value}${a}`),console.log(Se.dim(` ${r.volatility} \xB7 ${r.source} \xB7 checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy}`))}})),t.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(qo(async(n,s)=>{let i=(await Uo(s.dir)).get(n);if(!i){console.error(Se.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(i,null,2))})),t.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${ni.join(" | ")}`).option("--ttl-days <n>","days it stays trusted, overriding the class").option("--confirm","a person confirms this value: replace a newer-dated one").option("--dir <path>","wiki directory").action(qo(async n=>{if(n.class&&!ra(n.class)){console.error(Se.red(` --class must be one of ${ni.join(", ")}`)),process.exitCode=1;return}let i=(await Uo(n.dir)).write({subject:n.subject,attribute:n.attribute,value:n.value,source:n.source,verifiedBy:n.by,verifiedAt:n.checkedAt,volatility:n.class,ttlDays:n.ttlDays!==void 0?Number(n.ttlDays):void 0},n.confirm?{confirmedBy:n.by}:{});if(i.status==="contradiction"){let r=i.fact.confirmedBy?`${i.fact.confirmedBy} confirmed it, so only a person can change it`:n.checkedAt?"and this check is not newer":"and this value has no --checked-at";console.log(Se.yellow(` not replaced: the wiki says "${i.fact.value}" (checked ${i.fact.verifiedAt.slice(0,10)}), ${r}.`)),console.log(i.questionId?Se.dim(` Queued question ${i.questionId}: agentx wiki questions \xB7 agentx wiki answer ${i.questionId} "<true value>"`):i.questionClosed?Se.dim(` A person already ${i.questionClosed} this same claim, so it is not asked again.`):Se.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Se.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))}));let o=t.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");o.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(qo(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await Uo(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Se.dim(" no fact proposals waiting"));return}for(let r of i)console.log(` ${Se.cyan(r.id)} ${r.status==="pending"?"":Se.dim(`[${r.status}] `)}${r.claim}`),console.log(Se.dim(` ${r.agentId} \xB7 ${r.origin} \xB7 ${r.source} \xB7 ${r.verifiedAt.slice(0,10)}`));console.log(Se.dim(`
418
- Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(qo(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await Uo(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Se.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))})),o.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(qo(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await Uo(s.dir),n,s.by,s.reason);console.log(Se.dim(` rejected: ${r.claim}`))}))}import{resolve as F,relative as fg,dirname as hg}from"path";import{execSync as io}from"child_process";import{writeFileSync as ro,mkdirSync as $t,readFileSync as On,readdirSync as Qh,renameSync as _s,rmSync as Zh,existsSync as Ve}from"fs";function Te(e,t){return new oi(ao(e),void 0,t||"graph")}function ao(e){return e||F(process.cwd(),".agentx/wiki")}function pr(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new Xh().name("wiki").description("wiki knowledge base management");ug(ee);ee.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 t=e.mode,o=Te(e.dir,t),n=o.summary(),i=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${pr(t)}]`)),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())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let t=Te(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let r of o){let c=t.getAgentWiki(r).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(r)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(r)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-CH7R756S.js"),i=s(ao(e.dir));if(n+=i.length,i.length>0){console.log(` ${m.cyan("facts")}: ${m.yellow(`${i.length} contradiction(s)`)}`);for(let r of i)console.log(` [!] ${m.dim(r.type)} ${r.articles[0]}: ${r.message}`)}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});ee.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 t=e.mode,o=Te(e.dir,t),n=e.agent?[e.agent]:o.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=F(process.cwd(),".agentx/graph");return Ve(u)?new xt({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[f,p]of Object.entries(u.entries))r.set(f,p.path)}catch{}let a,c=u=>{let f=u.meta?.intentPath;if(Array.isArray(f)&&f.every(w=>typeof w=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),h=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(h)},l=(u,f)=>{let p=new Map;for(let w of u){let k=f.find(S=>S.id===w);if(!k)continue;let $=c(k);if(!$?.length)continue;let b=$.join("/"),E=p.get(b);E?E.n++:p.set(b,{path:$,n:1})}if(p.size===0)return;let h;for(let w of p.values())(!h||w.n>h.n)&&(h=w);return h?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=o.getUnabsorbedEntries(u).filter(v=>!f||(v.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let v of p.slice(0,3))console.log(m.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let h=o.getAgentWiki(u),w=h.rebuildIndex(),k=h.getWorldview()||o.getSharedStore().getWorldview()||"",$=p.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
417
+ `))}import{Command as sy}from"commander";import m from"chalk";import Se from"chalk";import{resolve as oy}from"path";var ny=e=>e||oy(process.cwd(),".agentx/wiki");async function Wo(e){let{FactLedger:t}=await import("./ledger-CH7R756S.js");return new t(ny(e))}function Bo(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(Se.red(` ${o?.message??o}`)),process.exitCode=1}}}function bg(e){let t=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");t.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(Bo(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await Wo(n.dir)).list().filter(r=>!n.stale||s(r));if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Se.dim(" no facts recorded"));return}for(let r of i){let a=r.undated?Se.yellow(" UNCHECKED"):s(r)?Se.yellow(" STALE"):"";console.log(` ${Se.cyan(r.id)} ${Se.bold(r.subject)} \xB7 ${r.attribute}: ${r.value}${a}`),console.log(Se.dim(` ${r.volatility} \xB7 ${r.source} \xB7 checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy}`))}})),t.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(Bo(async(n,s)=>{let i=(await Wo(s.dir)).get(n);if(!i){console.error(Se.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(i,null,2))})),t.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${ai.join(" | ")}`).option("--ttl-days <n>","days it stays trusted, overriding the class").option("--confirm","a person confirms this value: replace a newer-dated one").option("--dir <path>","wiki directory").action(Bo(async n=>{if(n.class&&!da(n.class)){console.error(Se.red(` --class must be one of ${ai.join(", ")}`)),process.exitCode=1;return}let i=(await Wo(n.dir)).write({subject:n.subject,attribute:n.attribute,value:n.value,source:n.source,verifiedBy:n.by,verifiedAt:n.checkedAt,volatility:n.class,ttlDays:n.ttlDays!==void 0?Number(n.ttlDays):void 0},n.confirm?{confirmedBy:n.by}:{});if(i.status==="contradiction"){let r=i.fact.confirmedBy?`${i.fact.confirmedBy} confirmed it, so only a person can change it`:n.checkedAt?"and this check is not newer":"and this value has no --checked-at";console.log(Se.yellow(` not replaced: the wiki says "${i.fact.value}" (checked ${i.fact.verifiedAt.slice(0,10)}), ${r}.`)),console.log(i.questionId?Se.dim(` Queued question ${i.questionId}: agentx wiki questions \xB7 agentx wiki answer ${i.questionId} "<true value>"`):i.questionClosed?Se.dim(` A person already ${i.questionClosed} this same claim, so it is not asked again.`):Se.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Se.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))}));let o=t.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");o.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(Bo(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await Wo(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Se.dim(" no fact proposals waiting"));return}for(let r of i)console.log(` ${Se.cyan(r.id)} ${r.status==="pending"?"":Se.dim(`[${r.status}] `)}${r.claim}`),console.log(Se.dim(` ${r.agentId} \xB7 ${r.origin} \xB7 ${r.source} \xB7 ${r.verifiedAt.slice(0,10)}`));console.log(Se.dim(`
418
+ Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(Bo(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await Wo(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Se.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))})),o.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(Bo(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await Wo(s.dir),n,s.by,s.reason);console.log(Se.dim(` rejected: ${r.claim}`))}))}import{resolve as F,relative as $g,dirname as kg}from"path";import{execSync as ro}from"child_process";import{writeFileSync as ao,mkdirSync as kt,readFileSync as Cn,readdirSync as iy,renameSync as Ls,rmSync as ry,existsSync as Ke}from"fs";function Te(e,t){return new ri(co(e),void 0,t||"graph")}function co(e){return e||F(process.cwd(),".agentx/wiki")}function yr(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new sy().name("wiki").description("wiki knowledge base management");bg(ee);ee.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 t=e.mode,o=Te(e.dir,t),n=o.summary(),i=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${yr(t)}]`)),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())});ee.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let t=Te(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let r of o){let c=t.getAgentWiki(r).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(r)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(r)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-CH7R756S.js"),i=s(co(e.dir));if(n+=i.length,i.length>0){console.log(` ${m.cyan("facts")}: ${m.yellow(`${i.length} contradiction(s)`)}`);for(let r of i)console.log(` [!] ${m.dim(r.type)} ${r.articles[0]}: ${r.message}`)}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});ee.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 t=e.mode,o=Te(e.dir,t),n=e.agent?[e.agent]:o.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=F(process.cwd(),".agentx/graph");return Ke(u)?new Et({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[f,p]of Object.entries(u.entries))r.set(f,p.path)}catch{}let a,c=u=>{let f=u.meta?.intentPath;if(Array.isArray(f)&&f.every(w=>typeof w=="string")&&f.length>0)return f;if(!i||r.size===0)return;let p=String(u.meta?.sender??""),h=i.fingerprint({text:u.content,channel:u.source,sender:p});return r.get(h)},l=(u,f)=>{let p=new Map;for(let w of u){let k=f.find(S=>S.id===w);if(!k)continue;let $=c(k);if(!$?.length)continue;let b=$.join("/"),E=p.get(b);E?E.n++:p.set(b,{path:$,n:1})}if(p.size===0)return;let h;for(let w of p.values())(!h||w.n>h.n)&&(h=w);return h?.path},g=0,d=0;for(let u of n){let f=typeof e.since=="string"?e.since.trim():"",p=o.getUnabsorbedEntries(u).filter(v=>!f||(v.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let v of p.slice(0,3))console.log(m.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let h=o.getAgentWiki(u),w=h.rebuildIndex(),k=h.getWorldview()||o.getSharedStore().getWorldview()||"",$=p.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
419
419
  ${v.content}
420
420
  --- END ENTRY ---`).join(`
421
421
 
422
- `),b="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:C,renderFactsBlock:O,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-X44PF73W.js");if(!a){let J=new Set;for(let je of o.listAgents())for(let ke of o.getAgentWiki(je).listArticles(je))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=v(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:je,results:ke}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...me,...je]);b=O(M);let Ye=[...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${Ye.length?` (${Ye.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 E=La(t,u,k,w.articles,$,p.length,b);console.log(m.dim(` Mode: ${pr(t)}`));let S=F(h.baseDir,"_tmp");$t(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");ro(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=io(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:mo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,O=[],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,je=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){je=M+1;break}if(je===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=R.slice(L,je);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],O=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 Ye=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);h.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ye,lastUpdated:Ye,sources:M.sources||[],graphPath:ve},M.content,u);let Ht=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("+")} ${Ht}${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(O.length>0){console.log(),console.log(m.yellow(` Gaps detected (${O.length} missing pieces):`));for(let M of O)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ye=new M(ao(e.dir)).add(O.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ye.added>0&&console.log(m.dim(` queued ${Ye.added} for follow-up (agentx wiki questions)`))}catch{}}h.rebuildIndex()}catch(v){console.log(m.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(m.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(m.dim("stdout: "+String(v.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=ey(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.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-5XZWP2BN.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ve(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()-(t??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(!Ve(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(t??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let h=p[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Fa({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,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 Ds=ee.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Ps(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Ds.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:t}=await import("./proposals-O4B5LD5T.js"),o=t(Ps(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){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}`))}});Ds.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,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Ps(t.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(`
422
+ `),b="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:C,renderFactsBlock:O,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-2K6UX5GD.js");if(!a){let J=new Set;for(let je of o.listAgents())for(let ke of o.getAgentWiki(je).listArticles(je))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=v(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:je,results:ke}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...me,...je]);b=O(M);let Ve=[...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${Ve.length?` (${Ve.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 E=Wa(t,u,k,w.articles,$,p.length,b);console.log(m.dim(` Mode: ${yr(t)}`));let S=F(h.baseDir,"_tmp");kt(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");ao(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=ro(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:uo({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,O=[],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,je=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){je=M+1;break}if(je===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=R.slice(L,je);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],O=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 Ve=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);h.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ve,lastUpdated:Ve,sources:M.sources||[],graphPath:ve},M.content,u);let Gt=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("+")} ${Gt}${M.path}: ${M.title}${m.dim(_)}`);let ye=(M.tags||[]).slice(0,4).join(", ");ye&&console.log(m.dim(` tags: ${ye}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(O.length>0){console.log(),console.log(m.yellow(` Gaps detected (${O.length} missing pieces):`));for(let M of O)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ve=new M(co(e.dir)).add(O.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ve.added>0&&console.log(m.dim(` queued ${Ve.added} for follow-up (agentx wiki questions)`))}catch{}}h.rebuildIndex()}catch(v){console.log(m.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(m.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(m.dim("stdout: "+String(v.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=ay(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.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-UQJ3IA2Z.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ke(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()-(t??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(!Ke(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(t??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let h=p[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Ba({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,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 Fs=ee.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Us(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Fs.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:t}=await import("./proposals-O4B5LD5T.js"),o=t(Us(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){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}`))}});Fs.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,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Us(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
423
423
  `).map(s=>` ${s}`).join(`
424
- `)),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>)`))}});Ds.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,t)=>{let{approveProposal:o}=await import("./promote-36XF4LH7.js"),n=o(Ps(t.dir),e,{force:t.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`))});Ds.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,t)=>{let{rejectProposal:o}=await import("./promote-36XF4LH7.js"),n=o(Ps(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function ey(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",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:t}=await import("./query-YFZ6GWHU.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Te(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=o(d).sort().reverse();for(let w of f){let k=r(d,w),$=[];try{$=o(k).filter(b=>b.endsWith(".json")).sort().reverse()}catch{continue}for(let b of $){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,b),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||b.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let b=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
424
+ `)),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>)`))}});Fs.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,t)=>{let{approveProposal:o}=await import("./promote-I5QCWYXG.js"),n=o(Us(t.dir),e,{force:t.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`))});Fs.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,t)=>{let{rejectProposal:o}=await import("./promote-I5QCWYXG.js"),n=o(Us(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function ay(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",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:t}=await import("./query-WNOCMO46.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Te(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=o(d).sort().reverse();for(let w of f){let k=r(d,w),$=[];try{$=o(k).filter(b=>b.endsWith(".json")).sort().reverse()}catch{continue}for(let b of $){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,b),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||b.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let b=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
425
425
  `)||"_(none returned)_",E;try{let S=await t(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")E=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map(v=>`\`${v.title}\` [${v.type||"?"}]`).join(", ");E=`**Answer:**
426
426
 
427
427
  ${S.answer}
428
428
 
429
429
  **Citations:** ${x}`}}catch(S){E=`_(error: ${S.message})_`}console.log(m.dim("done")),p.push(`## ${w+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",b,"","### NEW \u2014 agentic query","",E,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let h=p.join(`
430
- `);e.out?((await import("fs")).writeFileSync(e.out,h),console.log(),console.log(m.green(` Wrote ${h.length} bytes to ${e.out}`))):(console.log(),console.log(h))});ee.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 t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-NZOBHQGS.js"),s=e.answers?On(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=Te(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:t.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":""}`)+`
431
- `),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 h=[],w=!1;for(let _=0;_<p.length;_++){let he=p[_],Xe=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${he}
432
- ${m.green(">")} `);if(Xe==="/abort"){w=!0;break}if(Xe==="/done")break;Xe!=="/skip"&&Xe&&h.push({q:he,a:Xe})}if(!w){let _=await l(`
430
+ `);e.out?((await import("fs")).writeFileSync(e.out,h),console.log(),console.log(m.green(` Wrote ${h.length} bytes to ${e.out}`))):(console.log(),console.log(h))});ee.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 t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-NZOBHQGS.js"),s=e.answers?Cn(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=Te(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:t.createInterface({input:process.stdin,output:process.stdout}),l=async _=>{if(s){let ye=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${ye.slice(0,80)}${ye.length>80?"\u2026":""}`)+`
431
+ `),ye.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 h=[],w=!1;for(let _=0;_<p.length;_++){let ye=p[_],Qe=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${ye}
432
+ ${m.green(">")} `);if(Qe==="/abort"){w=!0;break}if(Qe==="/done")break;Qe!=="/skip"&&Qe&&h.push({q:ye,a:Qe})}if(!w){let _=await l(`
433
433
  ${m.dim("Anything else worth capturing?")}
434
434
  ${m.green(">")} `);_&&_!=="/abort"&&_!=="/done"&&h.push({q:"Anything else worth capturing?",a:_})}if(w||h.length===0){console.log(m.yellow(`
435
435
  Nothing captured. Exiting.`)),c?.close();return}let $=a.listArticles(e.agent).slice(0,40).map(_=>`- ${_.meta.title} [${_.meta.type||"?"}]`).join(`
436
436
  `),b=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...h.map(_=>`
437
437
  Q: ${_.q}
438
438
  A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",$||"(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(`
439
- `),E=F(a.baseDir,"_tmp");$t(E,{recursive:!0});let S=F(E,`interview-${o().slice(0,8)}.txt`);ro(S,b),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=io(_,{env:mo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Xe=JSON.parse(he);x=String(Xe.result||Xe.content||"")}catch{x=he}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let v=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(x=v[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let 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 O={};for(let _ of C[1].split(`
440
- `)){let he=_.match(/^(\w+):\s*(.+)$/);he&&(O[he[1]]=he[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=O.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 je=P,ke={title:B,type:O.type||d,related:O.related?O.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:O.tags?O.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:O.access||"public",created:O.created||new Date().toISOString().slice(0,10),lastUpdated:O.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(E,`draft-${o().slice(0,8)}.md`);ro(he,x);try{io(`${_} '${he}'`,{stdio:"inherit"});let Zs=On(he,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Zs){let vt={};for(let tn of Zs[1].split(`
441
- `)){let ei=tn.match(/^(\w+):\s*(.+)$/);ei&&(vt[ei[1]]=ei[2].trim().replace(/^"(.*)"$/,"$1"))}je=Zs[2],ke={...ke,title:vt.title||ke.title,type:vt.type||ke.type,access:vt.access||ke.access,related:vt.related?vt.related.replace(/^\[|\]$/g,"").split(",").map(tn=>tn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:vt.tags?vt.tags.replace(/^\[|\]$/g,"").split(",").map(tn=>tn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Xe){console.log(m.red(` editor failed: ${Xe.message}`));return}}if(!a.writeArticle(me,ke,je,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ye=a.extractWikilinks(je),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Ht=Ye.filter(_=>!ve.has(_.toLowerCase()));if(Ht.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Ht.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-YFZ6GWHU.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Te(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=On(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);r=[];for(let h of p){let w=h.split(/\r?\n/).filter(b=>b.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),$=w.slice(1).join(" ").trim();k&&$&&r.push({q:k,verdict:$})}}let a=r?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,h;if(r){let G=r[f];if(!G)break;p=G.q,h=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let G=w.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
442
- `)),console.log(m.dim(" citations: "+G))}r||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let k={q:p,answer:w.answer,citations:w.citations,verdict:h},$=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let b=$[1].toLowerCase(),E=($[2]||"").trim();if(d.push(k),b==="/ok"||b==="/skip")continue;if(!E){console.log(m.yellow(` ${b} without note \u2014 skipping.`));continue}let S=w.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let v=oy(x.content,b,E,x.meta.title,x.meta.type),R=F(i.baseDir,"_tmp");$t(R,{recursive:!0});let C=F(R,`quiz-patch-${o().slice(0,8)}.txt`);ro(C,v);let O="";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=io(G,{env:mo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let je=JSON.parse(me);O=String(je.result||je.content||"")}catch{O=me}let J=O.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(O=J[1].trim()),O=O.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!O||O.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
439
+ `),E=F(a.baseDir,"_tmp");kt(E,{recursive:!0});let S=F(E,`interview-${o().slice(0,8)}.txt`);ao(S,b),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ye=ro(_,{env:uo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Qe=JSON.parse(ye);x=String(Qe.result||Qe.content||"")}catch{x=ye}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let v=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(x=v[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let 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 O={};for(let _ of C[1].split(`
440
+ `)){let ye=_.match(/^(\w+):\s*(.+)$/);ye&&(O[ye[1]]=ye[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=O.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 je=P,ke={title:B,type:O.type||d,related:O.related?O.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:O.tags?O.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:O.access||"public",created:O.created||new Date().toISOString().slice(0,10),lastUpdated:O.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",ye=F(E,`draft-${o().slice(0,8)}.md`);ao(ye,x);try{ro(`${_} '${ye}'`,{stdio:"inherit"});let ni=Cn(ye,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(ni){let St={};for(let nn of ni[1].split(`
441
+ `)){let si=nn.match(/^(\w+):\s*(.+)$/);si&&(St[si[1]]=si[2].trim().replace(/^"(.*)"$/,"$1"))}je=ni[2],ke={...ke,title:St.title||ke.title,type:St.type||ke.type,access:St.access||ke.access,related:St.related?St.related.replace(/^\[|\]$/g,"").split(",").map(nn=>nn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:St.tags?St.tags.replace(/^\[|\]$/g,"").split(",").map(nn=>nn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Qe){console.log(m.red(` editor failed: ${Qe.message}`));return}}if(!a.writeArticle(me,ke,je,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ve=a.extractWikilinks(je),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Gt=Ve.filter(_=>!ve.has(_.toLowerCase()));if(Gt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Gt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-WNOCMO46.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Te(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=Cn(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);r=[];for(let h of p){let w=h.split(/\r?\n/).filter(b=>b.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),$=w.slice(1).join(" ").trim();k&&$&&r.push({q:k,verdict:$})}}let a=r?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,h;if(r){let G=r[f];if(!G)break;p=G.q,h=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let G=w.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
442
+ `)),console.log(m.dim(" citations: "+G))}r||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let k={q:p,answer:w.answer,citations:w.citations,verdict:h},$=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let b=$[1].toLowerCase(),E=($[2]||"").trim();if(d.push(k),b==="/ok"||b==="/skip")continue;if(!E){console.log(m.yellow(` ${b} without note \u2014 skipping.`));continue}let S=w.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let v=ly(x.content,b,E,x.meta.title,x.meta.type),R=F(i.baseDir,"_tmp");kt(R,{recursive:!0});let C=F(R,`quiz-patch-${o().slice(0,8)}.txt`);ao(C,v);let O="";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=ro(G,{env:uo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let je=JSON.parse(me);O=String(je.result||je.content||"")}catch{O=me}let J=O.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(O=J[1].trim()),O=O.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!O||O.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
443
443
  `).length,B=O.split(`
444
- `).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)},O,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let h=d[p];f.push(`## ${p+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}ro(e.out,f.join(`
445
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ee.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,t,o)=>{let n=Te(o.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=bg(s,t,e);if(!i){console.log(m.yellow(` no article matches "${t}" 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=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{io(`${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)}`))}});ee.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,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=Te(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=bg(a,t,e);if(!c){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=ty(l.content,l.meta.title,l.meta.type,o),d=F(a.baseDir,"_tmp");$t(d,{recursive:!0});let u=F(d,`patch-${i().slice(0,8)}.txt`);ro(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=io(S,{env:mo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(x);f=String(R.result||R.content||"")}catch{f=x}let v=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(f=v[1].trim()),f=f.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let p=l.content.split(`
444
+ `).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)},O,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let h=d[p];f.push(`## ${p+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}ao(e.out,f.join(`
445
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});ee.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,t,o)=>{let n=Te(o.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=Sg(s,t,e);if(!i){console.log(m.yellow(` no article matches "${t}" 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=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{ro(`${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)}`))}});ee.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,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=Te(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=Sg(a,t,e);if(!c){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=cy(l.content,l.meta.title,l.meta.type,o),d=F(a.baseDir,"_tmp");kt(d,{recursive:!0});let u=F(d,`patch-${i().slice(0,8)}.txt`);ao(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=ro(S,{env:uo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let R=JSON.parse(x);f=String(R.result||R.content||"")}catch{f=x}let v=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(f=v[1].trim()),f=f.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let p=l.content.split(`
446
446
  `).length,h=f.split(`
447
- `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${h} lines (${h-p>=0?"+":""}${h-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let w=!!n.yes;if(!w){let S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),w=x==="y"||x==="yes"}if(!w){console.log(m.dim(" aborted."));return}let k=new Set,$=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let E=(l.meta.related||[]).filter(S=>!$.includes(S));E.length&&console.log(m.dim(` (pruned stale related: ${E.slice(0,3).join(", ")}${E.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function bg(e,t,o){let n=t.trim(),s=e.listArticles(o),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 ty(e,t,o,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${o||"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(`
448
- `)}function oy(e,t,o,n,s){let i={"/correct":`The operator says the article contains an error:
447
+ `).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${p} \u2192 ${h} lines (${h-p>=0?"+":""}${h-p})`)),console.log(),console.log(f),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let w=!!n.yes;if(!w){let S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),w=x==="y"||x==="yes"}if(!w){console.log(m.dim(" aborted."));return}let k=new Set,$=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let E=(l.meta.related||[]).filter(S=>!$.includes(S));E.length&&console.log(m.dim(` (pruned stale related: ${E.slice(0,3).join(", ")}${E.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Sg(e,t,o){let n=t.trim(),s=e.listArticles(o),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 cy(e,t,o,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${o||"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(`
448
+ `)}function ly(e,t,o,n,s){let i={"/correct":`The operator says the article contains an error:
449
449
 
450
450
  ${o}
451
451
 
@@ -458,8 +458,8 @@ Incorporate it into the most relevant existing section, or create a short new se
458
458
  ${o}
459
459
 
460
460
  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 [[${o}]].`};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[t]||`Make a minimal edit per: ${o}`,"","## 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(`
461
- `)}ee.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 t=Te(e.dir),o=e.agent?[e.agent]:t.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 o){let u=F(s,"agents",d);if(!Ve(u))continue;let f=F(u,i),p=r.map($=>({mode:$,dir:F(u,$)})).filter($=>Ve($.dir));if(p.length===0)continue;let h=new Map;mr(f,$=>{let b=fg(f,$);if(b.startsWith("_")||b.startsWith("raw/")||b.includes("_tmp/"))return;let E=yg(On($,"utf-8"));E?.meta.title&&h.set(E.meta.title.trim().toLowerCase(),{relPath:b,type:E.meta.type,lastUpdated:E.meta.lastUpdated||""})});let w=[];for(let $ of p)mr($.dir,b=>{let E=fg($.dir,b);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=yg(On(b,"utf-8"));S?.meta.title&&w.push({mode:$.mode,relPath:E,absPath:b,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let k=p.map($=>$.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${k}`));for(let $ of w){let b=$.title.toLowerCase(),E=h.get(b),S;E?!E.type&&$.type||!!E.type==!!$.type&&$.lastUpdated&&E.lastUpdated&&$.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let x=$.type?m.magenta(`[${$.type}]`):m.yellow("[untyped]"),v=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=$.relPath.length>46?$.relPath.slice(0,43)+"...":$.relPath.padEnd(46);if(console.log(` ${v} ${x} ${m.dim($.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${E.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let C=F(f,$.relPath);Ve(C)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${$.relPath}`)),wg(u,$),g++):($t(hg(C),{recursive:!0}),_s($.absPath,C),h.set(b,{relPath:$.relPath,type:$.type,lastUpdated:$.lastUpdated}),c++)}else if(S==="upgrade"){let C=F(f,E.relPath);if(Ve(C)){let O=F(u,"_versions",E.relPath.replace(/\.md$/,""));$t(O,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");_s(C,F(O,`${P}.md`))}$t(hg(C),{recursive:!0}),_s($.absPath,C),h.set(b,{relPath:E.relPath,type:$.type,lastUpdated:$.lastUpdated}),l++}else wg(u,$),g++}catch(C){console.log(m.red(` ! ${S} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let $ of p)try{Zh($.dir,{recursive:!0,force:!0})}catch{}try{t.getAgentWiki(d).rebuildIndex()}catch($){console.log(m.dim(` (catalog rebuild skipped: ${$.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 mr(e,t){if(Ve(e))for(let o of Qh(e,{withFileTypes:!0})){let n=F(e,o.name);o.isDirectory()?mr(n,t):o.isFile()&&o.name.endsWith(".md")&&t(n)}}function yg(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let o={};for(let n of t[1].split(`
462
- `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];o[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:o}}function wg(e,t){let o=F(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));$t(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");_s(t.absPath,F(o,`${n}.md`))}ee.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 t=Te(e.dir),o=e.agent?[e.agent]:t.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 o){let g=t.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 h=g.baseDir,w=F(h,"_tmp");$t(w,{recursive:!0});for(let k=0;k<p;k+=n){let $=u.slice(k,Math.min(k+n,p)),b=sy($),E=F(w,"migrate-prompt.txt");ro(E,b);let S;try{let x=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=io(x,{env:mo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(v),O=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!O)throw new Error("no JSON array in classifier response");S=JSON.parse(O[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of $){let v=S.find(L=>L.path===x.path),R=ny(v?.type);if(!v||!R){console.log(m.yellow(` ? ${x.path}: unclassified${v?` (got "${v.type}")`:""}`));continue}let C=g.extractWikilinks(x.content),O={...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,O,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 ny(e){if(!e)return null;let t=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!t)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"}[t];return n?n===t?{type:n}:{type:n,alias:t}:null}function sy(e){let t=e.map((o,n)=>{let s=o.content.replace(/\s+/g," ").slice(0,400),i=(o.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${o.path}"
461
+ `)}ee.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 t=Te(e.dir),o=e.agent?[e.agent]:t.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 o){let u=F(s,"agents",d);if(!Ke(u))continue;let f=F(u,i),p=r.map($=>({mode:$,dir:F(u,$)})).filter($=>Ke($.dir));if(p.length===0)continue;let h=new Map;hr(f,$=>{let b=$g(f,$);if(b.startsWith("_")||b.startsWith("raw/")||b.includes("_tmp/"))return;let E=vg(Cn($,"utf-8"));E?.meta.title&&h.set(E.meta.title.trim().toLowerCase(),{relPath:b,type:E.meta.type,lastUpdated:E.meta.lastUpdated||""})});let w=[];for(let $ of p)hr($.dir,b=>{let E=$g($.dir,b);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=vg(Cn(b,"utf-8"));S?.meta.title&&w.push({mode:$.mode,relPath:E,absPath:b,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let k=p.map($=>$.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${k}`));for(let $ of w){let b=$.title.toLowerCase(),E=h.get(b),S;E?!E.type&&$.type||!!E.type==!!$.type&&$.lastUpdated&&E.lastUpdated&&$.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let x=$.type?m.magenta(`[${$.type}]`):m.yellow("[untyped]"),v=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=$.relPath.length>46?$.relPath.slice(0,43)+"...":$.relPath.padEnd(46);if(console.log(` ${v} ${x} ${m.dim($.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${E.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let C=F(f,$.relPath);Ke(C)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${$.relPath}`)),xg(u,$),g++):(kt(kg(C),{recursive:!0}),Ls($.absPath,C),h.set(b,{relPath:$.relPath,type:$.type,lastUpdated:$.lastUpdated}),c++)}else if(S==="upgrade"){let C=F(f,E.relPath);if(Ke(C)){let O=F(u,"_versions",E.relPath.replace(/\.md$/,""));kt(O,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");Ls(C,F(O,`${P}.md`))}kt(kg(C),{recursive:!0}),Ls($.absPath,C),h.set(b,{relPath:E.relPath,type:$.type,lastUpdated:$.lastUpdated}),l++}else xg(u,$),g++}catch(C){console.log(m.red(` ! ${S} failed: ${C.message?.slice(0,120)}`))}}if(n){for(let $ of p)try{ry($.dir,{recursive:!0,force:!0})}catch{}try{t.getAgentWiki(d).rebuildIndex()}catch($){console.log(m.dim(` (catalog rebuild skipped: ${$.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function hr(e,t){if(Ke(e))for(let o of iy(e,{withFileTypes:!0})){let n=F(e,o.name);o.isDirectory()?hr(n,t):o.isFile()&&o.name.endsWith(".md")&&t(n)}}function vg(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let o={};for(let n of t[1].split(`
462
+ `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];o[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:o}}function xg(e,t){let o=F(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));kt(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Ls(t.absPath,F(o,`${n}.md`))}ee.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 t=Te(e.dir),o=e.agent?[e.agent]:t.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 o){let g=t.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 h=g.baseDir,w=F(h,"_tmp");kt(w,{recursive:!0});for(let k=0;k<p;k+=n){let $=u.slice(k,Math.min(k+n,p)),b=gy($),E=F(w,"migrate-prompt.txt");ao(E,b);let S;try{let x=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=ro(x,{env:uo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(v),O=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!O)throw new Error("no JSON array in classifier response");S=JSON.parse(O[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of $){let v=S.find(L=>L.path===x.path),R=dy(v?.type);if(!v||!R){console.log(m.yellow(` ? ${x.path}: unclassified${v?` (got "${v.type}")`:""}`));continue}let C=g.extractWikilinks(x.content),O={...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,O,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 dy(e){if(!e)return null;let t=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!t)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"}[t];return n?n===t?{type:n}:{type:n,alias:t}:null}function gy(e){let t=e.map((o,n)=>{let s=o.content.replace(/\s+/g," ").slice(0,400),i=(o.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${o.path}"
463
463
  title: "${o.meta.title}"
464
464
  tags: [${i}]
465
465
  body: ${s}${o.content.length>400?"\u2026":""}`}).join(`
@@ -499,51 +499,51 @@ Output (JSON array, one entry per input article, same order):
499
499
  [
500
500
  {"path": "path/to/article.md", "type": "project"},
501
501
  ...
502
- ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Te(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let t=e.dir||F(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-X7BHZ75G.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:${o}`),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: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),nl(t,o,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:t,articleQualityState:o,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-FGFHW363.js"),c=Te(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let $ of k.listArticles(w)){if(u.length>=g)break e;let b=k.readArticle($.path);if(!b||e.type&&b.meta.type!==e.type)continue;let E={...t(b.meta.type),...e.fields?i(b.meta.type):{}},S=await a(s,o({path:$.path,title:b.meta.title,type:b.meta.type,tags:b.meta.tags,body:b.content}),E,{links:[{kind:"article",id:$.path}],features:{agent:w,type:b.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),v=e.fields?r(b.meta.type,S.answers):null;x.completeness>=d&&!(v&&!v.fit)||u.push({agent:w,type:b.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...v?{missing:v.missingCritical.join(",")||"-",cov:`${Math.round(v.coverage*100)}%`}:{},title:b.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),h=w=>w.map((k,$)=>String(k).padEnd(p[$])).join(" ");console.log(),console.log(m.bold(h(f)));for(let w of u)console.log(h(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
502
+ ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Te(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let t=e.dir||F(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-6UXC7MPC.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:${o}`),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: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),cl(t,o,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:t,articleQualityState:o,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-2GOJBTII.js"),c=Te(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let $ of k.listArticles(w)){if(u.length>=g)break e;let b=k.readArticle($.path);if(!b||e.type&&b.meta.type!==e.type)continue;let E={...t(b.meta.type),...e.fields?i(b.meta.type):{}},S=await a(s,o({path:$.path,title:b.meta.title,type:b.meta.type,tags:b.meta.tags,body:b.content}),E,{links:[{kind:"article",id:$.path}],features:{agent:w,type:b.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),v=e.fields?r(b.meta.type,S.answers):null;x.completeness>=d&&!(v&&!v.fit)||u.push({agent:w,type:b.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...v?{missing:v.missingCritical.join(",")||"-",cov:`${Math.round(v.coverage*100)}%`}:{},title:b.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),h=w=>w.map((k,$)=>String(k).padEnd(p[$])).join(" ");console.log(),console.log(m.bold(h(f)));for(let w of u)console.log(h(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
503
503
  ${u.length} article(s) flagged; ${w} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
504
- ${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-YFZ6GWHU.js"),n=Te(t.dir),s=t.agent?[t.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 o(e,r,i,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles)});if(t.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(t.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=Te(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=await o.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=Te(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ve(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new xt({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 o){let u=t.getAgentWiki(d),f=u.listArticles(d),p=t.getSharedStore().listEntries(),h=new Map(p.map(b=>[b.id,b])),w=0,k=0,$=0;for(let b of f){if(a++,b.meta.graphPath?.length||!b.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of b.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),C=s.fingerprint({text:v.content,channel:v.source,sender:R}),O=r.get(C);if(!O?.length)continue;let P=O.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:O,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(b.path,{...b.meta,graphPath:S.path},b.content,d),$++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green($)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let o=Te(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-X7BHZ75G.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(o.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||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new oi(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,h=0,w=new Set;for(let $ of d.articles){for(let b of $.tags||[])p.add(b);h+=$.tags?.length||0;for(let b of $.sources||[])w.add(b)}let k=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:pr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,t)=>{let o=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),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(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.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=Ve(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${iy(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-FGFHW363.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Te(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let C=v.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let O=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),t(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!O){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,O.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 h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(ao(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),$=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),b=(x,v)=>String(x)+" ".repeat(Math.max(0,$[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>b(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>b(x[v],R)).join(" "));let E=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=v);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-X7BHZ75G.js"),O=C(),P=O?.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(`
504
+ ${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-WNOCMO46.js"),n=Te(t.dir),s=t.agent?[t.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 o(e,r,i,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles)});if(t.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(t.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=Te(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=await o.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=Te(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ke(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Et({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 o){let u=t.getAgentWiki(d),f=u.listArticles(d),p=t.getSharedStore().listEntries(),h=new Map(p.map(b=>[b.id,b])),w=0,k=0,$=0;for(let b of f){if(a++,b.meta.graphPath?.length||!b.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of b.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),C=s.fingerprint({text:v.content,channel:v.source,sender:R}),O=r.get(C);if(!O?.length)continue;let P=O.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:O,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(b.path,{...b.meta,graphPath:S.path},b.content,d),$++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green($)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let o=Te(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-6UXC7MPC.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(o.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||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new ri(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,h=0,w=new Set;for(let $ of d.articles){for(let b of $.tags||[])p.add(b);h+=$.tags?.length||0;for(let b of $.sources||[])w.add(b)}let k=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:yr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,t)=>{let o=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ke(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),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(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.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=Ke(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${my(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-2GOJBTII.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Te(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let C=v.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let O=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),t(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!O){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,O.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 h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(co(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),$=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),b=(x,v)=>String(x)+" ".repeat(Math.max(0,$[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>b(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>b(x[v],R)).join(" "));let E=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=v);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-6UXC7MPC.js"),O=C(),P=O?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
505
505
  `),L=R.length>10?`
506
506
  \u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
507
507
  ${B}${L}
508
508
 
509
- agentx wiki questions`,me=O?.daemon?.port??O?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-FGFHW363.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-X44PF73W.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Te(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),$=new Map(k.map(O=>[O.name.toLowerCase().trim(),O])),b=0,E=0,S=[],x=!1;e:for(let O of p){let P=f.getAgentWiki(O);for(let B of P.listArticles(O)){if(b>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;b++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:O,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:je,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=$.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ye=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...je]);if(Ye.length===0)continue;let{content:ve,edits:Ht}=u(L.content,Ye[0],J);if(Ht.length!==0){for(let _ of Ht)S.push({agent:O,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,O)?E++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${b} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(O=>Math.max(O.length,...S.map(P=>String(P[O]).length))),C=O=>O.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(v)));for(let O of S)console.log(C(v.map(P=>O[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${b} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ao(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)=>(o[s.tier??"furniture"]??9)-(o[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ao(o.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(ao(o.dir));try{let k=w.get(c.factId);if(k){let $=w.write({subject:k.subject,attribute:k.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${$.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${$.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",t)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Te(o.dir,o.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-FGFHW363.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Te(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),$=a(w,L=>L.absorbed,parseInt(e.n)),b={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${$.length}`));for(let L of e.load?[]:$){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;E.push({entry:L,verdict:s(G.answers,b),citeWorthy:me.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:b.minTypeConfidence,minWorth:b.minWorth,minDurability:b.minDurability}),R=l(E,"seat","seat"),C=d(R,{minN:50}),O=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:C,failures:S,elapsed:O},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),v.lostPositives>0){let L=v.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=v.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${O}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((je,ke)=>ke.recall-je.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=F(process.cwd(),e);Ve(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(n)&&!t.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",o];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 iy(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"}Sm();import{Command as ry}from"commander";import D from"chalk";import{resolve as Ms}from"path";import{existsSync as ay}from"fs";ie();var Wo=new ry().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Wo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new xt({baseDir:Ms(process.cwd(),t.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: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let h=r[p],w=qn(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(h.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=cy(h,a,c),$=null;try{$=await ly(n,o,k,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!$||!$.decision){u++,console.log(D.red("ERR no decision"));continue}let b=String($.decision).toLowerCase().trim(),E=($.reason||"").toString().slice(0,180);if(b==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{dy(i,h,a,c,o),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else b==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||b)),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()});Wo.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 t=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ms(process.cwd(),t.graph.baseDir);if(!ay(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new xt({baseDir:o,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()});Wo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=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 xt({baseDir:Ms(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let v=await fetch(`${o}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let O=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!O.ok)throw new Error(`classifications HTTP ${O.status}`);d=(await O.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),$=0,b=0,E=0;for(let v of k){if(c.has(v.id)){b++;continue}if(e.dryRun){$++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${o}`}),c.add(v.id),$++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${$} added \xB7 ${b} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function cy(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
509
+ agentx wiki questions`,me=O?.daemon?.port??O?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-2GOJBTII.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-2K6UX5GD.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Te(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),$=new Map(k.map(O=>[O.name.toLowerCase().trim(),O])),b=0,E=0,S=[],x=!1;e:for(let O of p){let P=f.getAgentWiki(O);for(let B of P.listArticles(O)){if(b>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;b++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:O,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:je,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=$.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ve=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,ye])=>[_,ye.value]))}]:[],...je]);if(Ve.length===0)continue;let{content:ve,edits:Gt}=u(L.content,Ve[0],J);if(Gt.length!==0){for(let _ of Gt)S.push({agent:O,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,O)?E++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${b} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(O=>Math.max(O.length,...S.map(P=>String(P[O]).length))),C=O=>O.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(v)));for(let O of S)console.log(C(v.map(P=>O[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${b} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(co(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)=>(o[s.tier??"furniture"]??9)-(o[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(co(o.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(co(o.dir));try{let k=w.get(c.factId);if(k){let $=w.write({subject:k.subject,attribute:k.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${$.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${$.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",t)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Te(o.dir,o.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-2GOJBTII.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Te(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),$=a(w,L=>L.absorbed,parseInt(e.n)),b={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${$.length}`));for(let L of e.load?[]:$){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;E.push({entry:L,verdict:s(G.answers,b),citeWorthy:me.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:b.minTypeConfidence,minWorth:b.minWorth,minDurability:b.minDurability}),R=l(E,"seat","seat"),C=d(R,{minN:50}),O=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:C,failures:S,elapsed:O},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),v.lostPositives>0){let L=v.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=v.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${O}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((je,ke)=>ke.recall-je.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=F(process.cwd(),e);Ke(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ke(n)&&!t.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",o];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 my(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"}Cm();import{Command as py}from"commander";import D from"chalk";import{resolve as qs}from"path";import{existsSync as uy}from"fs";ne();var Jo=new py().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Jo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new Et({baseDir:qs(process.cwd(),t.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: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let h=r[p],w=Hn(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(h.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=fy(h,a,c),$=null;try{$=await hy(n,o,k,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!$||!$.decision){u++,console.log(D.red("ERR no decision"));continue}let b=String($.decision).toLowerCase().trim(),E=($.reason||"").toString().slice(0,180);if(b==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{yy(i,h,a,c,o),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else b==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||b)),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()});Jo.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 t=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=qs(process.cwd(),t.graph.baseDir);if(!uy(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Et({baseDir:o,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()});Jo.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 t=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=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 Et({baseDir:qs(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let v=await fetch(`${o}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let O=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!O.ok)throw new Error(`classifications HTTP ${O.status}`);d=(await O.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),$=0,b=0,E=0;for(let v of k){if(c.has(v.id)){b++;continue}if(e.dryRun){$++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${o}`}),c.add(v.id),$++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${$} added \xB7 ${b} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function fy(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
510
510
  `),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(`
511
- `)}async function ly(e,t,o,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:t,message:o,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 Xr((c?.content||"").toString())}finally{clearTimeout(r)}}function dy(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function ur(){let e=I();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let t=Ms(process.cwd(),e.graph.baseDir);return{store:new xt({baseDir:t}),baseDir:t}}var fr=Wo.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");fr.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 t=ur();if(!t)return;let{ReviewStore:o,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.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=t.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(qn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});fr.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,t,o)=>{if(!["correct","wrong","unsure"].includes(t)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=ur();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:t,correctPath:o.path?String(o.path).split("/").filter(Boolean):void 0,note:o.note,reviewer:o.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${t}: ${qn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),o.path&&console.log(D.dim(` should have been: ${o.path}`))});fr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=ur();if(!t)return;let{ReviewStore:o,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.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 hy}from"commander";import V from"chalk";import{Command as kg}from"commander";import de from"chalk";import{existsSync as gy}from"fs";import{resolve as my}from"path";import py from"better-sqlite3";function uy(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(t){let n=Number(t[1]),s=t[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(de.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function fy(e){let t=my(process.cwd(),e);return gy(t)||(console.log(de.red(` No db at ${t}`)),process.exit(1)),new py(t,{readonly:!0})}var vg=new kg().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(rn)).option("--max <n>","max clusters distilled per run",String(Hn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(de.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=fy(e.path),o=await Ua(t,{since:uy(e.since),agentId:e.agent,sessions:new ia(process.cwd()),minOccurrences:Number(e.minOccurrences)||rn,max:Number(e.max)||Hn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(de.dim(` ${n}`))});console.log(),console.log(` ${o.episodes} episode(s) \u2192 ${o.clusters} cluster(s), ${o.ready.length} at threshold`);for(let n of o.ready)console.log(` ${de.cyan(n.key)} ${de.bold(`\xD7${n.count}`)} ${de.dim(n.status)}`),n.sampleMessage&&console.log(de.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(de.dim(`
511
+ `)}async function hy(e,t,o,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:t,message:o,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 oa((c?.content||"").toString())}finally{clearTimeout(r)}}function yy(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function wr(){let e=I();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let t=qs(process.cwd(),e.graph.baseDir);return{store:new Et({baseDir:t}),baseDir:t}}var br=Jo.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");br.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 t=wr();if(!t)return;let{ReviewStore:o,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.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=t.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(Hn(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]"))});br.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,t,o)=>{if(!["correct","wrong","unsure"].includes(t)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=wr();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:t,correctPath:o.path?String(o.path).split("/").filter(Boolean):void 0,note:o.note,reviewer:o.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${t}: ${Hn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),o.path&&console.log(D.dim(` should have been: ${o.path}`))});br.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=wr();if(!t)return;let{ReviewStore:o,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.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 xy}from"commander";import V from"chalk";import{Command as Ag}from"commander";import de from"chalk";import{existsSync as wy}from"fs";import{resolve as by}from"path";import $y from"better-sqlite3";function ky(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(t){let n=Number(t[1]),s=t[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(de.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function vy(e){let t=by(process.cwd(),e);return wy(t)||(console.log(de.red(` No db at ${t}`)),process.exit(1)),new $y(t,{readonly:!0})}var Tg=new Ag().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(cn)).option("--max <n>","max clusters distilled per run",String(Vn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(de.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=vy(e.path),o=await Ja(t,{since:ky(e.since),agentId:e.agent,sessions:new la(process.cwd()),minOccurrences:Number(e.minOccurrences)||cn,max:Number(e.max)||Vn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(de.dim(` ${n}`))});console.log(),console.log(` ${o.episodes} episode(s) \u2192 ${o.clusters} cluster(s), ${o.ready.length} at threshold`);for(let n of o.ready)console.log(` ${de.cyan(n.key)} ${de.bold(`\xD7${n.count}`)} ${de.dim(n.status)}`),n.sampleMessage&&console.log(de.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(de.dim(`
512
512
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(de.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(de.green(` \u2713 draft written: ${n.id}`)+de.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(de.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(de.yellow(` \u26A0 ${n}`));o.dryRun?console.log(de.dim(`
513
513
  dry run only; pass --commit --via <agentId> to write drafts`)):o.drafted.length&&console.log(de.dim(`
514
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),$g={hourly:"0 * * * *",daily:"0 3 * * *"},xg=new kg().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(rn)).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 t=e.off?void 0:e.cron??(e.hourly?$g.hourly:e.daily?$g.daily:void 0);!e.off&&!t&&!e.onTask&&(console.log(de.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(de.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let o=Number(e.minOccurrences)||rn,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:o,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 ${Hn} --min-occurrences ${o} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
515
- `),i=await ye(a=>{Oe(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Oe(a,"crons.procedure-extract.enabled",!1):t&&Oe(a,"crons.procedure-extract",{enabled:!0,schedule:t,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(de.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(de.green(` \u2713 ${r} procedure extraction: off`)):(console.log(de.green(` \u2713 ${r} procedure extraction cadence`)),t&&console.log(de.dim(` cron: ${t} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(de.dim(" on-task counting: enabled")),console.log(de.dim(` threshold: ${o} occurrences`))),console.log(de.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var at=new hy().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");at.addCommand(vg);at.addCommand(xg);at.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 t=new St,o=[...e.drafts?[]:t.list(),...e.drafts||e.all?t.listDrafts():[]];if(!o.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 o){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(` ${o.length} procedure${o.length===1?"":"s"}.`))});at.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,t=[])=>[...t,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,t=[])=>[...t,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,t=[])=>[...t,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,t=[])=>[...t,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let t=new St,o=e.steps?String(e.steps):`## Steps
514
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Eg={hourly:"0 * * * *",daily:"0 3 * * *"},jg=new Ag().name("watch").description("set the extraction cadence: registers the cron + config the daemon runs on").option("--hourly","extract every hour").option("--daily","extract daily at 03:00").option("--cron <expr>","custom 5-field cron expression").option("--on-task","also count patterns live after each completed task").option("--off","disable scheduled extraction").option("--via <agentId>","agent that runs the extraction (LLM distillation goes through its session)").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(cn)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let t=e.off?void 0:e.cron??(e.hourly?Eg.hourly:e.daily?Eg.daily:void 0);!e.off&&!t&&!e.onTask&&(console.log(de.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(de.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let o=Number(e.minOccurrences)||cn,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:o,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 ${Vn} --min-occurrences ${o} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
515
+ `),i=await pe(a=>{Oe(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&Oe(a,"crons.procedure-extract.enabled",!1):t&&Oe(a,"crons.procedure-extract",{enabled:!0,schedule:t,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(de.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(de.green(` \u2713 ${r} procedure extraction: off`)):(console.log(de.green(` \u2713 ${r} procedure extraction cadence`)),t&&console.log(de.dim(` cron: ${t} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(de.dim(" on-task counting: enabled")),console.log(de.dim(` threshold: ${o} occurrences`))),console.log(de.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var ct=new xy().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");ct.addCommand(Tg);ct.addCommand(jg);ct.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 t=new At,o=[...e.drafts?[]:t.list(),...e.drafts||e.all?t.listDrafts():[]];if(!o.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 o){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(` ${o.length} procedure${o.length===1?"":"s"}.`))});ct.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,t=[])=>[...t,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,t=[])=>[...t,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,t=[])=>[...t,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,t=[])=>[...t,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let t=new At,o=e.steps?String(e.steps):`## Steps
516
516
 
517
517
  1. (fill in)
518
518
 
519
519
  ## Notes
520
520
 
521
- `;try{let n=t.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||[]},o);console.log(V.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(V.dim(` ${t.baseDir}/${n.path}`))}catch(n){console.log(V.red(` add failed: ${n.message}`)),process.exit(1)}});at.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let t=new St,o=t.get(e)??t.getDraft(e);o||(console.log(V.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(V.bold(` ${o.meta.title}`)+V.dim(` (${o.meta.id}, ${o.meta.status})`)),console.log(V.dim(` trigger: ${o.meta.trigger}`)),o.meta.inputs?.length&&console.log(V.dim(` inputs: ${o.meta.inputs.join(", ")}`)),o.meta.expected&&console.log(V.dim(` expected: ${o.meta.expected}`)),o.meta.kpis?.length&&console.log(V.dim(` kpis: ${o.meta.kpis.join(", ")}`)),o.meta.owner&&console.log(V.dim(` owner: ${o.meta.owner}`)),o.meta.source&&console.log(V.dim(` source: ${o.meta.source}`)),o.meta.related?.length&&console.log(V.dim(` related: ${o.meta.related.join(", ")}`)),console.log(),console.log(o.body),console.log()});at.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let t=new St;try{let o=t.promoteDraft(e);console.log(V.green(` \u2713 promoted: ${o.meta.id}`)),console.log(V.dim(` agents will now follow it when a task matches: "${o.meta.trigger}"`))}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});at.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let t=new St;try{t.rejectDraft(e),console.log(V.green(` \u2713 rejected: ${e}`))}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});at.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let t=new St;try{t.deprecate(e),console.log(V.green(` \u2713 deprecated: ${e}`))}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});at.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,t)=>{let o=new St,n=ba(e,o.list(),{limit:Number(t.limit)||3,minScore:Number(t.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 by}from"commander";import A from"chalk";import{resolve as Jo,basename as $y}from"path";import{existsSync as hr,readFileSync as yr,writeFileSync as Ls}from"fs";import qE from"better-sqlite3";import{readFileSync as yy}from"fs";import{resolve as Bo,dirname as Sg}from"path";import{fileURLToPath as wy}from"url";var In=[{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 Eg(e){let t=Sg(wy(import.meta.url)),o=process.argv[1]?Sg(process.argv[1]):"",n=[Bo(t,`${e}.yaml`),Bo(t,"workflows/templates",`${e}.yaml`),Bo(t,"..","workflows/templates",`${e}.yaml`),Bo(t,"../..","workflows/templates",`${e}.yaml`),o?Bo(o,"workflows/templates",`${e}.yaml`):"",o?Bo(o,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return yy(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
521
+ `;try{let n=t.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||[]},o);console.log(V.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(V.dim(` ${t.baseDir}/${n.path}`))}catch(n){console.log(V.red(` add failed: ${n.message}`)),process.exit(1)}});ct.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let t=new At,o=t.get(e)??t.getDraft(e);o||(console.log(V.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(V.bold(` ${o.meta.title}`)+V.dim(` (${o.meta.id}, ${o.meta.status})`)),console.log(V.dim(` trigger: ${o.meta.trigger}`)),o.meta.inputs?.length&&console.log(V.dim(` inputs: ${o.meta.inputs.join(", ")}`)),o.meta.expected&&console.log(V.dim(` expected: ${o.meta.expected}`)),o.meta.kpis?.length&&console.log(V.dim(` kpis: ${o.meta.kpis.join(", ")}`)),o.meta.owner&&console.log(V.dim(` owner: ${o.meta.owner}`)),o.meta.source&&console.log(V.dim(` source: ${o.meta.source}`)),o.meta.related?.length&&console.log(V.dim(` related: ${o.meta.related.join(", ")}`)),console.log(),console.log(o.body),console.log()});ct.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let t=new At;try{let o=t.promoteDraft(e);console.log(V.green(` \u2713 promoted: ${o.meta.id}`)),console.log(V.dim(` agents will now follow it when a task matches: "${o.meta.trigger}"`))}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});ct.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let t=new At;try{t.rejectDraft(e),console.log(V.green(` \u2713 rejected: ${e}`))}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});ct.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let t=new At;try{t.deprecate(e),console.log(V.green(` \u2713 deprecated: ${e}`))}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});ct.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,t)=>{let o=new At,n=xa(e,o.list(),{limit:Number(t.limit)||3,minScore:Number(t.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 Ay}from"commander";import A from"chalk";import{resolve as Go,basename as Ty}from"path";import{existsSync as $r,readFileSync as kr,writeFileSync as Ws}from"fs";import VE from"better-sqlite3";import{readFileSync as Sy}from"fs";import{resolve as Ho,dirname as Og}from"path";import{fileURLToPath as Ey}from"url";var Nn=[{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 Ig(e){let t=Og(Ey(import.meta.url)),o=process.argv[1]?Og(process.argv[1]):"",n=[Ho(t,`${e}.yaml`),Ho(t,"workflows/templates",`${e}.yaml`),Ho(t,"..","workflows/templates",`${e}.yaml`),Ho(t,"../..","workflows/templates",`${e}.yaml`),o?Ho(o,"workflows/templates",`${e}.yaml`):"",o?Ho(o,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Sy(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
522
522
  ${n.join(`
523
- `)}`)}var Ge=new by().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ge.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new Gt().list();if(!t.length){console.log(A.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let o of t){let s=o.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=o.state==="active"?A.green("dispatch: active"):A.yellow(`dispatch: ${o.state}`);console.log(` ${A.cyan(o.id)} ${A.bold(o.title)} ${A.dim(`v${o.version} \xB7`)} ${r} ${A.dim(`\xB7 review: ${o.status}`)}`),console.log(` ${A.dim("trigger:")} ${s.source??"?"}${i?` ${A.dim(i)}`:""}`),console.log(` ${A.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(A.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});Ge.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,t)=>{let n=new Gt().get(e);n||(console.log(A.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(da(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(A.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});Ge.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=Jo(process.cwd(),e);hr(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=yr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?ho(r,{filePath:e}):JSON.parse(r),l=fo.safeParse(c);if(!l.success){console.log(A.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=Wn(l.data);if(g.length){console.log(A.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(A.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof Bn?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let o=new Gt().validateAll(),n=0,s=0;for(let i of o)if(i.isValid)console.log(A.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(A.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(A.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ge.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${In.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,t)=>{let o=String(t.template||"linear");In.some(a=>a.name===o)||(console.log(A.red(` unknown template "${t.template}"`)),console.log(A.dim(` available: ${In.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(A.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Gt;!t.force&&n.get(e)&&(console.log(A.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Eg(o);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,t.title?String(t.title):`${o} workflow ${e}`).replace(/__AGENT__/g,String(t.agent)).replace(/__REVIEWER__/g,String(t.reviewer));try{let a=ho(s,{filePath:`${e}.yaml`}),c=fo.safeParse(a);if(!c.success){console.log(A.red(` template "${o}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(A.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=t.json?"json":"yaml",r=Jo(process.cwd(),".agentx/workflows",`${e}.${i}`);if(t.json){let a=ho(s,{filePath:`${e}.yaml`}),c=fo.parse(a);Ls(r,JSON.stringify(c,null,2)+`
524
- `)}else Ls(r,s);console.log(),console.log(A.green(` \u2713 scaffolded ${r}`)),console.log(A.dim(` template: ${o}`)),console.log(),console.log(A.dim(" Next:")),console.log(A.dim(` 1. edit ${r}`)),console.log(A.dim(` 2. agentx workflow validate ${r}`)),console.log(A.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Ge.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of In)console.log(` ${A.cyan(e.name.padEnd(20))} ${A.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${A.dim(e.description)}`);console.log(),console.log(A.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Ge.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,t)=>{let o=Jo(process.cwd(),e);hr(o)||(console.log(A.red(` file not found: ${o}`)),process.exit(1));let n=yr(o,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?ho(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof Bn?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=fo.safeParse(i);if(!r.success){console.log(A.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=Wn(r.data);if(a.length){console.log(A.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Gt,l=s?$y(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Jo(c.baseDir,`${r.data.id}.${l}`);if(Ls(g,s?n:JSON.stringify(r.data,null,2)+`
525
- `),console.log(A.green(` \u2713 ${r.data.id} \u2192 ${g}`)),t.reload===!1){console.log(A.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(t.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(A.dim(" \u2713 daemon reloaded")):console.log(A.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(A.dim(` daemon not reachable at ${t.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ge.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,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new sn({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(A.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?A.cyan:s.status==="failed"?A.red:A.green;console.log(` ${A.dim(s.id.slice(0,8))} ${A.bold(s.workflowId)} ${a(r)} ${A.dim(s.status)}`),console.log(` ${A.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${A.dim("home: ")} ${s.homeNode}`),console.log(` ${A.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${A.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(A.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ge.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,t)=>{let o={};if(t.input)try{o=JSON.parse(t.input)}catch{console.log(A.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Jo(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&hr(s)){let c=yr(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?ho(c,{filePath:e}):JSON.parse(c)}catch($){let b=$ instanceof Bn?$.message:`parse error: ${$?.message??$}`;console.log(A.red(` ${b}`)),process.exit(1)}let d=fo.safeParse(g);if(!d.success){console.log(A.red(" \u2717 schema:"));for(let $ of d.error.issues)console.log(` ${$.path.join(".")||"<root>"}: ${$.message}`);process.exit(1)}let u=Wn(d.data);if(u.length){console.log(A.red(" \u2717 lint:"));for(let $ of u)console.log(` ${$}`);process.exit(1)}let f=new Gt,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,h=l?"yaml":"json",w=Jo(f.baseDir,`${p}.${h}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
526
- `;Ls(w,k),n=p,console.log(A.dim(` ad-hoc registered as "${p}" \u2192 ${w}`));try{await fetch(`${String(t.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(t.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:o,force:!!t.force})});if(!c.ok){let g=await c.text();console.log(A.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(A.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(A.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?A.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(A.red(` request to daemon failed: ${c.message}`)),process.exit(1)}t.watch&&a&&await ky({daemonUrl:String(t.daemon).replace(/\/$/,""),runId:a})});async function ky(e){let t=new Set,o=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||t.has(r.taskId)||(t.add(r.taskId),o.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?A.green:a==="error"?A.red:A.cyan,l=r.totalTokens!=null?A.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?A.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${A.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${A.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${A.dim("run finished:")} ${c.status}`),console.log(A.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(o.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(A.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(o.values())}Ge.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,t)=>{let o=String(t.daemon).replace(/\/$/,"");try{let i=await fetch(`${o}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(t.json){console.log(JSON.stringify(r,null,2));return}Ag(r);return}}catch{}let n;try{let i=await fetch(`${o}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(A.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(A.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(A.yellow(` no traces for "${e}"`)),console.log(A.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(t.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(A.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Ag(i)});function Ag(e){let t=e.status||"ok",o=t==="ok"?A.green:t==="error"?A.red:A.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${o(t.padEnd(5))} ${A.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${A.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${A.dim("model:")} ${i}`),console.log(` ${A.dim("tokens:")} ${n} ${A.dim("duration:")} ${s}`),e.error&&console.log(` ${A.dim("error:")} ${A.red(String(e.error).slice(0,300))}`),console.log()}Ge.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new sn({nodeId:o}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Ge.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new sn({nodeId:o}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Ge.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new sn({nodeId:o}).setStatus(e,"canceled")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 canceled ${e}`))});import{Command as Tg}from"commander";import re from"chalk";import co from"prompts";import{readFileSync as vy,existsSync as xy}from"fs";import{resolve as Sy}from"path";var Cn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],wr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),jg={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 Og(){let e=Sy(process.cwd(),"agentx.json");if(!xy(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(vy(e,"utf-8"))}function Ey(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?re.yellow("\u26A0 no signing secret"):re.green("\u2713 active"):re.dim("disabled")}function Ay(e,t){let o=t?`${t.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=wr.has(e.source)?re.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${re.cyan(e.id)} ${Ey(e)}`),console.log(` ${re.dim(e.source)} \u2192 ${re.bold(e.agentId)}${n}`),console.log(` POST ${re.dim(o)}`),e.secretEnv&&console.log(` secret: ${re.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${re.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${re.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${re.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var kt=new Tg().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");kt.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let t=Og(),o=Array.isArray(t.webhooks)?t.webhooks:[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(re.dim(`
523
+ `)}`)}var ze=new Ay().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");ze.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new zt().list();if(!t.length){console.log(A.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let o of t){let s=o.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=o.state==="active"?A.green("dispatch: active"):A.yellow(`dispatch: ${o.state}`);console.log(` ${A.cyan(o.id)} ${A.bold(o.title)} ${A.dim(`v${o.version} \xB7`)} ${r} ${A.dim(`\xB7 review: ${o.status}`)}`),console.log(` ${A.dim("trigger:")} ${s.source??"?"}${i?` ${A.dim(i)}`:""}`),console.log(` ${A.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(A.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});ze.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,t)=>{let n=new zt().get(e);n||(console.log(A.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(ua(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(A.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});ze.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=Go(process.cwd(),e);$r(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=kr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?wo(r,{filePath:e}):JSON.parse(r),l=yo.safeParse(c);if(!l.success){console.log(A.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=Gn(l.data);if(g.length){console.log(A.yellow(` ! ${i} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(A.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof zn?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let o=new zt().validateAll(),n=0,s=0;for(let i of o)if(i.isValid)console.log(A.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(A.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(A.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});ze.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Nn.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,t)=>{let o=String(t.template||"linear");Nn.some(a=>a.name===o)||(console.log(A.red(` unknown template "${t.template}"`)),console.log(A.dim(` available: ${Nn.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(A.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new zt;!t.force&&n.get(e)&&(console.log(A.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Ig(o);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,t.title?String(t.title):`${o} workflow ${e}`).replace(/__AGENT__/g,String(t.agent)).replace(/__REVIEWER__/g,String(t.reviewer));try{let a=wo(s,{filePath:`${e}.yaml`}),c=yo.safeParse(a);if(!c.success){console.log(A.red(` template "${o}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(A.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=t.json?"json":"yaml",r=Go(process.cwd(),".agentx/workflows",`${e}.${i}`);if(t.json){let a=wo(s,{filePath:`${e}.yaml`}),c=yo.parse(a);Ws(r,JSON.stringify(c,null,2)+`
524
+ `)}else Ws(r,s);console.log(),console.log(A.green(` \u2713 scaffolded ${r}`)),console.log(A.dim(` template: ${o}`)),console.log(),console.log(A.dim(" Next:")),console.log(A.dim(` 1. edit ${r}`)),console.log(A.dim(` 2. agentx workflow validate ${r}`)),console.log(A.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});ze.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Nn)console.log(` ${A.cyan(e.name.padEnd(20))} ${A.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${A.dim(e.description)}`);console.log(),console.log(A.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});ze.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,t)=>{let o=Go(process.cwd(),e);$r(o)||(console.log(A.red(` file not found: ${o}`)),process.exit(1));let n=kr(o,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?wo(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof zn?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=yo.safeParse(i);if(!r.success){console.log(A.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=Gn(r.data);if(a.length){console.log(A.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new zt,l=s?Ty(e).match(/\.yml$/i)?"yml":"yaml":"json",g=Go(c.baseDir,`${r.data.id}.${l}`);if(Ws(g,s?n:JSON.stringify(r.data,null,2)+`
525
+ `),console.log(A.green(` \u2713 ${r.data.id} \u2192 ${g}`)),t.reload===!1){console.log(A.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(t.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(A.dim(" \u2713 daemon reloaded")):console.log(A.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(A.dim(` daemon not reachable at ${t.daemon} \u2014 start it or restart to pick up the new workflow`))}});ze.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,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new an({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(A.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?A.cyan:s.status==="failed"?A.red:A.green;console.log(` ${A.dim(s.id.slice(0,8))} ${A.bold(s.workflowId)} ${a(r)} ${A.dim(s.status)}`),console.log(` ${A.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${A.dim("home: ")} ${s.homeNode}`),console.log(` ${A.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${A.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(A.dim(` ${n.length} run${n.length===1?"":"s"}.`))});ze.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,t)=>{let o={};if(t.input)try{o=JSON.parse(t.input)}catch{console.log(A.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=Go(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&$r(s)){let c=kr(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?wo(c,{filePath:e}):JSON.parse(c)}catch($){let b=$ instanceof zn?$.message:`parse error: ${$?.message??$}`;console.log(A.red(` ${b}`)),process.exit(1)}let d=yo.safeParse(g);if(!d.success){console.log(A.red(" \u2717 schema:"));for(let $ of d.error.issues)console.log(` ${$.path.join(".")||"<root>"}: ${$.message}`);process.exit(1)}let u=Gn(d.data);if(u.length){console.log(A.red(" \u2717 lint:"));for(let $ of u)console.log(` ${$}`);process.exit(1)}let f=new zt,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,h=l?"yaml":"json",w=Go(f.baseDir,`${p}.${h}`),k=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${p}`):JSON.stringify({...d.data,id:p},null,2)+`
526
+ `;Ws(w,k),n=p,console.log(A.dim(` ad-hoc registered as "${p}" \u2192 ${w}`));try{await fetch(`${String(t.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(t.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:o,force:!!t.force})});if(!c.ok){let g=await c.text();console.log(A.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&console.log(A.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(A.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?A.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(A.red(` request to daemon failed: ${c.message}`)),process.exit(1)}t.watch&&a&&await jy({daemonUrl:String(t.daemon).replace(/\/$/,""),runId:a})});async function jy(e){let t=new Set,o=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||t.has(r.taskId)||(t.add(r.taskId),o.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?A.green:a==="error"?A.red:A.cyan,l=r.totalTokens!=null?A.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?A.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${A.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${A.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${A.dim("run finished:")} ${c.status}`),console.log(A.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(o.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(A.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(o.values())}ze.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,t)=>{let o=String(t.daemon).replace(/\/$/,"");try{let i=await fetch(`${o}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(t.json){console.log(JSON.stringify(r,null,2));return}Cg(r);return}}catch{}let n;try{let i=await fetch(`${o}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(A.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(A.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(A.yellow(` no traces for "${e}"`)),console.log(A.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(t.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(A.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Cg(i)});function Cg(e){let t=e.status||"ok",o=t==="ok"?A.green:t==="error"?A.red:A.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${o(t.padEnd(5))} ${A.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${A.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${A.dim("model:")} ${i}`),console.log(` ${A.dim("tokens:")} ${n} ${A.dim("duration:")} ${s}`),e.error&&console.log(` ${A.dim("error:")} ${A.red(String(e.error).slice(0,300))}`),console.log()}ze.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new an({nodeId:o}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});ze.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new an({nodeId:o}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});ze.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new an({nodeId:o}).setStatus(e,"canceled")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 canceled ${e}`))});import{Command as Ng}from"commander";import re from"chalk";import lo from"prompts";import{readFileSync as Oy,existsSync as Iy}from"fs";import{resolve as Cy}from"path";var Rn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],vr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Rg={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 _g(){let e=Cy(process.cwd(),"agentx.json");if(!Iy(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Oy(e,"utf-8"))}function Ny(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?re.yellow("\u26A0 no signing secret"):re.green("\u2713 active"):re.dim("disabled")}function Ry(e,t){let o=t?`${t.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=vr.has(e.source)?re.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${re.cyan(e.id)} ${Ny(e)}`),console.log(` ${re.dim(e.source)} \u2192 ${re.bold(e.agentId)}${n}`),console.log(` POST ${re.dim(o)}`),e.secretEnv&&console.log(` secret: ${re.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${re.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${re.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${re.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var vt=new Ng().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");vt.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let t=_g(),o=Array.isArray(t.webhooks)?t.webhooks:[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(re.dim(`
527
527
  No webhooks registered. Add one with: agentx webhook add
528
- `));return}console.log();for(let n of o)Ay(n)});kt.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Cn.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,t)=>{let o=Og(),n=Object.keys(o.agents||{}),s=(o.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(t.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(t.source||"").trim(),c=String(t.agent||"").trim(),l=String(t.secretEnv||"").trim(),g=String(t.description||"").trim(),d=t.prompt!==!1;if(!r&&d&&(r=((await co({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 co({type:"select",name:"source",message:"Source",choices:Cn.map(p=>({title:`${p}${wr.has(p)?" \u2713 wired":""}`,value:p,description:jg[p]}))})).source),!Cn.includes(a))throw new Error(`Source must be one of: ${Cn.join(", ")}`);if(!c&&d&&(i?c=((await co({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await co({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(!o.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 co({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await co({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(h=>h.id===r))throw new Error(`Webhook "${r}" already exists.`);let p={id:r,source:a,agentId:c,enabled:!0};l&&(p.secretEnv=l),g&&(p.description=g),i&&(p.node=i),f.webhooks.push(p)});if(!u.success)throw new Error(u.error);console.log(re.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(re.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(re.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});kt.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,t)=>{if(!t.yes&&!(await co({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let o=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(!o.success)throw new Error(o.error);console.log(re.green(`\u2713 removed webhook "${e}"`))});function Ig(e){return async t=>{let o=await ye(n=>{let s=(n.webhooks||[]).find(i=>i.id===t);if(!s)throw new Error(`Webhook "${t}" not found.`);s.enabled=e});if(!o.success)throw new Error(o.error);console.log(re.green(`\u2713 ${e?"enabled":"disabled"} webhook "${t}"`))}}kt.command("enable <id>").description("enable a webhook entry").action(Ig(!0));kt.command("disable <id>").description("disable a webhook entry").action(Ig(!1));var Fs=new Tg().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Fs.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,t,o)=>{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[t]=o});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: ${t} \u2192 ${o}`))});Fs.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,t)=>{let o=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[t]});if(!o.success)throw new Error(o.error);console.log(re.green(`\u2713 removed trigger ${t} from "${e}"`))});Fs.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,t)=>{let o=t==="-"||t==="",n=await ye(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);o?delete i.defaultWorkflow:i.defaultWorkflow=t});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: defaultWorkflow ${o?"cleared":`\u2192 ${t}`}`))});kt.addCommand(Fs);kt.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let t=Cn.map(o=>({source:o,wired:wr.has(o),hint:jg[o]}));if(e.json){console.log(JSON.stringify(t,null,2));return}console.log();for(let o of t){let n=o.wired?re.green("\u2713 wired"):re.dim("inbound-only");console.log(` ${re.cyan(o.source.padEnd(8))} ${n} ${re.dim(o.hint)}`)}console.log(),console.log(re.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(re.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Ty}from"commander";import ae from"chalk";ie();function Ho(e){let{summary:t,backupPath:o}=Ke(n=>e(n));console.log(ae.green(`
528
+ `));return}console.log();for(let n of o)Ry(n)});vt.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Rn.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,t)=>{let o=_g(),n=Object.keys(o.agents||{}),s=(o.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(t.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(t.source||"").trim(),c=String(t.agent||"").trim(),l=String(t.secretEnv||"").trim(),g=String(t.description||"").trim(),d=t.prompt!==!1;if(!r&&d&&(r=((await lo({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 lo({type:"select",name:"source",message:"Source",choices:Rn.map(p=>({title:`${p}${vr.has(p)?" \u2713 wired":""}`,value:p,description:Rg[p]}))})).source),!Rn.includes(a))throw new Error(`Source must be one of: ${Rn.join(", ")}`);if(!c&&d&&(i?c=((await lo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await lo({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(!o.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 lo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await lo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await pe(f=>{if(f.webhooks=Array.isArray(f.webhooks)?f.webhooks:[],f.webhooks.find(h=>h.id===r))throw new Error(`Webhook "${r}" already exists.`);let p={id:r,source:a,agentId:c,enabled:!0};l&&(p.secretEnv=l),g&&(p.description=g),i&&(p.node=i),f.webhooks.push(p)});if(!u.success)throw new Error(u.error);console.log(re.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(re.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(re.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});vt.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,t)=>{if(!t.yes&&!(await lo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let o=await pe(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!o.success)throw new Error(o.error);console.log(re.green(`\u2713 removed webhook "${e}"`))});function Dg(e){return async t=>{let o=await pe(n=>{let s=(n.webhooks||[]).find(i=>i.id===t);if(!s)throw new Error(`Webhook "${t}" not found.`);s.enabled=e});if(!o.success)throw new Error(o.error);console.log(re.green(`\u2713 ${e?"enabled":"disabled"} webhook "${t}"`))}}vt.command("enable <id>").description("enable a webhook entry").action(Dg(!0));vt.command("disable <id>").description("disable a webhook entry").action(Dg(!1));var Bs=new Ng().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Bs.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,t,o)=>{let n=await pe(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[t]=o});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: ${t} \u2192 ${o}`))});Bs.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,t)=>{let o=await pe(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[t]});if(!o.success)throw new Error(o.error);console.log(re.green(`\u2713 removed trigger ${t} from "${e}"`))});Bs.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,t)=>{let o=t==="-"||t==="",n=await pe(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);o?delete i.defaultWorkflow:i.defaultWorkflow=t});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: defaultWorkflow ${o?"cleared":`\u2192 ${t}`}`))});vt.addCommand(Bs);vt.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let t=Rn.map(o=>({source:o,wired:vr.has(o),hint:Rg[o]}));if(e.json){console.log(JSON.stringify(t,null,2));return}console.log();for(let o of t){let n=o.wired?re.green("\u2713 wired"):re.dim("inbound-only");console.log(` ${re.cyan(o.source.padEnd(8))} ${n} ${re.dim(o.hint)}`)}console.log(),console.log(re.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(re.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as _y}from"commander";import ae from"chalk";ne();function zo(e){let{summary:t,backupPath:o}=Xe(n=>e(n));console.log(ae.green(`
529
529
  \u2713 ${t}`)),o&&console.log(ae.dim(` Backup: ${o}`)),console.log(ae.dim(` Restart the daemon (or POST /reload) for the change to take effect.
530
- `))}function Us(){try{return I().business||{}}catch{return{}}}var Go=new Ty().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");Go.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let t=Us();if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t||!t.enabled){console.log(),console.log(ae.yellow(" business block not enabled (or missing).")),console.log(ae.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let o=t.orgChart||{},n=t.projects||[],s=t.contactMap||[];console.log(),console.log(ae.bold(" Org chart"));let i=Object.entries(o);if(i.length===0)console.log(ae.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?ae.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?ae.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${ae.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(ae.bold(` Projects (${n.length})`)),n.length===0)console.log(ae.dim(" (empty)"));else for(let r of n){let a=r.pm?ae.dim(` \xB7 pm=${r.pm}`):"",c=r.client?ae.dim(` \xB7 client=${r.client}`):"";console.log(` ${ae.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(ae.bold(` Contact map (${s.length})`)),s.length===0)console.log(ae.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(` ${ae.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?ae.dim(` (${r.displayName})`):""}`)}console.log()});var br=Go.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");br.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let t=Us(),o=Object.entries(t.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(o),null,2));return}if(o.length===0){console.log(ae.dim(" no entries"));return}for(let[n,s]of o)console.log(` ${ae.cyan(n)} ${s.role}${s.reportsTo?ae.dim(` \u2192 ${s.reportsTo}`):""}`)});br.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,t)=>{let o=String(t.days).split(",").map(n=>n.trim()).filter(Boolean);Ho(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:t.role,...t.reportsTo?{reportsTo:t.reportsTo}:{},schedule:{days:o,start:t.start,end:t.end},utilizationTarget:parseFloat(t.utilization)||.8},`orgChart entry "${e}" upserted (role=${t.role}${t.reportsTo?`, reports to ${t.reportsTo}`:""})`))});br.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{Ho(t=>{if(!t.business?.orgChart||!(e in t.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete t.business.orgChart[e],`orgChart entry "${e}" removed`})});var $r=Go.command("project").description("manage business.projects \u2014 id, pm, client");$r.command("list").description("list projects").option("--json","JSON output").action(e=>{let o=Us().projects||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ae.dim(" no projects"));return}for(let n of o)console.log(` ${ae.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});$r.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,t)=>{Ho(o=>{o.business=o.business||{},o.business.projects=o.business.projects||[];let n=o.business.projects.findIndex(i=>i.id===e),s={id:e,...t.pm?{pm:t.pm}:{},...t.client?{client:t.client}:{}};return n>=0?o.business.projects[n]={...o.business.projects[n],...s}:o.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});$r.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{Ho(t=>{let o=t.business?.projects||[],n=o.length;if(t.business.projects=o.filter(s=>s.id!==e),t.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var kr=Go.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");kr.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let o=Us().contactMap||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ae.dim(" no entries"));return}for(let n of o){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${ae.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});kr.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(ae.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),Ho(t=>{t.business=t.business||{},t.business.contactMap=t.business.contactMap||[];let o={client:e.client};e.channel&&(o.channel=e.channel),e.chatId&&(o.chatId=e.chatId),e.username&&(o.username=e.username),e.senderId&&(o.senderId=e.senderId),e.project&&(o.project=e.project),e.displayName&&(o.displayName=e.displayName),t.business.contactMap.push(o);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});kr.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=>{Ho(t=>{let o=t.business?.contactMap||[],n=o.length;if(t.business.contactMap=o.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)),t.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-t.business.contactMap.length} contact entry/entries removed`})});import{Command as jy}from"commander";import Le from"chalk";ie();var Oy={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function vr(e){let t=Oy[e.toLowerCase()];if(!t)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return t}function qs(){let t=I().business?.standup?.plansDir||".agentx/plans";return new qc(t)}var zo=new jy().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");zo.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,t)=>{let o=vr(e),n=qs(),s;if(t.file){let{readFileSync:a}=await import("fs");s=a(t.file,"utf-8")}else t.markdown?s=t.markdown:t.priority?.length?s=t.priority.map(a=>`- ${a}`).join(`
531
- `):(console.error(Le.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(o,s);console.log(Le.green(` \u2713 ${o} plan saved \u2192 ${i.path}`));let r=bi(s);if(r.length){console.log(Le.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Le.dim(` \u2022 ${a}`))}});zo.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let t=qs();if(e){let n=vr(e),s=t.read(n);if(!s){console.log(Le.dim(` No ${n} plan set.`));return}Cg(s.tier,s.date,s.content);return}let o=t.resolve();if(!o){console.log(Le.yellow(" No plan set at any tier.")),console.log(Le.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Le.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Cg(o.tier,o.date,o.content)});zo.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let o=qs().list(parseInt(e.limit,10)||20);if(!o.length){console.log(Le.dim(" No plans yet."));return}for(let n of o)console.log(` ${Le.cyan(n.tier.padEnd(5))} ${Le.bold(n.date.padEnd(11))} ${Le.dim(n.path)}`)});zo.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let t=vr(e),n=qs().read(t);if(!n){console.log(Le.dim(` No ${t} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Le.green(` \u2713 ${t} plan cleared (${n.path})`))});function Cg(e,t,o){console.log(Le.cyan(` ${e} plan \u2014 ${t}`)),console.log();for(let s of o.split(`
532
- `))console.log(` ${s}`);console.log();let n=bi(o);n.length&&console.log(Le.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Iy}from"commander";import Y from"chalk";ie();function Cy(){try{return I().notifications||{}}catch{return{}}}function Ny(){try{return I().channels?.ntfy}catch{return}}function Ry(){try{return I().channels?.push}catch{return}}function Yo(e){let{summary:t,backupPath:o}=Ke(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Y.green(`
530
+ `))}function Js(){try{return I().business||{}}catch{return{}}}var Yo=new _y().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");Yo.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let t=Js();if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t||!t.enabled){console.log(),console.log(ae.yellow(" business block not enabled (or missing).")),console.log(ae.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let o=t.orgChart||{},n=t.projects||[],s=t.contactMap||[];console.log(),console.log(ae.bold(" Org chart"));let i=Object.entries(o);if(i.length===0)console.log(ae.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?ae.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?ae.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${ae.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(ae.bold(` Projects (${n.length})`)),n.length===0)console.log(ae.dim(" (empty)"));else for(let r of n){let a=r.pm?ae.dim(` \xB7 pm=${r.pm}`):"",c=r.client?ae.dim(` \xB7 client=${r.client}`):"";console.log(` ${ae.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(ae.bold(` Contact map (${s.length})`)),s.length===0)console.log(ae.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(` ${ae.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?ae.dim(` (${r.displayName})`):""}`)}console.log()});var xr=Yo.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");xr.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let t=Js(),o=Object.entries(t.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(o),null,2));return}if(o.length===0){console.log(ae.dim(" no entries"));return}for(let[n,s]of o)console.log(` ${ae.cyan(n)} ${s.role}${s.reportsTo?ae.dim(` \u2192 ${s.reportsTo}`):""}`)});xr.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,t)=>{let o=String(t.days).split(",").map(n=>n.trim()).filter(Boolean);zo(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:t.role,...t.reportsTo?{reportsTo:t.reportsTo}:{},schedule:{days:o,start:t.start,end:t.end},utilizationTarget:parseFloat(t.utilization)||.8},`orgChart entry "${e}" upserted (role=${t.role}${t.reportsTo?`, reports to ${t.reportsTo}`:""})`))});xr.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{zo(t=>{if(!t.business?.orgChart||!(e in t.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete t.business.orgChart[e],`orgChart entry "${e}" removed`})});var Sr=Yo.command("project").description("manage business.projects \u2014 id, pm, client");Sr.command("list").description("list projects").option("--json","JSON output").action(e=>{let o=Js().projects||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ae.dim(" no projects"));return}for(let n of o)console.log(` ${ae.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Sr.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,t)=>{zo(o=>{o.business=o.business||{},o.business.projects=o.business.projects||[];let n=o.business.projects.findIndex(i=>i.id===e),s={id:e,...t.pm?{pm:t.pm}:{},...t.client?{client:t.client}:{}};return n>=0?o.business.projects[n]={...o.business.projects[n],...s}:o.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Sr.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{zo(t=>{let o=t.business?.projects||[],n=o.length;if(t.business.projects=o.filter(s=>s.id!==e),t.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var Er=Yo.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Er.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let o=Js().contactMap||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ae.dim(" no entries"));return}for(let n of o){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${ae.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Er.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(ae.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),zo(t=>{t.business=t.business||{},t.business.contactMap=t.business.contactMap||[];let o={client:e.client};e.channel&&(o.channel=e.channel),e.chatId&&(o.chatId=e.chatId),e.username&&(o.username=e.username),e.senderId&&(o.senderId=e.senderId),e.project&&(o.project=e.project),e.displayName&&(o.displayName=e.displayName),t.business.contactMap.push(o);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});Er.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=>{zo(t=>{let o=t.business?.contactMap||[],n=o.length;if(t.business.contactMap=o.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)),t.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-t.business.contactMap.length} contact entry/entries removed`})});import{Command as Dy}from"commander";import Fe from"chalk";ne();var Py={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Ar(e){let t=Py[e.toLowerCase()];if(!t)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return t}function Hs(){let t=I().business?.standup?.plansDir||".agentx/plans";return new Gc(t)}var Vo=new Dy().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Vo.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,t)=>{let o=Ar(e),n=Hs(),s;if(t.file){let{readFileSync:a}=await import("fs");s=a(t.file,"utf-8")}else t.markdown?s=t.markdown:t.priority?.length?s=t.priority.map(a=>`- ${a}`).join(`
531
+ `):(console.error(Fe.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(o,s);console.log(Fe.green(` \u2713 ${o} plan saved \u2192 ${i.path}`));let r=xi(s);if(r.length){console.log(Fe.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Fe.dim(` \u2022 ${a}`))}});Vo.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let t=Hs();if(e){let n=Ar(e),s=t.read(n);if(!s){console.log(Fe.dim(` No ${n} plan set.`));return}Pg(s.tier,s.date,s.content);return}let o=t.resolve();if(!o){console.log(Fe.yellow(" No plan set at any tier.")),console.log(Fe.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Fe.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}Pg(o.tier,o.date,o.content)});Vo.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let o=Hs().list(parseInt(e.limit,10)||20);if(!o.length){console.log(Fe.dim(" No plans yet."));return}for(let n of o)console.log(` ${Fe.cyan(n.tier.padEnd(5))} ${Fe.bold(n.date.padEnd(11))} ${Fe.dim(n.path)}`)});Vo.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let t=Ar(e),n=Hs().read(t);if(!n){console.log(Fe.dim(` No ${t} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Fe.green(` \u2713 ${t} plan cleared (${n.path})`))});function Pg(e,t,o){console.log(Fe.cyan(` ${e} plan \u2014 ${t}`)),console.log();for(let s of o.split(`
532
+ `))console.log(` ${s}`);console.log();let n=xi(o);n.length&&console.log(Fe.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as My}from"commander";import Y from"chalk";ne();function Ly(){try{return I().notifications||{}}catch{return{}}}function Fy(){try{return I().channels?.ntfy}catch{return}}function Uy(){try{return I().channels?.push}catch{return}}function Ko(e){let{summary:t,backupPath:o}=Xe(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Y.green(`
533
533
  \u2713 ${t}`)),o&&console.log(Y.dim(` Backup: ${o}`)),console.log(Y.dim(` Restart the daemon (or POST /reload) for the change to take effect.
534
- `))}var ut=new Iy().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");ut.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let t=Cy();if(e.json){console.log(JSON.stringify(t,null,2));return}if(console.log(),t.destination){let c=t.destination.accountId?` \xB7 account=${t.destination.accountId}`:"";console.log(` destination ${Y.cyan(t.destination.channel+":"+t.destination.chatId)}${Y.dim(c)}`)}else console.log(` destination ${Y.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${t.longTaskThreshold??30}s ${Y.dim("(0 disables long-task pings)")}`);let o=t.on||{};console.log(` on.taskComplete ${o.taskComplete===!1?Y.dim("off"):"on"}`),console.log(` on.taskError ${o.taskError===!1?Y.dim("off"):"on"}`),console.log(` on.taskQueued ${o.taskQueued?"on":Y.dim("off")}`);let n=Yn(t.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 Vc();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 ${Vn(s)} ${Y.dim(t.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=li(Ry()),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=ki(Ny());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()});ut.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){Yo(t=>(delete t.destination,"notifications destination cleared"));return}Yo(t=>(t.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});ut.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,t)=>{let o=["taskComplete","taskError","taskQueued"];o.includes(e)||(console.log(Y.red(` unknown event "${e}". Pick from: ${o.join(", ")}`)),process.exit(1));let n=t.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";Yo(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});ut.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let t=parseInt(e,10);(!Number.isFinite(t)||t<0)&&(console.log(Y.red(" threshold must be a non-negative integer")),process.exit(1)),Yo(o=>(o.longTaskThreshold=t,`longTaskThreshold = ${t}s`))});ut.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 t=(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)},o={};e.banner!==void 0&&(o.banner=t("--banner",e.banner)),e.sound!==void 0&&(o.sound=t("--sound",e.sound)),e.soundName!==void 0&&(o.soundName=e.soundName),e.volume!==void 0&&(o.volume=e.volume),e.icon!==void 0&&(o.icon=e.icon),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{Yo(n=>(n.local=Qa(n.local,o),`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.
535
- `))}catch(n){console.log(Y.red(` ${n?.message??n}`)),process.exit(1)}});ut.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 t=e.trim();/^[\w-]+$/.test(t)||(console.log(Y.red(` not a channel name: ${e}`)),process.exit(1)),Yo(o=>(o.channel=t,`notifications.channel = ${t}`))});ut.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 t={};e.subject!==void 0&&(t.subject=e.subject),e.relayTo!==void 0&&(t.relayTo=e.relayTo),e.enable&&(t.enabled=!0),e.disable&&(t.enabled=!1),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:o,backupPath:n}=Ke(s=>{s.channels=s.channels||{},s.channels.push=ic(s.channels.push,t);let i=li(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(`
534
+ `))}var ft=new My().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");ft.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let t=Ly();if(e.json){console.log(JSON.stringify(t,null,2));return}if(console.log(),t.destination){let c=t.destination.accountId?` \xB7 account=${t.destination.accountId}`:"";console.log(` destination ${Y.cyan(t.destination.channel+":"+t.destination.chatId)}${Y.dim(c)}`)}else console.log(` destination ${Y.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${t.longTaskThreshold??30}s ${Y.dim("(0 disables long-task pings)")}`);let o=t.on||{};console.log(` on.taskComplete ${o.taskComplete===!1?Y.dim("off"):"on"}`),console.log(` on.taskError ${o.taskError===!1?Y.dim("off"):"on"}`),console.log(` on.taskQueued ${o.taskQueued?"on":Y.dim("off")}`);let n=Qn(t.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 el();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 ${Zn(s)} ${Y.dim(t.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=pi(Uy()),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=Ei(Fy());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()});ft.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){Ko(t=>(delete t.destination,"notifications destination cleared"));return}Ko(t=>(t.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});ft.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,t)=>{let o=["taskComplete","taskError","taskQueued"];o.includes(e)||(console.log(Y.red(` unknown event "${e}". Pick from: ${o.join(", ")}`)),process.exit(1));let n=t.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";Ko(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});ft.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let t=parseInt(e,10);(!Number.isFinite(t)||t<0)&&(console.log(Y.red(" threshold must be a non-negative integer")),process.exit(1)),Ko(o=>(o.longTaskThreshold=t,`longTaskThreshold = ${t}s`))});ft.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 t=(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)},o={};e.banner!==void 0&&(o.banner=t("--banner",e.banner)),e.sound!==void 0&&(o.sound=t("--sound",e.sound)),e.soundName!==void 0&&(o.soundName=e.soundName),e.volume!==void 0&&(o.volume=e.volume),e.icon!==void 0&&(o.icon=e.icon),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{Ko(n=>(n.local=oc(n.local,o),`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.
535
+ `))}catch(n){console.log(Y.red(` ${n?.message??n}`)),process.exit(1)}});ft.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 t=e.trim();/^[\w-]+$/.test(t)||(console.log(Y.red(` not a channel name: ${e}`)),process.exit(1)),Ko(o=>(o.channel=t,`notifications.channel = ${t}`))});ft.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 t={};e.subject!==void 0&&(t.subject=e.subject),e.relayTo!==void 0&&(t.relayTo=e.relayTo),e.enable&&(t.enabled=!0),e.disable&&(t.enabled=!1),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:o,backupPath:n}=Xe(s=>{s.channels=s.channels||{},s.channels.push=lc(s.channels.push,t);let i=pi(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(`
536
536
  \u2713 ${o}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
537
- `))}catch(o){console.log(Y.red(` ${o?.message??o}`)),process.exit(1)}});ut.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 t={};e.server!==void 0&&(t.server=e.server),e.topic!==void 0&&(t.topic=e.topic),e.token!==void 0&&(t.token=e.token),e.enable&&(t.enabled=!0),e.disable&&(t.enabled=!1),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:o,backupPath:n}=Ke(s=>{s.channels=s.channels||{},s.channels.ntfy=ol(s.channels.ntfy,t);let i=ki(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(`
537
+ `))}catch(o){console.log(Y.red(` ${o?.message??o}`)),process.exit(1)}});ft.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 t={};e.server!==void 0&&(t.server=e.server),e.topic!==void 0&&(t.topic=e.topic),e.token!==void 0&&(t.token=e.token),e.enable&&(t.enabled=!0),e.disable&&(t.enabled=!1),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:o,backupPath:n}=Xe(s=>{s.channels=s.channels||{},s.channels.ntfy=al(s.channels.ntfy,t);let i=Ei(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(`
538
538
  \u2713 ${o}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
539
- `))}catch(o){console.log(Y.red(` ${o?.message??o}`)),process.exit(1)}});import{Command as _y}from"commander";import Ut from"chalk";import{readdirSync as xr,statSync as Ng,unlinkSync as Dy,rmSync as Py,existsSync as Rg}from"fs";import{resolve as _g,join as Dg}from"path";var Pg=[{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 Sr(e,t){if(!Rg(e))return[];let o=[];for(let n of xr(e,{withFileTypes:!0})){let s=Dg(e,n.name);n.isFile()?o.push(s):n.isDirectory()&&t&&o.push(...Sr(s,!0))}return o}var Bs=new _y().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Bs.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let t of Pg){let o=_g(process.cwd(),t.dir),n=Sr(o,!!t.recursive),s=0,i=null;for(let a of n)try{let c=Ng(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(` ${Ut.cyan(t.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Ws(s).padStart(10)} oldest=${r}`)}console.log(Ut.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Ws(e).padStart(10)} total`)),console.log(),console.log(Ut.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Bs.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 t=parseInt(e.days,10);(!Number.isFinite(t)||t<1)&&(console.log(Ut.red(" --days must be a positive integer")),process.exit(1));let o=Date.now()-t*864e5,n=e.target,s=0,i=0;console.log(),console.log(Ut.bold(` Pruning files older than ${t}d (${new Date(o).toISOString().slice(0,10)})${e.dryRun?Ut.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Pg){if(n&&r.dir!==n)continue;let a=_g(process.cwd(),r.dir),c=Sr(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=Ng(u);if(f.mtimeMs<o&&(g+=f.size,l++,!e.dryRun))try{Dy(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Mg(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Ut.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${Ws(g)})`),s+=l,i+=g}console.log(),console.log(Ut.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Ws(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Mg(e){if(Rg(e))for(let t of xr(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let o=Dg(e,t.name);Mg(o);try{xr(o).length===0&&Py(o,{recursive:!1})}catch{}}}function Ws(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 My}from"commander";import U from"chalk";var qt=new My().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");qt.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let o=new yo().list();if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.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 o){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()});qt.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,t)=>{let n=new yo().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),t.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()});qt.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,t)=>{let o=Ly(t.inputs),n={id:e,title:t.title,description:t.description,inputs:o,timeoutMs:parseInt(t.timeout,10)||3e4,kind:t.kind};if(t.kind==="shell")t.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=t.command,t.cwd&&(n.cwd=t.cwd);else if(t.kind==="http"){if(t.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=t.url,n.method=t.method,t.headers)try{n.headers=JSON.parse(t.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}t.body&&(n.body=t.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=ga.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 yo().save(s.data);console.log(U.green(`
539
+ `))}catch(o){console.log(Y.red(` ${o?.message??o}`)),process.exit(1)}});import{Command as qy}from"commander";import Wt from"chalk";import{readdirSync as Tr,statSync as Mg,unlinkSync as Wy,rmSync as By,existsSync as Lg}from"fs";import{resolve as Fg,join as Ug}from"path";var qg=[{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 jr(e,t){if(!Lg(e))return[];let o=[];for(let n of Tr(e,{withFileTypes:!0})){let s=Ug(e,n.name);n.isFile()?o.push(s):n.isDirectory()&&t&&o.push(...jr(s,!0))}return o}var zs=new qy().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");zs.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let t of qg){let o=Fg(process.cwd(),t.dir),n=jr(o,!!t.recursive),s=0,i=null;for(let a of n)try{let c=Mg(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(` ${Wt.cyan(t.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Gs(s).padStart(10)} oldest=${r}`)}console.log(Wt.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Gs(e).padStart(10)} total`)),console.log(),console.log(Wt.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});zs.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 t=parseInt(e.days,10);(!Number.isFinite(t)||t<1)&&(console.log(Wt.red(" --days must be a positive integer")),process.exit(1));let o=Date.now()-t*864e5,n=e.target,s=0,i=0;console.log(),console.log(Wt.bold(` Pruning files older than ${t}d (${new Date(o).toISOString().slice(0,10)})${e.dryRun?Wt.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of qg){if(n&&r.dir!==n)continue;let a=Fg(process.cwd(),r.dir),c=jr(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=Mg(u);if(f.mtimeMs<o&&(g+=f.size,l++,!e.dryRun))try{Wy(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Wg(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Wt.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${Gs(g)})`),s+=l,i+=g}console.log(),console.log(Wt.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Gs(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Wg(e){if(Lg(e))for(let t of Tr(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let o=Ug(e,t.name);Wg(o);try{Tr(o).length===0&&By(o,{recursive:!1})}catch{}}}function Gs(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 Jy}from"commander";import U from"chalk";var Bt=new Jy().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Bt.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let o=new bo().list();if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.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 o){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()});Bt.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,t)=>{let n=new bo().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),t.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()});Bt.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,t)=>{let o=Hy(t.inputs),n={id:e,title:t.title,description:t.description,inputs:o,timeoutMs:parseInt(t.timeout,10)||3e4,kind:t.kind};if(t.kind==="shell")t.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=t.command,t.cwd&&(n.cwd=t.cwd);else if(t.kind==="http"){if(t.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=t.url,n.method=t.method,t.headers)try{n.headers=JSON.parse(t.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}t.body&&(n.body=t.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=fa.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 bo().save(s.data);console.log(U.green(`
540
540
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
541
- `))});qt.command("remove <id>").alias("rm").description("delete an action").action(e=>{new yo().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});qt.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,t)=>{let n=new yo().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of t.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 ma(n,s);if(t.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)}});qt.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,t)=>{let o=String(t.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${o}/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(t.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(t.schema){try{let r=((await(await fetch(`${o}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),t.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(t.input)try{n=JSON.parse(t.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${o}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(t.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)),t.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 Ly(e){if(!e)return[];let t=[];for(let o of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=o.endsWith("!"),s=n?o.slice(0,-1):o,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";t.push({name:r,type:a,required:n})}return t}ie();import{Command as Fy}from"commander";import oe from"chalk";var Lg=new Fy().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 t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let r=I(e.config);t||(t=r.dashboard?.daemonUrl||""),o||(o=r.dashboard?.token||"")}catch{}t||(t="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=`${t.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(oe.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};o&&(i.Authorization=`Bearer ${o}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(oe.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(oe.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(`
541
+ `))});Bt.command("remove <id>").alias("rm").description("delete an action").action(e=>{new bo().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Bt.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,t)=>{let n=new bo().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of t.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await ha(n,s);if(t.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)}});Bt.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,t)=>{let o=String(t.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${o}/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(t.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(t.schema){try{let r=((await(await fetch(`${o}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),t.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(t.input)try{n=JSON.parse(t.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${o}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(t.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)),t.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 Hy(e){if(!e)return[];let t=[];for(let o of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=o.endsWith("!"),s=n?o.slice(0,-1):o,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";t.push({name:r,type:a,required:n})}return t}ne();import{Command as Gy}from"commander";import oe from"chalk";var Bg=new Gy().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 t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let r=I(e.config);t||(t=r.dashboard?.daemonUrl||""),o||(o=r.dashboard?.token||"")}catch{}t||(t="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=`${t.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(oe.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};o&&(i.Authorization=`Bearer ${o}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(oe.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(oe.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(`
542
542
 
543
- `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),Uy(f)}}}catch(r){console.error(oe.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Uy(e){let t="message",o="";for(let i of e.split(`
544
- `))i.startsWith("event: ")?t=i.slice(7):i.startsWith("data: ")&&(o=i.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?oe.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let i=oe.cyan(n.phase?.padEnd(9)??"run"),r=oe.bold(n.workflowId??""),a=oe.dim((n.runId??"").slice(0,8)),c=n.nodeId?oe.yellow(n.nodeId):"",l=n.note?oe.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=oe.magenta(`task.${n.phase}`.padEnd(14)),r=oe.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?oe.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${oe.cyan(a)} ${c}`);break}case"signal":{let i=oe.green("signal".padEnd(9)),r=oe.bold(n.name),a=oe.dim(`(${n.scope})`),c=n.workflowId?oe.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=oe.blue("mesh".padEnd(9)),r=oe.bold(n.peer),a=n.healthy?oe.green("\u2713 healthy"):oe.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${oe.dim(n.delta??"")}`);break}case"channel":{let i=oe.yellow("channel".padEnd(9)),r=n.direction==="in"?oe.cyan("\u2190"):oe.magenta("\u2192"),a=oe.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?oe.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(oe.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}ie();import{Command as qy}from"commander";import Vo from"chalk";function Wy(e,t){let o=e.replace(/\/+$/,""),n=new URLSearchParams;if(t.since&&n.set("since",t.since),t.limit&&n.set("limit",t.limit),t.agent){let s=n.toString();return`${o}/agents/${encodeURIComponent(t.agent)}/events${s?`?${s}`:""}`}return t.kind&&n.set("kind",t.kind),t.limit||n.set("limit","50"),`${o}/events/recent?${n}`}var Fg=new qy().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 t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let a=I(e.config);t||(t=a.dashboard?.daemonUrl||""),o||(o=a.dashboard?.token||"")}catch{}t||(t="http://localhost:18800");let n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(Wy(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(Vo.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(Vo.red(` daemon unreachable at ${t}: ${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(Vo.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(Vo.dim(" no events"));return}for(let a of i)console.log(` ${ca(a)} ${Vo.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(Vo.dim(`
545
- ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as Jy}from"commander";import Nn from"chalk";import{spawn as Hy}from"node:child_process";import{execFileSync as By}from"node:child_process";function Ug(e=()=>By("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=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 o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var qg=new Jy().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(Nn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-L4JAPXTE.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Ug();if(n?.ok){let{fetchAgents:l}=await import("./client-L4JAPXTE.js"),g=await l(o);if(!g.length)throw new Error(`No AgentX agents returned by ${o.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${o.baseUrl}/v1`},models:f}}})};console.error(Nn.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:h,spawnImpl:Hy,log:k=>console.error(Nn.dim(k))});return}n&&!n.ok&&(console.error(Nn.yellow(n.reason)),console.error(Nn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-244WEQJR.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:o,pollMs:a})).waitUntilExit()});import{Command as Gy}from"commander";import K from"chalk";import{randomUUID as Jg}from"crypto";import{createInterface as zy}from"node:readline/promises";import Yy from"ora";import Js from"chalk";function Wg(e){console.error(),console.error(Js.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Js.dim(` ${e.why}`)),console.error(),console.error(` Use ${Js.cyan(e.instead)} instead.`),e.note&&console.error(Js.dim(` ${e.note}`)),console.error()}var Bg={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 Hg=new Gy().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,t)=>{Wg({what:"agentx chat",...Bg});let o=sl({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,i=t.chatId||`chat-cli:${Jg().slice(0,12)}`,r=[];try{r=await ns(o)}catch(g){console.error(K.red(` cannot reach daemon at ${o.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-SFP6SHUU.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:o,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}Ky(o.baseUrl,n,i,s);let a=zy({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
546
- 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:${Jg().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await ns(o);for(let h of p){let w=h.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${w} @${h.id} ${K.dim(h.tier)} ${h.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await ns(o)).find(w=>w.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(h){console.error(K.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=Yy({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=Vy(n);try{let p=await il(o,n,g,{channel:s,chatId:i,onText:w=>{d.stop(),f.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),f.tool(w)}});d.stop();let h=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(h,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function Vy(e){let t=!1,o=!0,n=!1,s=new Set,i=()=>{t||(process.stdout.write(`${K.green(`@${e}`)}
543
+ `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),zy(f)}}}catch(r){console.error(oe.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function zy(e){let t="message",o="";for(let i of e.split(`
544
+ `))i.startsWith("event: ")?t=i.slice(7):i.startsWith("data: ")&&(o=i.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?oe.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let i=oe.cyan(n.phase?.padEnd(9)??"run"),r=oe.bold(n.workflowId??""),a=oe.dim((n.runId??"").slice(0,8)),c=n.nodeId?oe.yellow(n.nodeId):"",l=n.note?oe.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=oe.magenta(`task.${n.phase}`.padEnd(14)),r=oe.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?oe.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${oe.cyan(a)} ${c}`);break}case"signal":{let i=oe.green("signal".padEnd(9)),r=oe.bold(n.name),a=oe.dim(`(${n.scope})`),c=n.workflowId?oe.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=oe.blue("mesh".padEnd(9)),r=oe.bold(n.peer),a=n.healthy?oe.green("\u2713 healthy"):oe.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${oe.dim(n.delta??"")}`);break}case"channel":{let i=oe.yellow("channel".padEnd(9)),r=n.direction==="in"?oe.cyan("\u2190"):oe.magenta("\u2192"),a=oe.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?oe.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(oe.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}ne();import{Command as Yy}from"commander";import Xo from"chalk";function Vy(e,t){let o=e.replace(/\/+$/,""),n=new URLSearchParams;if(t.since&&n.set("since",t.since),t.limit&&n.set("limit",t.limit),t.agent){let s=n.toString();return`${o}/agents/${encodeURIComponent(t.agent)}/events${s?`?${s}`:""}`}return t.kind&&n.set("kind",t.kind),t.limit||n.set("limit","50"),`${o}/events/recent?${n}`}var Jg=new Yy().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 t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let a=I(e.config);t||(t=a.dashboard?.daemonUrl||""),o||(o=a.dashboard?.token||"")}catch{}t||(t="http://localhost:18800");let n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(Vy(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(Xo.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(Xo.red(` daemon unreachable at ${t}: ${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(Xo.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(Xo.dim(" no events"));return}for(let a of i)console.log(` ${ma(a)} ${Xo.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(Xo.dim(`
545
+ ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as Xy}from"commander";import _n from"chalk";import{spawn as Qy}from"node:child_process";import{execFileSync as Ky}from"node:child_process";function Hg(e=()=>Ky("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=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 o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var Gg=new Xy().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(_n.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-7SK3SEQV.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Hg();if(n?.ok){let{fetchAgents:l}=await import("./client-7SK3SEQV.js"),g=await l(o);if(!g.length)throw new Error(`No AgentX agents returned by ${o.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${o.baseUrl}/v1`},models:f}}})};console.error(_n.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:h,spawnImpl:Qy,log:k=>console.error(_n.dim(k))});return}n&&!n.ok&&(console.error(_n.yellow(n.reason)),console.error(_n.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-U2MOUDOM.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:o,pollMs:a})).waitUntilExit()});import{Command as Zy}from"commander";import K from"chalk";import{randomUUID as Vg}from"crypto";import{createInterface as ew}from"node:readline/promises";import tw from"ora";import Ys from"chalk";function zg(e){console.error(),console.error(Ys.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Ys.dim(` ${e.why}`)),console.error(),console.error(` Use ${Ys.cyan(e.instead)} instead.`),e.note&&console.error(Ys.dim(` ${e.note}`)),console.error()}var Yg={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 Kg=new Zy().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,t)=>{zg({what:"agentx chat",...Yg});let o=ll({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,i=t.chatId||`chat-cli:${Vg().slice(0,12)}`,r=[];try{r=await as(o)}catch(g){console.error(K.red(` cannot reach daemon at ${o.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-YY4RGZSI.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:o,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}nw(o.baseUrl,n,i,s);let a=ew({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
546
+ 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:${Vg().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await as(o);for(let h of p){let w=h.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${w} @${h.id} ${K.dim(h.tier)} ${h.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await as(o)).find(w=>w.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(h){console.error(K.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=tw({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=ow(n);try{let p=await dl(o,n,g,{channel:s,chatId:i,onText:w=>{d.stop(),f.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),f.tool(w)}});d.stop();let h=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(h,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function ow(e){let t=!1,o=!0,n=!1,s=new Set,i=()=>{t||(process.stdout.write(`${K.green(`@${e}`)}
547
547
  `),t=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)o&&a!==`
548
548
  `&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
549
549
  `&&(o=!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),o||(process.stdout.write(`
@@ -558,17 +558,17 @@ agentx wiki questions`,me=O?.daemon?.port??O?.port??18800;try{let J=await fetch(
558
558
  `))},finishError(r){t&&!o&&process.stdout.write(`
559
559
  `),process.stdout.write(K.red(` \u2717 ${r}
560
560
 
561
- `))}}}function Ky(e,t,o,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${o}`)),console.log(K.dim(` agent: @${t} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Xy}from"commander";import Z from"chalk";import{readFileSync as Qy}from"fs";import{existsSync as Zy,readdirSync as ew}from"fs";import{resolve as tw}from"path";var Hs=["user","feedback","project","reference"],Wt=new Xy().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Wt.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(!Hs.includes(e.type)){console.error(Z.red(` --type must be one of: ${Hs.join(", ")}`)),process.exitCode=1;return}let t=e.body??"";if(e.file)if(e.file==="-")t=await ow();else try{t=Qy(e.file,"utf-8")}catch(s){console.error(Z.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!t.trim()){console.error(Z.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new uo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:t});console.log(Z.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Wt.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let o=new uo().list(e.agent);if(e.type){if(!Hs.includes(e.type)){console.error(Z.red(` --type must be one of: ${Hs.join(", ")}`)),process.exitCode=1;return}o=o.filter(s=>s.type===e.type)}if(!o.length){console.log(Z.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of o)s.type!==n&&(console.log(Z.bold(` ${s.type}`)),n=s.type),console.log(` ${Z.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Z.dim(` ${o.length} memor${o.length===1?"y":"ies"} for ${e.agent}`))});Wt.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{let n=new uo().get(t.agent,e);if(!n){console.error(Z.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(Z.bold(`${n.type}/${n.name}`)+Z.dim(` (${n.description})`)),console.log(Z.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Wt.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{if(!new uo().remove(t.agent,e)){console.error(Z.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 memory "${e}" removed`))});Wt.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let o=new uo().indexMarkdown(e.agent);if(!o){console.log(Z.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(o)});var Rn=Wt.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function Gs(e){if(e)return[e];let t=tw(process.cwd(),".agentx/memory");return Zy(t)?ew(t).filter(o=>o.endsWith(".jsonl")).map(o=>o.slice(0,-6)).sort():[]}Rn.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let t=new po;for(let o of Gs(e.agent)){let n=Object.entries(t.trustSummary(o)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${Z.bold(o)} ${n||Z.dim("(none)")}`)}});Rn.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let t=new po,o=0;for(let n of Gs(e.agent))for(let s of t.held(n))o++,console.log(` ${Z.bold(n)} ${Z.cyan(s.id)} ${Z.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);o===0&&console.log(Z.dim(" nothing held"))});for(let e of["approve","reject"])Rn.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((t,o)=>{if(!new po().review(o.agent,t,e==="approve"?"approved":"rejected")){console.error(Z.red(` no fact "${t}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 ${t} ${e==="approve"?"approved":"rejected"}`))});Rn.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 t=new po,o=0;for(let n of Gs(e.agent)){let s=t.scrubSecrets(n,!!e.apply);s&&console.log(` ${Z.bold(n)} ${s}`),o+=s}console.log(e.apply?Z.green(` \u2713 deleted ${o} fact(s) containing credentials`):Z.dim(` ${o} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});Rn.command("flag-unsourced").description("mark facts about billing, accounts, outages or deploys that name no source as unverified; --apply writes (with a backup)").option("--agent <id>","one agent (default: all)").option("--apply","flag them (default: list only)").action(async e=>{let{flagUnsourced:t}=await import("./memory-migrate-ED37IBEL.js"),o=new po,n=0;for(let s of Gs(e.agent)){let i=t(o,s,{apply:!!e.apply});if(i.flagged.length!==0){n+=i.flagged.length,console.log(` ${Z.bold(s)} ${i.flagged.length}${i.backup?Z.dim(` (backup: ${i.backup})`):""}`);for(let r of i.flagged.slice(0,10))console.log(Z.dim(` ${r.id} [${r.volatility}] ${r.content.slice(0,100)}`))}}console.log(e.apply?Z.green(` \u2713 flagged ${n} fact(s) as unverified`):Z.dim(` ${n} fact(s) state billing, account, outage or deploy state with no source. Run with --apply to flag them.`))});async function ow(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}wm();import Er from"chalk";import{Command as nw}from"commander";import{resolve as sw}from"path";var Gg=new nw().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(sw(e.cwd)),e.stdio!==!1?await Na():(ft.error("Only stdio transport is currently supported."),ft.info(`Usage: ${Er.green("agentx serve --stdio")} or configure in your MCP client.`),ft.break(),ft.info("Add to Claude Code:"),ft.info(Er.dim(" claude mcp add agentx -- npx agentx serve --stdio")),ft.break(),ft.info("Add to Cursor/MCP config:"),ft.info(Er.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(t){Jc(t)}});import{Command as pw}from"commander";import ce from"chalk";import{spawn as Ar}from"child_process";import{mkdirSync as uw,writeFileSync as Vs,readFileSync as fw,readdirSync as hw,rmSync as Qg,openSync as Zg,existsSync as zs}from"fs";import{resolve as yw,join as Fe}from"path";import{randomBytes as ww}from"crypto";var zg={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"}]};ie();import{existsSync as iw,readFileSync as rw}from"fs";import{cpus as aw,loadavg as cw}from"os";import{resolve as lw}from"path";var Yg="AGENTX_DEMO_STARTUP_TIMEOUT",dw=60,gw=300;function mw(e,t){let o=Math.max(1,e/Math.max(1,t));return Math.min(gw,Math.ceil(dw*o))}function Vg(e,t){if(e===void 0||e.trim()==="")return;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`${t} must be a positive number of seconds, got "${e}"`);return o}function Kg(e){let t=lw(e,"agentx.json");if(!iw(t))return;let o;try{o=JSON.parse(rw(t,"utf8"))}catch{return}let n=Jr.shape.demo.safeParse(o?.demo);if(!n.success)throw new Error(`${t}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function Xg(e){let t=Vg(e.flag,"--startup-timeout");if(t!==void 0)return{seconds:t,source:"--startup-timeout"};let o=Vg(e.env,Yg);if(o!==void 0)return{seconds:o,source:Yg};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??cw()[0],s=e.cpuCount??aw().length;return{seconds:mw(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var em="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",bw="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function $w(e,t){return[{dir:Fe(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:t,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(zg,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:Fe(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:t+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:Fe(e,"node-c"),id:"demo-pi",name:"pi-office",port:t+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 kw(e,t,o){let n=Fe(e.dir,"workspaces",e.agentId);uw(n,{recursive:!0}),Vs(Fe(n,"CLAUDE.md"),`# ${e.agentName}
561
+ `))}}}function nw(e,t,o,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${o}`)),console.log(K.dim(` agent: @${t} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as sw}from"commander";import Z from"chalk";import{readFileSync as iw}from"fs";import{existsSync as rw,readdirSync as aw}from"fs";import{resolve as cw}from"path";var Vs=["user","feedback","project","reference"],Jt=new sw().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Jt.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(!Vs.includes(e.type)){console.error(Z.red(` --type must be one of: ${Vs.join(", ")}`)),process.exitCode=1;return}let t=e.body??"";if(e.file)if(e.file==="-")t=await lw();else try{t=iw(e.file,"utf-8")}catch(s){console.error(Z.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!t.trim()){console.error(Z.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new ho().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:t});console.log(Z.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Jt.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let o=new ho().list(e.agent);if(e.type){if(!Vs.includes(e.type)){console.error(Z.red(` --type must be one of: ${Vs.join(", ")}`)),process.exitCode=1;return}o=o.filter(s=>s.type===e.type)}if(!o.length){console.log(Z.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of o)s.type!==n&&(console.log(Z.bold(` ${s.type}`)),n=s.type),console.log(` ${Z.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Z.dim(` ${o.length} memor${o.length===1?"y":"ies"} for ${e.agent}`))});Jt.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{let n=new ho().get(t.agent,e);if(!n){console.error(Z.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(Z.bold(`${n.type}/${n.name}`)+Z.dim(` (${n.description})`)),console.log(Z.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Jt.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{if(!new ho().remove(t.agent,e)){console.error(Z.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 memory "${e}" removed`))});Jt.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let o=new ho().indexMarkdown(e.agent);if(!o){console.log(Z.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(o)});var Dn=Jt.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function Ks(e){if(e)return[e];let t=cw(process.cwd(),".agentx/memory");return rw(t)?aw(t).filter(o=>o.endsWith(".jsonl")).map(o=>o.slice(0,-6)).sort():[]}Dn.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let t=new fo;for(let o of Ks(e.agent)){let n=Object.entries(t.trustSummary(o)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${Z.bold(o)} ${n||Z.dim("(none)")}`)}});Dn.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let t=new fo,o=0;for(let n of Ks(e.agent))for(let s of t.held(n))o++,console.log(` ${Z.bold(n)} ${Z.cyan(s.id)} ${Z.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);o===0&&console.log(Z.dim(" nothing held"))});for(let e of["approve","reject"])Dn.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((t,o)=>{if(!new fo().review(o.agent,t,e==="approve"?"approved":"rejected")){console.error(Z.red(` no fact "${t}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 ${t} ${e==="approve"?"approved":"rejected"}`))});Dn.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 t=new fo,o=0;for(let n of Ks(e.agent)){let s=t.scrubSecrets(n,!!e.apply);s&&console.log(` ${Z.bold(n)} ${s}`),o+=s}console.log(e.apply?Z.green(` \u2713 deleted ${o} fact(s) containing credentials`):Z.dim(` ${o} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});Dn.command("flag-unsourced").description("mark facts about billing, accounts, outages or deploys that name no source as unverified; --apply writes (with a backup)").option("--agent <id>","one agent (default: all)").option("--apply","flag them (default: list only)").action(async e=>{let{flagUnsourced:t}=await import("./memory-migrate-ED37IBEL.js"),o=new fo,n=0;for(let s of Ks(e.agent)){let i=t(o,s,{apply:!!e.apply});if(i.flagged.length!==0){n+=i.flagged.length,console.log(` ${Z.bold(s)} ${i.flagged.length}${i.backup?Z.dim(` (backup: ${i.backup})`):""}`);for(let r of i.flagged.slice(0,10))console.log(Z.dim(` ${r.id} [${r.volatility}] ${r.content.slice(0,100)}`))}}console.log(e.apply?Z.green(` \u2713 flagged ${n} fact(s) as unverified`):Z.dim(` ${n} fact(s) state billing, account, outage or deploy state with no source. Run with --apply to flag them.`))});async function lw(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}Em();import Or from"chalk";import{Command as dw}from"commander";import{resolve as gw}from"path";var Xg=new dw().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(gw(e.cwd)),e.stdio!==!1?await Pa():(ht.error("Only stdio transport is currently supported."),ht.info(`Usage: ${Or.green("agentx serve --stdio")} or configure in your MCP client.`),ht.break(),ht.info("Add to Claude Code:"),ht.info(Or.dim(" claude mcp add agentx -- npx agentx serve --stdio")),ht.break(),ht.info("Add to Cursor/MCP config:"),ht.info(Or.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(t){Vc(t)}});import{Command as $w}from"commander";import ce from"chalk";import{spawn as Ir}from"child_process";import{mkdirSync as kw,writeFileSync as Zs,readFileSync as vw,readdirSync as xw,rmSync as nm,openSync as sm,existsSync as Xs}from"fs";import{resolve as Sw,join as Ue}from"path";import{randomBytes as Ew}from"crypto";var Qg={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"}]};ne();import{existsSync as mw,readFileSync as pw}from"fs";import{cpus as uw,loadavg as fw}from"os";import{resolve as hw}from"path";var Zg="AGENTX_DEMO_STARTUP_TIMEOUT",yw=60,ww=300;function bw(e,t){let o=Math.max(1,e/Math.max(1,t));return Math.min(ww,Math.ceil(yw*o))}function em(e,t){if(e===void 0||e.trim()==="")return;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`${t} must be a positive number of seconds, got "${e}"`);return o}function tm(e){let t=hw(e,"agentx.json");if(!mw(t))return;let o;try{o=JSON.parse(pw(t,"utf8"))}catch{return}let n=Vr.shape.demo.safeParse(o?.demo);if(!n.success)throw new Error(`${t}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function om(e){let t=em(e.flag,"--startup-timeout");if(t!==void 0)return{seconds:t,source:"--startup-timeout"};let o=em(e.env,Zg);if(o!==void 0)return{seconds:o,source:Zg};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??fw()[0],s=e.cpuCount??uw().length;return{seconds:bw(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var im="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Aw="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Tw(e,t){return[{dir:Ue(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:t,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(Qg,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:Ue(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:t+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:Ue(e,"node-c"),id:"demo-pi",name:"pi-office",port:t+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 jw(e,t,o){let n=Ue(e.dir,"workspaces",e.agentId);kw(n,{recursive:!0}),Zs(Ue(n,"CLAUDE.md"),`# ${e.agentName}
562
562
 
563
563
  ${e.persona}
564
- `),Vs(Fe(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=t.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:o})),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}};Vs(Fe(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Tr(e,t,o){let n=Date.now();for(;Date.now()-n<o;){try{if(await t())return}catch{}await new Promise(s=>setTimeout(s,250))}throw new Error(`Timed out waiting for ${e} (${o/1e3}s) \u2014 raise it with --startup-timeout <seconds>`)}function jr(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function Or(e,t,o){let n=await fetch(`http://127.0.0.1:${e}${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${t} HTTP ${n.status}`);return s}function Ys(e,t,o){console.log(),console.log(o(` ${e}`)),console.log(` ${t.split(`
564
+ `),Zs(Ue(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=t.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:o})),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}};Zs(Ue(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Cr(e,t,o){let n=Date.now();for(;Date.now()-n<o;){try{if(await t())return}catch{}await new Promise(s=>setTimeout(s,250))}throw new Error(`Timed out waiting for ${e} (${o/1e3}s) \u2014 raise it with --startup-timeout <seconds>`)}function Nr(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function Rr(e,t,o){let n=await fetch(`http://127.0.0.1:${e}${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${t} HTTP ${n.status}`);return s}function Qs(e,t,o){console.log(),console.log(o(` ${e}`)),console.log(` ${t.split(`
565
565
  `).join(`
566
- `)}`)}var tm=new pw().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").option("--startup-timeout <seconds>","seconds each startup step may take (default: 60, longer when the machine is loaded)").action(async e=>{let t=parseInt(e.basePort,10),o=yw(process.cwd(),".agentx-demo"),n;try{n=Xg({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:Kg(process.cwd())})}catch(h){console.error(ce.red(h.message)),process.exit(1)}let s=n.seconds*1e3,i=$w(o,t),r=Fe(o,"mesh-token"),a=!!e.reuse&&zs(r)&&zs(Fe(i[0].dir,"agentx.json")),c=a?fw(r,"utf8").trim():ww(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!zs(d))&&(console.error(ce.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if(zs(o))for(let h of hw(o))Qg(Fe(o,h),{recursive:!0,force:!0});for(let h of i)kw(h,i,c);Vs(r,c+`
567
- `,{mode:384})}console.log(),console.log(ce.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ce.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ce.dim(" Run `agentx setup` to wire real agents.\n")),console.log(ce.dim(` Startup limit: ${n.seconds}s per step (${n.source})`));let u=!1,f=h=>{if(!u){u=!0;for(let w of g)try{w.kill("SIGTERM")}catch{}setTimeout(()=>{if(!l)try{Qg(o,{recursive:!0,force:!0})}catch{}process.exit(h)},800)}};process.on("SIGINT",()=>f(0)),process.on("SIGTERM",()=>f(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let b of i){let E=Zg(Fe(b.dir,"daemon.log"),"a"),S=Ar(process.execPath,[d,"daemon","start","-c",Fe(b.dir,"agentx.json")],{cwd:b.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:Fe(b.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(ce.dim(` \u25B8 ${b.name} starting on 127.0.0.1:${b.port} (log: ${Fe(b.dir,"daemon.log")})`))}let h=b=>Tr(`${b.name} /health`,async()=>(await jr(`http://127.0.0.1:${b.port}/health`)).ok,s);await h(i[0]);let w=i[0].port+10;{let b=Zg(Fe(i[0].dir,"board.log"),"a"),E=Ar(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",b,b]});g.push(E)}for(let b of i.slice(1))await h(b);console.log(ce.green(" \u2713 three daemons up")),await Tr("dashboard /live",async()=>(await jr(`http://127.0.0.1:${w}/live`)).ok,s),console.log(ce.green(" \u2713 dashboard up")),await Tr("mesh discovery (laptop sees both peers)",async()=>((await(await jr(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(x=>x.healthy&&x.skills?.length).length>=2,s),console.log(ce.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let k=`http://127.0.0.1:${w}/live`;if(console.log(),console.log(` Dashboard: ${ce.cyan(k)} (all three nodes via the mesh)`),console.log(ce.dim(` Daemon APIs: ${i.map(b=>`127.0.0.1:${b.port}`).join(" \xB7 ")}`)),e.open!==!1){let b=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Ar(b,[k],{stdio:"ignore",detached:!0}).unref()}catch{}}let $=async()=>{console.log(),console.log(ce.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Ys("You \u2192 @cx (laptop-paris)",em,ce.cyan);let b=await Or(i[0].port,"/task",{agent:"cx",message:em});Ys("@cx (laptop-paris)",b.content||"(no content)",ce.green),console.log(),console.log(ce.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await Or(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:bw}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";Ys("@builder (vps-nyc)",S,ce.yellow);let x=await Or(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});Ys("@cx (laptop-paris)",x.content||"(no content)",ce.green),console.log(),console.log(ce.dim(` Inspect the run: ${k} \xB7 ledger rows on each node record every dispatch`)),console.log(ce.dim(` Worth your time? A star helps others find it: ${ce.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(ce.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await $(),e.once){console.log(),console.log(ce.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(ce.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{$().catch(b=>console.error(ce.red(` Replay failed: ${b.message}`)))}),process.stdin.resume()}catch(h){console.error(),console.error(ce.red(` Demo failed: ${h.message}`)),console.error(ce.dim(` Node logs: ${i.map(w=>Fe(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as vw}from"commander";import{randomUUID as xw}from"crypto";import{readFileSync as Sw}from"fs";import{resolve as Ew}from"path";ie();var nm=new vw().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,t)=>{let o=(e??Sw(0,"utf8")).trim();o||om("no task given (pass it as an argument or on stdin)");let n=I(t.config?Ew(t.config):void 0),s=n.agents[t.agent];s||om(`unknown agent "${t.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(t.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";oa(t.agent,s,l,i)}let r=new $a(n,i),a=Date.now(),c=await r.execute({agentId:t.agent,message:o,model:t.model,timeoutMinutes:t.timeout?Number(t.timeout):void 0,context:{channel:"exec",chatId:`exec-${xw()}`,sender:"cli"}});t.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})+`
566
+ `)}`)}var rm=new $w().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").option("--startup-timeout <seconds>","seconds each startup step may take (default: 60, longer when the machine is loaded)").action(async e=>{let t=parseInt(e.basePort,10),o=Sw(process.cwd(),".agentx-demo"),n;try{n=om({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:tm(process.cwd())})}catch(h){console.error(ce.red(h.message)),process.exit(1)}let s=n.seconds*1e3,i=Tw(o,t),r=Ue(o,"mesh-token"),a=!!e.reuse&&Xs(r)&&Xs(Ue(i[0].dir,"agentx.json")),c=a?vw(r,"utf8").trim():Ew(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!Xs(d))&&(console.error(ce.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if(Xs(o))for(let h of xw(o))nm(Ue(o,h),{recursive:!0,force:!0});for(let h of i)jw(h,i,c);Zs(r,c+`
567
+ `,{mode:384})}console.log(),console.log(ce.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ce.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ce.dim(" Run `agentx setup` to wire real agents.\n")),console.log(ce.dim(` Startup limit: ${n.seconds}s per step (${n.source})`));let u=!1,f=h=>{if(!u){u=!0;for(let w of g)try{w.kill("SIGTERM")}catch{}setTimeout(()=>{if(!l)try{nm(o,{recursive:!0,force:!0})}catch{}process.exit(h)},800)}};process.on("SIGINT",()=>f(0)),process.on("SIGTERM",()=>f(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let b of i){let E=sm(Ue(b.dir,"daemon.log"),"a"),S=Ir(process.execPath,[d,"daemon","start","-c",Ue(b.dir,"agentx.json")],{cwd:b.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:Ue(b.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(ce.dim(` \u25B8 ${b.name} starting on 127.0.0.1:${b.port} (log: ${Ue(b.dir,"daemon.log")})`))}let h=b=>Cr(`${b.name} /health`,async()=>(await Nr(`http://127.0.0.1:${b.port}/health`)).ok,s);await h(i[0]);let w=i[0].port+10;{let b=sm(Ue(i[0].dir,"board.log"),"a"),E=Ir(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",b,b]});g.push(E)}for(let b of i.slice(1))await h(b);console.log(ce.green(" \u2713 three daemons up")),await Cr("dashboard /live",async()=>(await Nr(`http://127.0.0.1:${w}/live`)).ok,s),console.log(ce.green(" \u2713 dashboard up")),await Cr("mesh discovery (laptop sees both peers)",async()=>((await(await Nr(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(x=>x.healthy&&x.skills?.length).length>=2,s),console.log(ce.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let k=`http://127.0.0.1:${w}/live`;if(console.log(),console.log(` Dashboard: ${ce.cyan(k)} (all three nodes via the mesh)`),console.log(ce.dim(` Daemon APIs: ${i.map(b=>`127.0.0.1:${b.port}`).join(" \xB7 ")}`)),e.open!==!1){let b=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Ir(b,[k],{stdio:"ignore",detached:!0}).unref()}catch{}}let $=async()=>{console.log(),console.log(ce.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Qs("You \u2192 @cx (laptop-paris)",im,ce.cyan);let b=await Rr(i[0].port,"/task",{agent:"cx",message:im});Qs("@cx (laptop-paris)",b.content||"(no content)",ce.green),console.log(),console.log(ce.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await Rr(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Aw}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";Qs("@builder (vps-nyc)",S,ce.yellow);let x=await Rr(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});Qs("@cx (laptop-paris)",x.content||"(no content)",ce.green),console.log(),console.log(ce.dim(` Inspect the run: ${k} \xB7 ledger rows on each node record every dispatch`)),console.log(ce.dim(` Worth your time? A star helps others find it: ${ce.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(ce.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await $(),e.once){console.log(),console.log(ce.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(ce.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{$().catch(b=>console.error(ce.red(` Replay failed: ${b.message}`)))}),process.stdin.resume()}catch(h){console.error(),console.error(ce.red(` Demo failed: ${h.message}`)),console.error(ce.dim(` Node logs: ${i.map(w=>Ue(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as Ow}from"commander";import{randomUUID as Iw}from"crypto";import{readFileSync as Cw}from"fs";import{resolve as Nw}from"path";ne();var cm=new Ow().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,t)=>{let o=(e??Cw(0,"utf8")).trim();o||am("no task given (pass it as an argument or on stdin)");let n=I(t.config?Nw(t.config):void 0),s=n.agents[t.agent];s||am(`unknown agent "${t.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(t.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";aa(t.agent,s,l,i)}let r=new Sa(n,i),a=Date.now(),c=await r.execute({agentId:t.agent,message:o,model:t.model,timeoutMinutes:t.timeout?Number(t.timeout):void 0,context:{channel:"exec",chatId:`exec-${Iw()}`,sender:"cli"}});t.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})+`
568
568
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
569
- `),process.exit(c.error?1:0)});function om(e){console.error(`agentx exec: ${e}`),process.exit(1)}ie();import{Command as Aw}from"commander";import Ce from"chalk";var Bt=new Aw().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Bt.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 o=(await _n("/whatsapp/chats")).chats??[];if(e.group&&(o=o.filter(n=>n.isGroup)),e.dm&&(o=o.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(Ce.dim(" no chats cached yet"));return}console.log(),console.log(Ce.bold(` ${o.length} chat${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=n.isGroup?Ce.cyan("group"):Ce.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ce.dim(n.jid.padEnd(40))} ${Ce.dim(i)}`)}console.log()}catch(t){Ko(t)}});Bt.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 o=(await _n("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(Ce.dim(" no contacts cached yet"));return}console.log(),console.log(Ce.bold(` ${o.length} contact${o.length===1?"":"s"}`)),console.log();for(let n of o){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} ${Ce.dim(i)} ${Ce.dim(n.jid)}`)}console.log()}catch(t){Ko(t)}});Bt.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 t={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(t.agent=e.agent);let o=await Cr("/whatsapp/ingest",t);Ir(o,!!e.dryRun)}catch(t){Ko(t)}});Bt.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,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};t.agent&&(o.agent=t.agent);let n=await Cr("/whatsapp/ingest",o);Ir(n,!!t.dryRun)}catch(o){Ko(o)}});Bt.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,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e};t.agent&&(o.agent=t.agent),t.messages&&(o.forceMode="messages");let n=await Cr("/whatsapp/ingest",o);Ir(n,!!t.dryRun)}catch(o){Ko(o)}});Bt.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await _n("/whatsapp/state"),t=await _n("/whatsapp/chats"),o=await _n("/whatsapp/contacts");console.log(),console.log(Ce.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${t.chats?.length??0}`),console.log(` cached contacts: ${o.contacts?.length??0}`),console.log()}catch(e){Ko(e)}});function Ir(e,t){if(console.log(),console.log(Ce.bold(t?" 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(Ce.yellow(` errors: ${e.errors.length}`));for(let o of e.errors.slice(0,5))console.log(Ce.yellow(` - [${o.kind}] ${o.jid}: ${o.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(Ce.dim(" would-be entries:"));for(let o of e.dryRunEntries.slice(0,10))console.log(Ce.dim(` - ${o.id} (${o.source}, ${o.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ce.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function sm(){try{let e=I(),[t,o]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${o||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function _n(e){let t=await fetch(`${sm()}${e}`,{signal:AbortSignal.timeout(1e4)}),o=await t.json().catch(()=>({}));if(!t.ok)throw new Error(o.error||`HTTP ${t.status}`);return o}async function Cr(e,t){let o=await fetch(`${sm()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(6e5)}),n=await o.json().catch(()=>({}));if(!o.ok)throw new Error(n.error||`HTTP ${o.status}`);return n}function Ko(e){console.error(Ce.red(` ${e.message||e}`)),process.exit(1)}ie();import{Command as Tw}from"commander";import ge from"chalk";import{existsSync as jw,mkdirSync as im,writeFileSync as Dn}from"fs";import{join as Xo,resolve as Ow}from"path";var Pn=new Tw().name("plugin").description("manage agentx plugins (Move B)");Pn.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let t=I().plugins??[];if(console.log(),t.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: ${t.length}`)),console.log();for(let o of t)console.log(` ${ge.cyan(o)}`);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}});Pn.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,t)=>{/^(@[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 o=e.startsWith("@")?e.split("/")[1]:e,n=Ow(t.cwd,o);jw(n)&&!t.force&&(console.log(ge.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),im(n,{recursive:!0}),im(Xo(n,"src"),{recursive:!0});let s=t.description||`AgentX plugin: ${e}`;Dn(Xo(n,"package.json"),Rw(e,s)),Dn(Xo(n,"tsconfig.json"),_w()),Dn(Xo(n,"src/index.ts"),Dw(e)),Dn(Xo(n,"README.md"),Pw(e,s)),Dn(Xo(n,".gitignore"),Mw()),console.log(),console.log(ge.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ge.bold(" Next steps:")),console.log(ge.dim(` cd ${o}`)),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()});Pn.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let t=I().plugins??[];if(console.log(),t.length===0){console.log(ge.dim(" No plugins configured. Nothing to check.")),console.log();return}let o=0;for(let n of t){let s=await Iw(n);s.kind==="ok"?console.log(` ${ge.green("\u2713")} ${ge.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(o++,console.log(` ${ge.red("\u2717")} ${ge.cyan(n)} \u2014 ${s.reason}`))}console.log(),o>0&&(console.log(ge.red(` ${o}/${t.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});async function Iw(e){let t;try{t=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let o=Cw(t);if(!Nw(o))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=dc.safeParse(o.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 Cw(e){if(e==null||typeof e!="object")return e;let t=e;if(t.default&&typeof t.default=="object"){let o=t.default;if(o.manifest&&typeof o.setup=="function")return o;if(o.default&&typeof o.default=="object"){let n=o.default;if(n.manifest&&typeof n.setup=="function")return n}}return t.manifest&&typeof t.setup=="function"?t:t.default??t}function Nw(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Rw(e,t){return JSON.stringify({name:e,version:"0.1.0",description:t,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)+`
570
- `}function _w(){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)+`
571
- `}function Dw(e){return`// ${e} \u2014 AgentX plugin
569
+ `),process.exit(c.error?1:0)});function am(e){console.error(`agentx exec: ${e}`),process.exit(1)}ne();import{Command as _w}from"commander";import Ne from"chalk";import{Command as Rw}from"commander";import Ce from"chalk";ne();var go=new Rw("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function Pn(e){let t="",o=await pe(n=>{n.whatsappTriage=n.whatsappTriage&&typeof n.whatsappTriage=="object"?n.whatsappTriage:{},n.whatsappTriage.rules=Array.isArray(n.whatsappTriage.rules)?n.whatsappTriage.rules:[],t=e(n.whatsappTriage,n)});o.success||(console.error(Ce.red(`\u2717 ${o.error}`)),process.exit(1)),console.log(Ce.green(`\u2713 ${t}`)),o.reloaded&&console.log(Ce.dim(" daemon hot-reloaded"))}function dm(e,t){let o=e.rules.find(n=>n.id===t);if(!o)throw new Error(`No watch rule "${t}". See \`agentx whatsapp triage status\`.`);return o}var lm=(e,t=[])=>[...t,e];go.command("status").description("show triage settings and watch rules").action(()=>{let e=I().whatsappTriage,t=!!process.env[e.secretEnv];console.log(),console.log(` WhatsApp triage: ${e.enabled?Ce.green("on"):Ce.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${t?Ce.green("set in this shell"):Ce.yellow("not set in this shell; the daemon needs it too")}`),console.log(` Batch: ${e.batchSeconds} s \xB7 auto-acknowledge allowed: ${e.allowAutoAck?"yes":"no"}`),console.log(),e.rules.length===0&&console.log(Ce.dim(" no watch rules yet: agentx whatsapp triage rule add <id> --agent <agent> --chat <number or JID>"));for(let o of e.rules){let n=o.quietHours?` \xB7 quiet ${o.quietHours.start}\u2013${o.quietHours.end}`:"";console.log(` ${o.enabled?Ce.green("\u25CF"):Ce.dim("\u25CB")} ${Ce.bold(o.id)} \u2192 ${o.agent}${n}${o.autoAck?" \xB7 autoAck":""}`),o.chats.length&&console.log(Ce.dim(` chats: ${o.chats.join(", ")}`)),o.senders.length&&console.log(Ce.dim(` senders: ${o.senders.join(", ")}`))}console.log()});go.command("on").description("turn triage on").action(()=>Pn(e=>(e.enabled=!0,"WhatsApp triage is on")));go.command("off").description("turn triage off").action(()=>Pn(e=>(e.enabled=!1,"WhatsApp triage is off")));go.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let t=Jn();t||(console.error(Ce.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let o=new _c(t).recent(Math.max(1,Number(e.limit)||20));if(o.length===0){console.log(Ce.dim(" nothing triaged yet"));return}for(let n of o){let s=new Date(n.at).toISOString().slice(0,16).replace("T"," "),i=n.error?Ce.red(n.error):`${Ce.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${Ce.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?Ce.dim(` draft whatsapp:${n.draftId}`):""}`)}});var _r=go.command("rule").description("add, remove, enable or disable a watch rule");_r.command("add <id>").description("watch a chat (or people) and send its messages to an agent").requiredOption("--agent <agent>","the agent that triages").option("--chat <jid>","a chat to watch: phone number, contact JID or group JID (repeatable)",lm).option("--sender <jid>","only messages from this person (repeatable)",lm).option("--prompt <text>","extra instructions for the agent").option("--quiet <range>","no notifications in this window, e.g. 22:00-07:00").option("--auto-ack","send short acknowledgements without asking (also needs allowAutoAck)").action((e,t)=>Pn((o,n)=>{if(!n.agents?.[t.agent])throw new Error(`No agent "${t.agent}" on this computer.`);if(o.rules.some(i=>i.id===e))throw new Error(`Watch rule "${e}" already exists.`);let s={id:e,agent:t.agent,chats:t.chat??[],senders:t.sender??[]};if(t.prompt&&(s.prompt=t.prompt),t.quiet){let i=String(t.quiet).match(/^(\d{2}:\d{2})-(\d{2}:\d{2})$/);if(!i)throw new Error("--quiet looks like 22:00-07:00");s.quietHours={start:i[1],end:i[2]}}return t.autoAck&&(s.autoAck=!0),o.rules.push(s),`added watch rule "${e}" \u2192 ${t.agent}`}));_r.command("remove <id>").description("delete a watch rule").action(e=>Pn(t=>(dm(t,e),t.rules=t.rules.filter(o=>o.id!==e),`removed watch rule "${e}"`)));for(let[e,t]of[["enable",!0],["disable",!1]])_r.command(`${e} <id>`).description(`${e} a watch rule`).action(o=>Pn(n=>(dm(n,o).enabled=t,`watch rule "${o}" ${t?"enabled":"disabled"}`)));var xt=new _w().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");xt.addCommand(go);xt.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 o=(await Mn("/whatsapp/chats")).chats??[];if(e.group&&(o=o.filter(n=>n.isGroup)),e.dm&&(o=o.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(Ne.dim(" no chats cached yet"));return}console.log(),console.log(Ne.bold(` ${o.length} chat${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=n.isGroup?Ne.cyan("group"):Ne.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ne.dim(n.jid.padEnd(40))} ${Ne.dim(i)}`)}console.log()}catch(t){Qo(t)}});xt.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 o=(await Mn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(Ne.dim(" no contacts cached yet"));return}console.log(),console.log(Ne.bold(` ${o.length} contact${o.length===1?"":"s"}`)),console.log();for(let n of o){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} ${Ne.dim(i)} ${Ne.dim(n.jid)}`)}console.log()}catch(t){Qo(t)}});xt.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 t={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(t.agent=e.agent);let o=await Pr("/whatsapp/ingest",t);Dr(o,!!e.dryRun)}catch(t){Qo(t)}});xt.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,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};t.agent&&(o.agent=t.agent);let n=await Pr("/whatsapp/ingest",o);Dr(n,!!t.dryRun)}catch(o){Qo(o)}});xt.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,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e};t.agent&&(o.agent=t.agent),t.messages&&(o.forceMode="messages");let n=await Pr("/whatsapp/ingest",o);Dr(n,!!t.dryRun)}catch(o){Qo(o)}});xt.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Mn("/whatsapp/state"),t=await Mn("/whatsapp/chats"),o=await Mn("/whatsapp/contacts");console.log(),console.log(Ne.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${t.chats?.length??0}`),console.log(` cached contacts: ${o.contacts?.length??0}`),console.log()}catch(e){Qo(e)}});function Dr(e,t){if(console.log(),console.log(Ne.bold(t?" 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(Ne.yellow(` errors: ${e.errors.length}`));for(let o of e.errors.slice(0,5))console.log(Ne.yellow(` - [${o.kind}] ${o.jid}: ${o.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(Ne.dim(" would-be entries:"));for(let o of e.dryRunEntries.slice(0,10))console.log(Ne.dim(` - ${o.id} (${o.source}, ${o.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ne.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function gm(){try{let e=I(),[t,o]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${o||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function Mn(e){let t=await fetch(`${gm()}${e}`,{signal:AbortSignal.timeout(1e4)}),o=await t.json().catch(()=>({}));if(!t.ok)throw new Error(o.error||`HTTP ${t.status}`);return o}async function Pr(e,t){let o=await fetch(`${gm()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(6e5)}),n=await o.json().catch(()=>({}));if(!o.ok)throw new Error(n.error||`HTTP ${o.status}`);return n}function Qo(e){console.error(Ne.red(` ${e.message||e}`)),process.exit(1)}ne();import{Command as Dw}from"commander";import ge from"chalk";import{existsSync as Pw,mkdirSync as mm,writeFileSync as Ln}from"fs";import{join as Zo,resolve as Mw}from"path";var Fn=new Dw().name("plugin").description("manage agentx plugins (Move B)");Fn.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let t=I().plugins??[];if(console.log(),t.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: ${t.length}`)),console.log();for(let o of t)console.log(` ${ge.cyan(o)}`);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}});Fn.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,t)=>{/^(@[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 o=e.startsWith("@")?e.split("/")[1]:e,n=Mw(t.cwd,o);Pw(n)&&!t.force&&(console.log(ge.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),mm(n,{recursive:!0}),mm(Zo(n,"src"),{recursive:!0});let s=t.description||`AgentX plugin: ${e}`;Ln(Zo(n,"package.json"),qw(e,s)),Ln(Zo(n,"tsconfig.json"),Ww()),Ln(Zo(n,"src/index.ts"),Bw(e)),Ln(Zo(n,"README.md"),Jw(e,s)),Ln(Zo(n,".gitignore"),Hw()),console.log(),console.log(ge.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ge.bold(" Next steps:")),console.log(ge.dim(` cd ${o}`)),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()});Fn.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let t=I().plugins??[];if(console.log(),t.length===0){console.log(ge.dim(" No plugins configured. Nothing to check.")),console.log();return}let o=0;for(let n of t){let s=await Lw(n);s.kind==="ok"?console.log(` ${ge.green("\u2713")} ${ge.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(o++,console.log(` ${ge.red("\u2717")} ${ge.cyan(n)} \u2014 ${s.reason}`))}console.log(),o>0&&(console.log(ge.red(` ${o}/${t.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});async function Lw(e){let t;try{t=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let o=Fw(t);if(!Uw(o))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=uc.safeParse(o.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 Fw(e){if(e==null||typeof e!="object")return e;let t=e;if(t.default&&typeof t.default=="object"){let o=t.default;if(o.manifest&&typeof o.setup=="function")return o;if(o.default&&typeof o.default=="object"){let n=o.default;if(n.manifest&&typeof n.setup=="function")return n}}return t.manifest&&typeof t.setup=="function"?t:t.default??t}function Uw(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function qw(e,t){return JSON.stringify({name:e,version:"0.1.0",description:t,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)+`
570
+ `}function Ww(){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)+`
571
+ `}function Bw(e){return`// ${e} \u2014 AgentX plugin
572
572
  //
573
573
  // A plugin's default export is { manifest, setup }. The daemon calls
574
574
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -604,7 +604,7 @@ const plugin = {
604
604
  }
605
605
 
606
606
  export default plugin
607
- `}function Pw(e,t){return`# ${e}
607
+ `}function Jw(e,t){return`# ${e}
608
608
 
609
609
  ${t}
610
610
 
@@ -631,24 +631,24 @@ agentx plugin doctor
631
631
  \`\`\`
632
632
 
633
633
  Restart the daemon to activate.
634
- `}function Mw(){return`node_modules/
634
+ `}function Hw(){return`node_modules/
635
635
  dist/
636
636
  *.log
637
637
  .env
638
- `}import{Command as Lw}from"commander";import Ne from"chalk";import{writeFileSync as Fw,mkdirSync as Uw,existsSync as Ks,readFileSync as rm,appendFileSync as am}from"fs";import{resolve as Qo,dirname as dm}from"path";import{homedir as Rr}from"os";var gm=new Lw().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:t}=await import("./program-6C3G65YA.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Bw(o);break;case"bash":s=Yw(o);break;case"fish":s=Vw(o);break;default:console.error(Ne.red(`unsupported shell: ${n}`)),console.error(Ne.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Qo(String(e.output)):qw(n);Uw(dm(i),{recursive:!0}),Fw(i,s),console.log(Ne.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Ww(n,i,!!e.yes)});function qw(e){let t=Rr();switch(e){case"zsh":return Qo(t,".zsh","completions","_agentx");case"bash":return Qo(t,".bash_completion.d","agentx.bash");case"fish":return Qo(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Ww(e,t,o){if(e==="zsh"){let n=Qo(Rr(),".zshrc"),s=dm(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ks(n)?rm(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ne.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Ks(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),am(n,g.join(`
638
+ `}import{Command as Gw}from"commander";import Re from"chalk";import{writeFileSync as zw,mkdirSync as Yw,existsSync as ei,readFileSync as pm,appendFileSync as um}from"fs";import{resolve as en,dirname as ym}from"path";import{homedir as Lr}from"os";var wm=new Gw().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:t}=await import("./program-3DYKSCIY.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Xw(o);break;case"bash":s=ob(o);break;case"fish":s=nb(o);break;default:console.error(Re.red(`unsupported shell: ${n}`)),console.error(Re.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?en(String(e.output)):Vw(n);Yw(ym(i),{recursive:!0}),zw(i,s),console.log(Re.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Kw(n,i,!!e.yes)});function Vw(e){let t=Lr();switch(e){case"zsh":return en(t,".zsh","completions","_agentx");case"bash":return en(t,".bash_completion.d","agentx.bash");case"fish":return en(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Kw(e,t,o){if(e==="zsh"){let n=en(Lr(),".zshrc"),s=ym(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ei(n)?pm(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Re.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&ei(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),um(n,g.join(`
639
639
  `)+`
640
- `),console.log(Ne.green("\u2713 Patched ~/.zshrc")),console.log(Ne.dim("Reload your shell: exec zsh"));return}console.log(Ne.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ne.cyan(` ${i}`)),l&&console.log(Ne.cyan(` ${r}`)),console.log(),console.log(Ne.dim("Then reload: exec zsh")),console.log(Ne.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Qo(Rr(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Ks(n)?rm(n,"utf-8"):"").includes(t)){console.log(Ne.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Ks(n)){am(n,`
640
+ `),console.log(Re.green("\u2713 Patched ~/.zshrc")),console.log(Re.dim("Reload your shell: exec zsh"));return}console.log(Re.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Re.cyan(` ${i}`)),l&&console.log(Re.cyan(` ${r}`)),console.log(),console.log(Re.dim("Then reload: exec zsh")),console.log(Re.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=en(Lr(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((ei(n)?pm(n,"utf-8"):"").includes(t)){console.log(Re.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&ei(n)){um(n,`
641
641
  # agentx completion
642
642
  ${s}
643
- `),console.log(Ne.green("\u2713 Patched ~/.bashrc")),console.log(Ne.dim("Reload your shell: exec bash"));return}console.log(Ne.dim("Add this to ~/.bashrc:")),console.log(Ne.cyan(` ${s}`)),console.log(),console.log(Ne.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ne.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function ze(e){return e._name||e.name()||""}function Jt(e){return e.commands.filter(t=>{let o=ze(t);return!(!o||o==="help")})}function Mn(e){return e.options.filter(t=>!t.hidden)}function Bw(e){let t=[];return t.push("#compdef agentx"),t.push(""),mm(e,[],t),t.push("compdef _agentx_root_completion agentx"),t.push(""),t.join(`
644
- `)}function cm(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function mm(e,t,o){let n=Jt(e),i=Mn(e).map(Gw).filter(c=>!!c),r=cm(t);if(o.push(`${r}() {`),o.push(" local -a commands"),o.push(" local -a options"),o.push(" "),i.length===0&&n.length===0){o.push(" return 0"),o.push("}"),o.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(zw).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}o.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;o.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){o.push(""),o.push(" case $state in"),o.push(" (args)"),o.push(" case $line[1] in");for(let c of n){let l=cm([...t,ze(c)]);o.push(` (${ze(c)}) ${l} ;;`)}o.push(" esac"),o.push(" ;;"),o.push(" esac")}o.push("}"),o.push("");for(let c of n)mm(c,[...t,ze(c)],o)}function Jw(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Hw(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Gw(e){let t=e.short||void 0,o=e.long||void 0;if(!t&&!o)return null;let n=Jw(e.description||"");return t&&o?` "(${o} ${t})"{${o},${t}}"[${n}]"`:` "${o||t}[${n}]"`}function zw(e){let t=Hw(e.description()||"");return`'${ze(e)}[${t}]'`}function Yw(e){let t=Jt(e),o=[];o.push("# bash completion for agentx"),o.push("_agentx_complete() {"),o.push(" local cur prev words cword"),o.push(" COMPREPLY=()"),o.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),o.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),o.push(""),o.push(` local top="${t.map(ze).join(" ")}"`),o.push(""),o.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),o.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),o.push(" return 0"),o.push(" fi"),o.push(""),o.push(' local cmd="${COMP_WORDS[1]}"'),o.push(' local sub2="${COMP_WORDS[2]:-}"'),o.push(' case "$cmd" in');for(let n of t){let s=Jt(n).map(ze),i=lm(n);if(o.push(` ${ze(n)})`),s.length>0){o.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),o.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),o.push(" return 0"),o.push(" fi"),o.push(' case "$sub2" in');for(let r of Jt(n)){let a=lm(r);o.push(` ${ze(r)})`),o.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),o.push(" return 0"),o.push(" ;;")}o.push(" esac")}else o.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);o.push(" ;;")}return o.push(" esac"),o.push("}"),o.push(""),o.push("complete -F _agentx_complete agentx"),o.push(""),o.join(`
645
- `)}function lm(e){let t=[];for(let o of Mn(e))o.long&&t.push(o.long),o.short&&t.push(o.short);return t.join(" ")}function Vw(e){let t=[];t.push("# fish completion for agentx"),t.push(""),t.push("complete -c agentx -f"),t.push(""),t.push("# top-level commands");for(let o of Jt(e)){let n=_r(o.description()||"");t.push(`complete -c agentx -n "__fish_use_subcommand" -a "${ze(o)}" -d "${n}"`)}t.push("");for(let o of Mn(e)){let n=Nr(o,["__fish_use_subcommand"]);n&&t.push(n)}t.push("");for(let o of Jt(e)){let n=ze(o);t.push(`# ${n}`);for(let s of Mn(o)){let i=Nr(s,[`__fish_seen_subcommand_from ${n}`]);i&&t.push(i)}for(let s of Jt(o)){let i=_r(s.description()||"");t.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Jt(o).map(ze).join(" ")}" -a "${ze(s)}" -d "${i}"`);for(let r of Mn(s)){let a=Nr(r,[`__fish_seen_subcommand_from ${ze(s)}`]);a&&t.push(a)}}t.push("")}return t.join(`
646
- `)}function _r(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Nr(e,t){let o=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!o&&!n)return null;let s=_r(e.description||""),r=["complete -c agentx",t.map(a=>`-n "${a}"`).join(" ")];return o&&r.push(`-s ${o}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}import{Command as Xw}from"commander";import en from"chalk";import{readFile as Qw}from"node:fs/promises";var Zo="anis-marrouchi/agentx",Dr=`https://raw.githubusercontent.com/${Zo}/main/contrib/models.json`,Qs=`https://github.com/${Zo}/issues/new/choose`,um=`https://github.com/${Zo}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,pm=8e3,Xs={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 Pr(e,t){let o=e.trim().toLowerCase();return o?t.models.some(n=>{let s=n.id.toLowerCase();return o===s||o.startsWith(`${s}-`)||(n.aliases??[]).some(i=>i.toLowerCase()===o)}):!1}function Mr(e,t){return[`The model "${e}" is not on the recommended list for drafting AgentX issues.`,`The list (${t.models.map(o=>o.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: ${Qs}`].join(`
647
- `)}function Kw(e){return`---
648
- _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function fm(e,t){let o=Xs[e.category];if(!o)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(Xs).join(", ")}`);let n=new Set(o.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=o.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(o.titlePrefix.toLowerCase())||(r=o.titlePrefix+r);let a=new URLSearchParams({template:o.template,title:r});for(let l of o.fields){let g=e.fields[l.id]?.trim()??"";l.id===o.footerField&&(g=`${g}
649
-
650
- ${Kw({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${Zo}/issues/new?${a.toString()}`;if(c.length>pm)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${pm}). Shorten it, or paste it into the web form.`);return c}async function hm(e,t=fetch){let o=`repo:${Zo} is:issue is:open ${e}`,n=await t(`https://api.github.com/search/issues?per_page=10&q=${encodeURIComponent(o)}`,{headers:{accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`GitHub search failed (HTTP ${n.status}). Search by hand: https://github.com/${Zo}/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 Lr(e,t=fetch){let o;if(/^https?:\/\//.test(e)){let s=await t(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Could not read the model list (HTTP ${s.status}) from ${e}`);o=await s.text()}else{let{readFile:s}=await import("node:fs/promises");o=await s(e,"utf8")}let n=JSON.parse(o);if(!Array.isArray(n.models))throw new Error(`The model list at ${e} has no "models" array`);return n}var Ln=new Xw().name("contribute").description("help you file a clear AgentX issue \u2014 check the model, find duplicates, build a pre-filled form link").action(()=>{console.log(),console.log(en.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${Qs}`),console.log(" 2. Let your agent help: install the skill with"),console.log(en.cyan(" agentx skill install anis-marrouchi/agentx/agentx-contribute")),console.log(" then ask your agent to help you file an AgentX issue."),console.log(),console.log(` Before posting, please \u{1F44D} the open requests you care about: ${um}`),console.log(` Categories: ${Object.keys(Xs).join(", ")}`),console.log()});Ln.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",Dr).action(async(e,t)=>{try{let o=await Lr(t.models);if(Pr(e,o)){console.log(en.green(` "${e}" is on the recommended list.`));return}console.log(Mr(e,o)),process.exitCode=1}catch(o){console.error(en.red(` ${o.message}`)),console.error(` You can always write the issue yourself: ${Qs}`),process.exitCode=1}});Ln.command("search <words...>").description("list open issues that match, most-voted first \u2014 check for duplicates before drafting").action(async e=>{try{let t=await hm(e.join(" "));if(!t.length){console.log(" No open issue matches. It looks new.");return}for(let o of t)console.log(` #${o.number} \u{1F44D} ${o.votes} ${o.title}
651
- ${o.url}`)}catch(t){console.error(en.red(` ${t.message}`)),process.exitCode=1}});Ln.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",Dr).action(async(e,t)=>{try{let o=await Lr(t.models);if(!Pr(t.model,o)){console.log(Mr(t.model,o)),process.exitCode=1;return}let n=e==="-"?await Zw():await Qw(e,"utf8"),s=JSON.parse(n),{version:i}=await Jn(),r=fm({...s,fields:s.fields??{}},{model:t.model,version:i??"unknown"});console.log(r)}catch(o){console.error(en.red(` ${o.message}`)),process.exitCode=1}});async function Zw(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function uj(){let e=await Jn(),t=new eb().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");t.hook("preAction",(o,n)=>{let s=el(n);tl(s)&&Zc("cli",s)});for(let o of[Ol,Al,Fo,xo,Ao,Ze,Kc,Vt,ms,bt,Lt,Mt,gs,qg,_t,Vl,sd,kn,fd,bd,vd,xd,Ud,Jd,Hd,Do,Tn,Gg,un,Ot,gm,Ln])t.addCommand(o);for(let o of ym)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=ym.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,tb(o,74," "),""].join(`
652
- `)}),t}var ym=[ee,Wo,Wt,at,hn,Po,Ge,kt,Ft,so,Go,zo,Nt,Be,Io,Cs,Lg,Fg,yt,Kt,rl,Xt,Pn,_i,qt,jo,Di,Bs,ut,Bt,tm,nm,Hg];function tb(e,t,o){let n=[],s="";for(let i of e)s&&s.length+i.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+i;return s&&n.push(o+s),n.join(`
653
- `)}export{uj as a};
654
- //# sourceMappingURL=chunk-335JCO5R.js.map
643
+ `),console.log(Re.green("\u2713 Patched ~/.bashrc")),console.log(Re.dim("Reload your shell: exec bash"));return}console.log(Re.dim("Add this to ~/.bashrc:")),console.log(Re.cyan(` ${s}`)),console.log(),console.log(Re.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Re.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ye(e){return e._name||e.name()||""}function Ht(e){return e.commands.filter(t=>{let o=Ye(t);return!(!o||o==="help")})}function Un(e){return e.options.filter(t=>!t.hidden)}function Xw(e){let t=[];return t.push("#compdef agentx"),t.push(""),bm(e,[],t),t.push("compdef _agentx_root_completion agentx"),t.push(""),t.join(`
644
+ `)}function fm(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function bm(e,t,o){let n=Ht(e),i=Un(e).map(eb).filter(c=>!!c),r=fm(t);if(o.push(`${r}() {`),o.push(" local -a commands"),o.push(" local -a options"),o.push(" "),i.length===0&&n.length===0){o.push(" return 0"),o.push("}"),o.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(tb).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}o.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;o.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){o.push(""),o.push(" case $state in"),o.push(" (args)"),o.push(" case $line[1] in");for(let c of n){let l=fm([...t,Ye(c)]);o.push(` (${Ye(c)}) ${l} ;;`)}o.push(" esac"),o.push(" ;;"),o.push(" esac")}o.push("}"),o.push("");for(let c of n)bm(c,[...t,Ye(c)],o)}function Qw(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Zw(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function eb(e){let t=e.short||void 0,o=e.long||void 0;if(!t&&!o)return null;let n=Qw(e.description||"");return t&&o?` "(${o} ${t})"{${o},${t}}"[${n}]"`:` "${o||t}[${n}]"`}function tb(e){let t=Zw(e.description()||"");return`'${Ye(e)}[${t}]'`}function ob(e){let t=Ht(e),o=[];o.push("# bash completion for agentx"),o.push("_agentx_complete() {"),o.push(" local cur prev words cword"),o.push(" COMPREPLY=()"),o.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),o.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),o.push(""),o.push(` local top="${t.map(Ye).join(" ")}"`),o.push(""),o.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),o.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),o.push(" return 0"),o.push(" fi"),o.push(""),o.push(' local cmd="${COMP_WORDS[1]}"'),o.push(' local sub2="${COMP_WORDS[2]:-}"'),o.push(' case "$cmd" in');for(let n of t){let s=Ht(n).map(Ye),i=hm(n);if(o.push(` ${Ye(n)})`),s.length>0){o.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),o.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),o.push(" return 0"),o.push(" fi"),o.push(' case "$sub2" in');for(let r of Ht(n)){let a=hm(r);o.push(` ${Ye(r)})`),o.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),o.push(" return 0"),o.push(" ;;")}o.push(" esac")}else o.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);o.push(" ;;")}return o.push(" esac"),o.push("}"),o.push(""),o.push("complete -F _agentx_complete agentx"),o.push(""),o.join(`
645
+ `)}function hm(e){let t=[];for(let o of Un(e))o.long&&t.push(o.long),o.short&&t.push(o.short);return t.join(" ")}function nb(e){let t=[];t.push("# fish completion for agentx"),t.push(""),t.push("complete -c agentx -f"),t.push(""),t.push("# top-level commands");for(let o of Ht(e)){let n=Fr(o.description()||"");t.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ye(o)}" -d "${n}"`)}t.push("");for(let o of Un(e)){let n=Mr(o,["__fish_use_subcommand"]);n&&t.push(n)}t.push("");for(let o of Ht(e)){let n=Ye(o);t.push(`# ${n}`);for(let s of Un(o)){let i=Mr(s,[`__fish_seen_subcommand_from ${n}`]);i&&t.push(i)}for(let s of Ht(o)){let i=Fr(s.description()||"");t.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Ht(o).map(Ye).join(" ")}" -a "${Ye(s)}" -d "${i}"`);for(let r of Un(s)){let a=Mr(r,[`__fish_seen_subcommand_from ${Ye(s)}`]);a&&t.push(a)}}t.push("")}return t.join(`
646
+ `)}function Fr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Mr(e,t){let o=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!o&&!n)return null;let s=Fr(e.description||""),r=["complete -c agentx",t.map(a=>`-n "${a}"`).join(" ")];return o&&r.push(`-s ${o}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}import{Command as ib}from"commander";import on from"chalk";import{readFile as rb}from"node:fs/promises";var tn="anis-marrouchi/agentx",Ur=`https://raw.githubusercontent.com/${tn}/main/contrib/models.json`,oi=`https://github.com/${tn}/issues/new/choose`,km=`https://github.com/${tn}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,$m=8e3,ti={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 qr(e,t){let o=e.trim().toLowerCase();return o?t.models.some(n=>{let s=n.id.toLowerCase();return o===s||o.startsWith(`${s}-`)||(n.aliases??[]).some(i=>i.toLowerCase()===o)}):!1}function Wr(e,t){return[`The model "${e}" is not on the recommended list for drafting AgentX issues.`,`The list (${t.models.map(o=>o.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: ${oi}`].join(`
647
+ `)}function sb(e){return`---
648
+ _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function vm(e,t){let o=ti[e.category];if(!o)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(ti).join(", ")}`);let n=new Set(o.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=o.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(o.titlePrefix.toLowerCase())||(r=o.titlePrefix+r);let a=new URLSearchParams({template:o.template,title:r});for(let l of o.fields){let g=e.fields[l.id]?.trim()??"";l.id===o.footerField&&(g=`${g}
649
+
650
+ ${sb({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${tn}/issues/new?${a.toString()}`;if(c.length>$m)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${$m}). Shorten it, or paste it into the web form.`);return c}async function xm(e,t=fetch){let o=`repo:${tn} is:issue is:open ${e}`,n=await t(`https://api.github.com/search/issues?per_page=10&q=${encodeURIComponent(o)}`,{headers:{accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`GitHub search failed (HTTP ${n.status}). Search by hand: https://github.com/${tn}/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 Br(e,t=fetch){let o;if(/^https?:\/\//.test(e)){let s=await t(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Could not read the model list (HTTP ${s.status}) from ${e}`);o=await s.text()}else{let{readFile:s}=await import("node:fs/promises");o=await s(e,"utf8")}let n=JSON.parse(o);if(!Array.isArray(n.models))throw new Error(`The model list at ${e} has no "models" array`);return n}var qn=new ib().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(on.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${oi}`),console.log(" 2. Let your agent help: install the skill with"),console.log(on.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: ${km}`),console.log(` Categories: ${Object.keys(ti).join(", ")}`),console.log()});qn.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",Ur).action(async(e,t)=>{try{let o=await Br(t.models);if(qr(e,o)){console.log(on.green(` "${e}" is on the recommended list.`));return}console.log(Wr(e,o)),process.exitCode=1}catch(o){console.error(on.red(` ${o.message}`)),console.error(` You can always write the issue yourself: ${oi}`),process.exitCode=1}});qn.command("search <words...>").description("list open issues that match, most-voted first \u2014 check for duplicates before drafting").action(async e=>{try{let t=await xm(e.join(" "));if(!t.length){console.log(" No open issue matches. It looks new.");return}for(let o of t)console.log(` #${o.number} \u{1F44D} ${o.votes} ${o.title}
651
+ ${o.url}`)}catch(t){console.error(on.red(` ${t.message}`)),process.exitCode=1}});qn.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",Ur).action(async(e,t)=>{try{let o=await Br(t.models);if(!qr(t.model,o)){console.log(Wr(t.model,o)),process.exitCode=1;return}let n=e==="-"?await ab():await rb(e,"utf8"),s=JSON.parse(n),{version:i}=await Yn(),r=vm({...s,fields:s.fields??{}},{model:t.model,version:i??"unknown"});console.log(r)}catch(o){console.error(on.red(` ${o.message}`)),process.exitCode=1}});async function ab(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Ij(){let e=await Yn(),t=new cb().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");t.hook("preAction",(o,n)=>{let s=il(n);rl(s)&&sl("cli",s)});for(let o of[_l,Cl,qo,Eo,jo,et,tl,Kt,hs,$t,Ut,Ft,fs,Gg,Pt,ed,ld,xn,$d,Sd,Td,jd,Hd,Vd,Kd,Mo,On,Xg,hn,Ct,wm,qn])t.addCommand(o);for(let o of Sm)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Sm.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,lb(o,74," "),""].join(`
652
+ `)}),t}var Sm=[ee,Jo,Jt,ct,wn,Lo,ze,vt,qt,io,Yo,Vo,_t,Je,No,Ds,Bg,Jg,wt,Xt,gl,Qt,Fn,Li,Bt,Io,Fi,zs,ft,xt,rm,cm,Kg];function lb(e,t,o){let n=[],s="";for(let i of e)s&&s.length+i.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+i;return s&&n.push(o+s),n.join(`
653
+ `)}export{Ij as a};
654
+ //# sourceMappingURL=chunk-22TKLH6A.js.map