agentix-cli 0.80.1 → 0.81.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 (148) hide show
  1. package/dist/{App-KVH5POXZ.js → App-HF6W6CV2.js} +2 -2
  2. package/dist/{App-KVH5POXZ.js.map → App-HF6W6CV2.js.map} +1 -1
  3. package/dist/ChatApp-74VBWP7R.js +7 -0
  4. package/dist/{ChatApp-LD4TXJWP.js.map → ChatApp-74VBWP7R.js.map} +1 -1
  5. package/dist/{agent-FUMJM6OW.js → agent-BDEPUFBQ.js} +2 -2
  6. package/dist/{board-dashboard-OS5J3F73.js → board-dashboard-TWEF5XVE.js} +186 -169
  7. package/dist/board-dashboard-TWEF5XVE.js.map +1 -0
  8. package/dist/{chunk-R42S57G6.js → chunk-4KJ3PCAI.js} +2 -2
  9. package/dist/{chunk-PE55MMLK.js → chunk-5GXCOHDM.js} +2 -2
  10. package/dist/{chunk-PE55MMLK.js.map → chunk-5GXCOHDM.js.map} +1 -1
  11. package/dist/{chunk-BJPIRNP6.js → chunk-74FSHUB3.js} +2 -2
  12. package/dist/{chunk-H7253EHW.js → chunk-ATXE3EMV.js} +2 -2
  13. package/dist/{chunk-TEFMZY6B.js → chunk-BB3ESU74.js} +2 -2
  14. package/dist/{chunk-XESESMKN.js → chunk-BDM4VTBR.js} +39 -39
  15. package/dist/{chunk-XESESMKN.js.map → chunk-BDM4VTBR.js.map} +1 -1
  16. package/dist/chunk-BYD5B3P3.js +9 -0
  17. package/dist/{chunk-Z3IP66SL.js.map → chunk-BYD5B3P3.js.map} +1 -1
  18. package/dist/chunk-EFV7U5LD.js +152 -0
  19. package/dist/chunk-EFV7U5LD.js.map +1 -0
  20. package/dist/chunk-ES7Z64Z5.js +22 -0
  21. package/dist/chunk-ES7Z64Z5.js.map +1 -0
  22. package/dist/{chunk-WP6KLXTP.js → chunk-GLQLCBJS.js} +4 -4
  23. package/dist/chunk-GLQLCBJS.js.map +1 -0
  24. package/dist/{chunk-UB63NQQL.js → chunk-GUAJNZIX.js} +2 -2
  25. package/dist/{chunk-UXSYVMPK.js → chunk-HUQRPEDP.js} +2 -2
  26. package/dist/{chunk-BEHC3X42.js → chunk-HYE2UUQ4.js} +242 -211
  27. package/dist/chunk-HYE2UUQ4.js.map +1 -0
  28. package/dist/chunk-JG3O5GL6.js +5 -0
  29. package/dist/{chunk-MOQNLS5Z.js.map → chunk-JG3O5GL6.js.map} +1 -1
  30. package/dist/chunk-JXF54PT7.js +2 -0
  31. package/dist/chunk-JXF54PT7.js.map +1 -0
  32. package/dist/chunk-LTHQXWZN.js +51 -0
  33. package/dist/chunk-LTHQXWZN.js.map +1 -0
  34. package/dist/{chunk-ZR3NZLJL.js → chunk-LUL4ILAQ.js} +2 -2
  35. package/dist/{chunk-N6EWZGIX.js → chunk-PN6XHTG5.js} +6 -6
  36. package/dist/{chunk-N6EWZGIX.js.map → chunk-PN6XHTG5.js.map} +1 -1
  37. package/dist/{chunk-7IGSJGXI.js → chunk-TW4L6RP2.js} +2 -2
  38. package/dist/chunk-UCKKAWLZ.js +2 -0
  39. package/dist/chunk-UCKKAWLZ.js.map +1 -0
  40. package/dist/{chunk-3UN6CXRL.js → chunk-VVW4JYV6.js} +24 -24
  41. package/dist/chunk-VVW4JYV6.js.map +1 -0
  42. package/dist/{chunk-BVZFYBBP.js → chunk-WWU2D65N.js} +2 -2
  43. package/dist/chunk-XF65CDNS.js +5 -0
  44. package/dist/{chunk-UR3ZIDMA.js.map → chunk-XF65CDNS.js.map} +1 -1
  45. package/dist/{chunk-YCI3KUYF.js → chunk-XQ7MVPWP.js} +7 -7
  46. package/dist/chunk-XQ7MVPWP.js.map +1 -0
  47. package/dist/{chunk-MYRSNJJ4.js → chunk-ZDDJNKU5.js} +2 -2
  48. package/dist/{chunk-Z3XUGXPD.js → chunk-ZUAV3PTL.js} +2 -2
  49. package/dist/cli.js +1 -1
  50. package/dist/cli.js.map +1 -1
  51. package/dist/client-JDY2FZUF.js +2 -0
  52. package/dist/config-JCETBKWT.js +2 -0
  53. package/dist/config-mutator-YQWTY47O.js +2 -0
  54. package/dist/doctor-6EWW7NC2.js +2 -0
  55. package/dist/{facts-U7BUYRXN.js → facts-5T5GRUTG.js} +6 -6
  56. package/dist/{facts-U7BUYRXN.js.map → facts-5T5GRUTG.js.map} +1 -1
  57. package/dist/{failure-candidates-RIXA3Y6D.js → failure-candidates-PBPF45GN.js} +2 -2
  58. package/dist/index.d.ts +619 -499
  59. package/dist/index.js +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/{chunk-AF46YOLU.js → program-FUYHN2F7.js} +194 -184
  62. package/dist/program-FUYHN2F7.js.map +1 -0
  63. package/dist/promote-ZZWMGVO2.js +2 -0
  64. package/dist/query-OQBB7EFS.js +2 -0
  65. package/dist/registry-PLSOZ3CL.js +2 -0
  66. package/dist/request-planner-HX44G2SX.js +2 -0
  67. package/dist/{request-planner-H74KHFGJ.js.map → request-planner-HX44G2SX.js.map} +1 -1
  68. package/dist/review-candidates-FBDLPU6H.js +4 -0
  69. package/dist/{review-candidates-IPJWEXR2.js.map → review-candidates-FBDLPU6H.js.map} +1 -1
  70. package/dist/routing-3SZHWHUA.js +2 -0
  71. package/dist/schedule-tool-5FULSHWJ.js +2 -0
  72. package/dist/scheduler-ITOKSMYT.js +2 -0
  73. package/dist/seat-2HJG3UNW.js +2 -0
  74. package/dist/select-UKAOL7QB.js +2 -0
  75. package/dist/{select-BUWOD47K.js.map → select-UKAOL7QB.js.map} +1 -1
  76. package/dist/set-enabled-ADFSNG5A.js +2 -0
  77. package/dist/{set-enabled-XWSFTICB.js.map → set-enabled-ADFSNG5A.js.map} +1 -1
  78. package/dist/signal-exit-WL7G3EEZ.js +2 -0
  79. package/dist/signal-exit-WL7G3EEZ.js.map +1 -0
  80. package/dist/{surface-usage-HVVP22SA.js → surface-usage-O5L4KLGS.js} +2 -2
  81. package/dist/{tool-VOA4HSVP.js → tool-MSXWU44P.js} +2 -2
  82. package/dist/{tool-VOA4HSVP.js.map → tool-MSXWU44P.js.map} +1 -1
  83. package/dist/{tool-GUINJ2BQ.js → tool-X7YEIJVZ.js} +2 -2
  84. package/dist/{tool-GUINJ2BQ.js.map → tool-X7YEIJVZ.js.map} +1 -1
  85. package/dist/wiki-QUVWB4IN.js +2 -0
  86. package/package.json +1 -1
  87. package/dist/ChatApp-LD4TXJWP.js +0 -7
  88. package/dist/board-dashboard-OS5J3F73.js.map +0 -1
  89. package/dist/chunk-3UN6CXRL.js.map +0 -1
  90. package/dist/chunk-42Y3BXXS.js +0 -15
  91. package/dist/chunk-42Y3BXXS.js.map +0 -1
  92. package/dist/chunk-6JJ3GODZ.js +0 -57
  93. package/dist/chunk-6JJ3GODZ.js.map +0 -1
  94. package/dist/chunk-AF46YOLU.js.map +0 -1
  95. package/dist/chunk-API4IZZG.js +0 -2
  96. package/dist/chunk-API4IZZG.js.map +0 -1
  97. package/dist/chunk-BEHC3X42.js.map +0 -1
  98. package/dist/chunk-MOQNLS5Z.js +0 -5
  99. package/dist/chunk-NOAAK2XI.js +0 -152
  100. package/dist/chunk-NOAAK2XI.js.map +0 -1
  101. package/dist/chunk-UR3ZIDMA.js +0 -5
  102. package/dist/chunk-WP6KLXTP.js.map +0 -1
  103. package/dist/chunk-YCI3KUYF.js.map +0 -1
  104. package/dist/chunk-Z3IP66SL.js +0 -9
  105. package/dist/client-TJ5YZOEE.js +0 -2
  106. package/dist/config-4WZ7Y34V.js +0 -2
  107. package/dist/config-mutator-5Z7EEB5N.js +0 -2
  108. package/dist/doctor-7K3NRBNN.js +0 -2
  109. package/dist/program-KMQNX6YK.js +0 -2
  110. package/dist/promote-NDC3X54P.js +0 -2
  111. package/dist/query-F7BD3JPE.js +0 -2
  112. package/dist/registry-5NBHBVY3.js +0 -2
  113. package/dist/request-planner-H74KHFGJ.js +0 -2
  114. package/dist/review-candidates-IPJWEXR2.js +0 -4
  115. package/dist/routing-3RSG7SKW.js +0 -2
  116. package/dist/schedule-tool-7NYAK43U.js +0 -2
  117. package/dist/scheduler-24O7PADJ.js +0 -2
  118. package/dist/seat-TOM2WHQR.js +0 -2
  119. package/dist/select-BUWOD47K.js +0 -2
  120. package/dist/set-enabled-XWSFTICB.js +0 -2
  121. package/dist/wiki-VFME4T2H.js +0 -2
  122. package/dist/wiki-VFME4T2H.js.map +0 -1
  123. /package/dist/{agent-FUMJM6OW.js.map → agent-BDEPUFBQ.js.map} +0 -0
  124. /package/dist/{chunk-R42S57G6.js.map → chunk-4KJ3PCAI.js.map} +0 -0
  125. /package/dist/{chunk-BJPIRNP6.js.map → chunk-74FSHUB3.js.map} +0 -0
  126. /package/dist/{chunk-H7253EHW.js.map → chunk-ATXE3EMV.js.map} +0 -0
  127. /package/dist/{chunk-TEFMZY6B.js.map → chunk-BB3ESU74.js.map} +0 -0
  128. /package/dist/{chunk-UB63NQQL.js.map → chunk-GUAJNZIX.js.map} +0 -0
  129. /package/dist/{chunk-UXSYVMPK.js.map → chunk-HUQRPEDP.js.map} +0 -0
  130. /package/dist/{chunk-ZR3NZLJL.js.map → chunk-LUL4ILAQ.js.map} +0 -0
  131. /package/dist/{chunk-7IGSJGXI.js.map → chunk-TW4L6RP2.js.map} +0 -0
  132. /package/dist/{chunk-BVZFYBBP.js.map → chunk-WWU2D65N.js.map} +0 -0
  133. /package/dist/{chunk-MYRSNJJ4.js.map → chunk-ZDDJNKU5.js.map} +0 -0
  134. /package/dist/{chunk-Z3XUGXPD.js.map → chunk-ZUAV3PTL.js.map} +0 -0
  135. /package/dist/{client-TJ5YZOEE.js.map → client-JDY2FZUF.js.map} +0 -0
  136. /package/dist/{config-4WZ7Y34V.js.map → config-JCETBKWT.js.map} +0 -0
  137. /package/dist/{config-mutator-5Z7EEB5N.js.map → config-mutator-YQWTY47O.js.map} +0 -0
  138. /package/dist/{doctor-7K3NRBNN.js.map → doctor-6EWW7NC2.js.map} +0 -0
  139. /package/dist/{failure-candidates-RIXA3Y6D.js.map → failure-candidates-PBPF45GN.js.map} +0 -0
  140. /package/dist/{program-KMQNX6YK.js.map → promote-ZZWMGVO2.js.map} +0 -0
  141. /package/dist/{promote-NDC3X54P.js.map → query-OQBB7EFS.js.map} +0 -0
  142. /package/dist/{query-F7BD3JPE.js.map → registry-PLSOZ3CL.js.map} +0 -0
  143. /package/dist/{registry-5NBHBVY3.js.map → routing-3SZHWHUA.js.map} +0 -0
  144. /package/dist/{routing-3RSG7SKW.js.map → schedule-tool-5FULSHWJ.js.map} +0 -0
  145. /package/dist/{schedule-tool-7NYAK43U.js.map → scheduler-ITOKSMYT.js.map} +0 -0
  146. /package/dist/{scheduler-24O7PADJ.js.map → seat-2HJG3UNW.js.map} +0 -0
  147. /package/dist/{seat-TOM2WHQR.js.map → surface-usage-O5L4KLGS.js.map} +0 -0
  148. /package/dist/{surface-usage-HVVP22SA.js.map → wiki-QUVWB4IN.js.map} +0 -0
@@ -1,42 +1,42 @@
1
- import{a as xl,b as hs,g as Sl}from"./chunk-MOQNLS5Z.js";import{a as ul,c as fl}from"./chunk-YCI3KUYF.js";import{a as Ze,b as dl,f as gl,g as ml,h as pl,i as It,j as hl,k as yl,l as Di,m as kl,o as vl}from"./chunk-3UN6CXRL.js";import{a as wl,c as $l,d as bl}from"./chunk-Z3IP66SL.js";import{a as bi,b as Ua}from"./chunk-RKPAVWXF.js";import{$ as us,A as Mc,B as Lc,C as qc,D as Uc,E as Fc,F as Vc,G as Tt,H as ms,I as Ci,J as Yc,K as Kc,L as Xc,M as Qc,N as Zc,O as el,P as Ot,Q as Ct,R as ol,S as tl,T as De,U as ps,V as kn,W as ji,X as nl,Y as rl,Z as Ri,_ as cl,a as Va,aa as jt,b as Ya,ba as fs,ca as _i,da as ll,h as ns,i as Za,j as wn,k as ss,l as tc,m as nc,n as fc,o as hc,p as cs,q as vi,r as kc,s as Oc,t as Ic,u as Nc,v as Rc,w as _c,x as Dc,y as Si,z as Pc}from"./chunk-BEHC3X42.js";import{Aa as gs,Da as Gc,Ea as zc,Fa as Oi,K as xi,L as Ec,N as Ac,O as ls,P as Tc,Va as sl,Wa as Ii,Xa as il,Ya as Ni,ca as $n,fa as Ei,ga as ds,ha as Wc,kb as uo,mb as al,oa as _o,p as Ro,pa as Bc,qa as Ai,sa as Ti,t as vc,ua as Jc,va as Hc,wa as bn,x as xc,y as Sc}from"./chunk-XESESMKN.js";import{a as Ka,d as Xa,e as Qa}from"./chunk-Z3XUGXPD.js";import{a as is,b as rs,c as sc,d as ic,e as rc,g as ac,h as cc,j as lc,k as dc,l as gc,m as mc,p as as,s as pc,t as uc}from"./chunk-S2GAEH2F.js";import{a as ec,p as oc}from"./chunk-BVZFYBBP.js";import{a as yc,b as wc,c as $c,d as bc}from"./chunk-2D3RYIDU.js";import{a as Cc,b as jc}from"./chunk-EKJG63EJ.js";import{C as No,I as Da,V as Ma,g as $a,p as ba,w as yi,x as Sa}from"./chunk-NOAAK2XI.js";import{b as kt,g as xt,h as os,i as ts,j as St,k as Ea,l as Qo,m as hn,w as Pa}from"./chunk-6JJ3GODZ.js";import{e as Ia,f as $i,k as Na}from"./chunk-WP6KLXTP.js";import{a as bt}from"./chunk-N6EWZGIX.js";import{b as vt}from"./chunk-DP7RTNDM.js";import{b as yn}from"./chunk-OVN5LVJY.js";import{a as La,b as qa}from"./chunk-SHEUCITK.js";import{a as ki,e as Fa,f as Wa,h as Ba,i as Ja,k as Ha,l as Ga,m as za}from"./chunk-TEFMZY6B.js";import{c as Ta}from"./chunk-SZDACK6O.js";import{f as Oa,g as Ca,h as wi}from"./chunk-76Z4VHDX.js";import{a as va,k as ja}from"./chunk-R42S57G6.js";import{a as Ra,b as pe,c as je,d as At,e as _a}from"./chunk-UR3ZIDMA.js";import{a as fi}from"./chunk-H7253EHW.js";import{a as hi,b as ka}from"./chunk-GQ76J72O.js";import{j as xa}from"./chunk-X5C5W3E4.js";import{a as Et}from"./chunk-GV7S5BAX.js";import{e as Aa}from"./chunk-GSX4NK2N.js";import{h as wa}from"./chunk-DWADWDMU.js";import{g as Io,i as es}from"./chunk-UB63NQQL.js";import{b as $t,d as ya}from"./chunk-2GIDVZ4H.js";import{a as ui,b as oa,c as Ym,d as Qn,e as ta,f as ga,g as Qm,h as ma,i as Zm,m as wt,n as ua,o as fa,s as ha,v as po,w as fn}from"./chunk-PE55MMLK.js";import{a as ko,b as yt,e as ca,f as un}from"./chunk-72SZI2UW.js";import{a as pa,b as ep}from"./chunk-FX3D7YON.js";import{a as bo,b as Vm}from"./chunk-7I7IEX4S.js";import{D as ra,E as aa,F as j,G as Zn,I as ne,m as na,n as sa,p as ia,q as Km}from"./chunk-42Y3BXXS.js";import{g as la,k as da,l as Xm}from"./chunk-RGDKHYY2.js";import{Command as op}from"commander";var El=new op().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 Ya({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 tp}from"commander";import{execFileSync as oo}from"node:child_process";import{cpSync as Al,existsSync as Li,mkdirSync as Pi,mkdtempSync as np,readdirSync as sp,rmSync as Tl,writeFileSync as Ol}from"node:fs";import{dirname as Cl,join as Me}from"node:path";import{homedir as ys,release as ip,tmpdir as rp}from"node:os";import{setTimeout as ap}from"node:timers/promises";function ws(){let e=sc(process.platform,process.arch,ip());if(e)throw new Error(e)}function $s(){let e=Me(ys(),"Library/LaunchAgents"),o=[];try{o=sp(e).filter(ac)}catch{}let t=o.flatMap(n=>{let s=Me(e,n);try{return[{file:s,plist:oo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return cc(e,t)}function vn(e){return`gui/${process.getuid()}/${e.label}`}async function Mi(e){try{oo("launchctl",["bootout",vn(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{oo("launchctl",["print",vn(e)],{stdio:"pipe"})}catch{return}await ap(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function jl(e){if(!Li(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{oo("launchctl",["print",vn(e)],{stdio:"pipe"})}catch{o=!1}o||oo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),oo("launchctl",["kickstart",vn(e)],{stdio:"pipe"})}function cp(){let e=mc();if(e&&Li(Me(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 Nt=new tp("desktop").description("install and control the macOS desktop assistant");Nt.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=>{ws();let o=j(),t=ic(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=cp(),r=Me(ys(),"Applications"),{keep:a,remove:c}=$s();if(console.log(`Desktop assistant \u2192 ${Me(r,is)}
2
- Computer-use helper \u2192 ${Me(r,rs)}
1
+ import{a as Dl,b as ks,g as Pl}from"./chunk-JG3O5GL6.js";import{a as El,c as Al}from"./chunk-XQ7MVPWP.js";import{a as eo,b as kl,f as vl,g as xl,h as Sl,i as Rt,j as Tl,k as Ol,l as Ji,m as Cl,p as Hi,q as Rl,s as _l}from"./chunk-VVW4JYV6.js";import{a as jl,c as Il,d as Nl}from"./chunk-BYD5B3P3.js";import"./chunk-O5U5NVLR.js";import{a as Ci,b as Xa}from"./chunk-RKPAVWXF.js";import{$ as $s,A as Yc,B as Vc,C as Kc,D as Xc,E as Qc,F as il,G as Ct,H as ys,I as Li,J as rl,K as al,L as cl,M as ll,N as dl,O as gl,P as jt,Q as It,R as ml,S as pl,T as De,U as ws,V as Sn,W as qi,X as ul,Y as yl,Z as Wi,_ as $l,a as ic,aa as Nt,b as rc,ba as bs,ca as Bi,da as bl,h as cs,i as dc,j as kn,k as ls,l as pc,m as uc,n as Ac,o as Tc,p as ps,q as Ii,r as Nc,s as qc,t as Wc,u as Bc,v as Jc,w as Hc,x as Gc,y as Ri,z as zc}from"./chunk-HYE2UUQ4.js";import{Aa as hs,Da as nl,Ea as sl,Fa as Mi,K as Ni,L as Pc,N as Mc,O as us,P as Lc,Va as fl,Wa as Ui,Xa as hl,Ya as Fi,ca as vn,fa as _i,ga as fs,ha as Zc,kb as fo,mb as wl,oa as Po,p as Do,pa as el,qa as Di,sa as Pi,t as Rc,ua as ol,va as tl,wa as xn,x as _c,y as Dc}from"./chunk-BDM4VTBR.js";import"./chunk-GTJIKXDB.js";import{a as ac,d as cc,e as lc}from"./chunk-ZUAV3PTL.js";import{a as ds,b as gs,c as fc,d as hc,e as yc,g as wc,h as $c,j as bc,k as kc,l as vc,m as xc,p as ms,s as Sc,t as Ec}from"./chunk-S2GAEH2F.js";import"./chunk-CL53UVOF.js";import"./chunk-ZVP6GB4G.js";import{a as gc,p as mc}from"./chunk-WWU2D65N.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Oc,b as Cc,c as jc,d as Ic}from"./chunk-2D3RYIDU.js";import{a as Uc,b as Fc}from"./chunk-EKJG63EJ.js";import{C as _o,I as za,T as Ya,g as Ia,p as Na,w as Ai,x as Pa}from"./chunk-EFV7U5LD.js";import{b as xt,g as Et,h as rs,i as as,j as At,k as Ma,l as ot,m as $n}from"./chunk-ES7Z64Z5.js";import{e as Ba,f as Oi,k as Ja}from"./chunk-GLQLCBJS.js";import{b as St}from"./chunk-DP7RTNDM.js";import"./chunk-ZDDJNKU5.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as bn}from"./chunk-OVN5LVJY.js";import{a as Va,b as Ka}from"./chunk-SHEUCITK.js";import{a as ji,e as Qa,f as Za,h as ec,i as oc,k as tc,l as nc,m as sc}from"./chunk-BB3ESU74.js";import{c as qa}from"./chunk-SZDACK6O.js";import{f as Ua,g as Fa,h as Ti}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as _a,k as Wa}from"./chunk-4KJ3PCAI.js";import{a as Ha,b as se,c as je,d as Ot,e as Ga}from"./chunk-XF65CDNS.js";import"./chunk-VWTBHLMX.js";import{a as Si}from"./chunk-ATXE3EMV.js";import"./chunk-LUL4ILAQ.js";import"./chunk-KA2UIZXG.js";import{a as Ei,b as Ra}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Da}from"./chunk-X5C5W3E4.js";import{a as Tt}from"./chunk-GV7S5BAX.js";import{e as La}from"./chunk-GSX4NK2N.js";import"./chunk-74FSHUB3.js";import"./chunk-MYVHVJWZ.js";import{h as ja}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-HUQRPEDP.js";import{g as Ro,i as is}from"./chunk-GUAJNZIX.js";import"./chunk-WPNRDEHW.js";import{b as vt,d as Ca}from"./chunk-2GIDVZ4H.js";import{a as bi,b as ga,c as pp,d as ts,e as ma,f as xa,g as yp,h as Sa,i as wp,m as kt,n as Aa,o as Ta,s as Oa,v as uo,w as wn}from"./chunk-5GXCOHDM.js";import{a as vo,b as bt,e as ba,f as yn}from"./chunk-72SZI2UW.js";import{a as Ea,b as $p}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as ko,b as mp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as $a,A as ya,N as vi,O as xi,Q as fp,_ as wa,aa as O,ba as ss,da as ee,m as pa,n as ua,p as fa,q as up,x as ki,z as ha}from"./chunk-LTHQXWZN.js";import"./chunk-UCKKAWLZ.js";import{a as No,i as ns}from"./chunk-PN6XHTG5.js";import{g as ka,k as va,l as hp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as bp}from"commander";var Ml=new bp().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 rc({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()});ee();import{Command as kp}from"commander";import{execFileSync as to}from"node:child_process";import{cpSync as Ll,existsSync as Yi,mkdirSync as Gi,mkdtempSync as vp,readdirSync as xp,rmSync as ql,writeFileSync as Ul}from"node:fs";import{dirname as Fl,join as Le}from"node:path";import{homedir as vs,release as Sp,tmpdir as Ep}from"node:os";import{setTimeout as Ap}from"node:timers/promises";function xs(){let e=fc(process.platform,process.arch,Sp());if(e)throw new Error(e)}function Ss(){let e=Le(vs(),"Library/LaunchAgents"),o=[];try{o=xp(e).filter(wc)}catch{}let t=o.flatMap(n=>{let s=Le(e,n);try{return[{file:s,plist:to("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return $c(e,t)}function En(e){return`gui/${process.getuid()}/${e.label}`}async function zi(e){try{to("launchctl",["bootout",En(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{to("launchctl",["print",En(e)],{stdio:"pipe"})}catch{return}await Ap(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Wl(e){if(!Yi(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{to("launchctl",["print",En(e)],{stdio:"pipe"})}catch{o=!1}o||to("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),to("launchctl",["kickstart",En(e)],{stdio:"pipe"})}function Tp(){let e=xc();if(e&&Yi(Le(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var _t=new kp("desktop").description("install and control the macOS desktop assistant");_t.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=>{xs();let o=O(),t=hc(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Tp(),r=Le(vs(),"Applications"),{keep:a,remove:c}=Ss();if(console.log(`Desktop assistant \u2192 ${Le(r,ds)}
2
+ Computer-use helper \u2192 ${Le(r,gs)}
3
3
  Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
5
5
  Starts at login \u2192 ${a.file}${c.map(d=>`
6
- Removes duplicate login item \u2192 ${d.file}`).join("")}`),e.dryRun)return;try{oo("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=oo("/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=np(Me(rp(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Al(Me(i,"apps",p),Me(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let h=p==="mac-helper"?dc(o.notifications.local.icon):[];oo("/bin/bash",[Me(g,p,"build.sh"),...h],{stdio:"inherit"})}let d=Me(ys(),"Library/Logs/agentx-desktop.err.log"),u=lc({label:a.label,executable:Me(r,is,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:gc(ys()),cli:Me(i,"dist/cli.js"),node:process.execPath,log:d,path:rc(l,process.env.AGENTX_VOICE_PATH)}),f=Me(g,"desktop.plist");Ol(f,u,{mode:384}),oo("plutil",["-lint",f],{stdio:"pipe"}),await Mi(a);for(let p of c)p.label!==a.label&&await Mi(p),Tl(p.file,{force:!0});Pi(r,{recursive:!0});for(let[p,h,w]of[["mac-voice","AgentX Voice.app",is],["mac-helper",rs,rs]])Al(Me(g,p,"build",h),Me(r,w),{recursive:!0});Pi(Cl(a.file),{recursive:!0}),Pi(Cl(d),{recursive:!0}),Ol(a.file,u,{mode:384}),jl(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{to("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=to("/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=vp(Le(Ep(),"agentx-desktop-"));try{for(let p of["mac-helper","mac-voice"]){Ll(Le(i,"apps",p),Le(g,p),{recursive:!0,filter:w=>!w.split("/").includes("build")});let h=p==="mac-helper"?kc(o.notifications.local.icon):[];to("/bin/bash",[Le(g,p,"build.sh"),...h],{stdio:"inherit"})}let d=Le(vs(),"Library/Logs/agentx-desktop.err.log"),u=bc({label:a.label,executable:Le(r,ds,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:n,url:s,helper:vc(vs()),cli:Le(i,"dist/cli.js"),node:process.execPath,log:d,path:yc(l,process.env.AGENTX_VOICE_PATH)}),f=Le(g,"desktop.plist");Ul(f,u,{mode:384}),to("plutil",["-lint",f],{stdio:"pipe"}),await zi(a);for(let p of c)p.label!==a.label&&await zi(p),ql(p.file,{force:!0});Gi(r,{recursive:!0});for(let[p,h,w]of[["mac-voice","AgentX Voice.app",ds],["mac-helper",gs,gs]])Ll(Le(g,p,"build",h),Le(r,w),{recursive:!0});Gi(Fl(a.file),{recursive:!0}),Gi(Fl(d),{recursive:!0}),Ul(a.file,u,{mode:384}),Wl(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{Tl(g,{recursive:!0,force:!0})}});Nt.command("start").description("start the installed desktop assistant").action(()=>{ws(),jl($s().keep),console.log("Desktop assistant started.")});Nt.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{ws(),await Mi($s().keep),console.log("Desktop assistant stopped.")});Nt.command("status").description("show the desktop login service status").action(()=>{ws();let{keep:e}=$s();try{console.log(oo("launchctl",["print",vn(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Li(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as up}from"commander";import{open as fp}from"fs/promises";import{existsSync as vs,mkdirSync as lp,readFileSync as xs,writeFileSync as Il}from"fs";import{homedir as dp}from"os";import{dirname as gp,resolve as qi}from"path";var Ui="/attach/",Nl="/guard/check";function Rl(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function bs(e,o,t){let n={hooks:[{type:"command",command:Rl(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function mp(e){return{SessionStart:[bs("/attach/session-start",e,"")],UserPromptSubmit:[bs("/attach/prompt",e)],Stop:[bs("/attach/stop",e)],SessionEnd:[bs("/attach/session-end",e)]}}function pp(e){let o=Rl("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function ks(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function xn(){return qi(dp(),".claude/settings.json")}function Zo(e=process.cwd()){for(let o of[e,qi(e,"..")]){let t=qi(o,"agentx.json");if(vs(t))try{let n=JSON.parse(xs(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function _l(e,o={}){let t=o.path??xn(),n=o.withGuard!==!1,s={};if(vs(t))try{s=JSON.parse(xs(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,d]of Object.entries(mp(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!ks(f,Ui)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!ks(d,Nl)):[];r.PreToolUse=[...g,...pp(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(lp(gp(t),{recursive:!0}),Il(t,`${JSON.stringify(s,null,2)}
9
- `)),{path:t,changed:l,events:a,guardInstalled:c}}function Dl(e={}){let o=e.path??xn();if(!vs(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(xs(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?Nl:Ui;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!ks(g,c));l.length!==s[a].length&&i.push(a),l.length===0?delete s[a]:s[a]=l}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Il(o,`${JSON.stringify(t,null,2)}
10
- `),{path:o,changed:r,events:i,guardInstalled:!1}}function Sn(e=xn()){if(!vs(e))return!1;try{return!!JSON.parse(xs(e,"utf-8"))?.hooks?.Stop?.some?.(t=>ks(t,Ui))}catch{return!1}}var Ss=new up("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Pl=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Zo()}`;async function Ml(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Ss.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",Pl).action(async e=>{try{await Ml(e.url,"register",Xa.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Ss.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",Pl).action(async e=>{try{let o=await fp(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
11
- `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await Ml(e.url,"ended",Qa.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as q$}from"commander";import{Command as Sp}from"commander";ne();import T from"chalk";import{existsSync as Ep,readFileSync as Ap}from"fs";ne();import{Command as hp}from"commander";import se from"chalk";import{spawn as ql}from"child_process";import{existsSync as yp,readFileSync as wp,unlinkSync as $p}from"fs";import{resolve as Fi}from"path";var Wi=e=>new Promise(o=>setTimeout(o,e));function Bi(e){try{return process.kill(e,0),!0}catch{return!1}}async function Rt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function bp(e){let o=await Rt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await Rt(`${e}/health`);return t?typeof t.inflight?.total=="number"?t.inflight.total:Array.isArray(t.agents)?t.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function kp(e){for(let o of[Fi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(wp(o,"utf-8").trim(),10);if(Number.isFinite(t)&&Bi(t))return t}catch{}return null}function vp(e){return new Promise(o=>{let t=ql(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var Ul=new hp("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let o=j(e.config),[t,n]=o.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s}`,r=await Rt(`${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 Rt(`${i}/daemon/restart`),c=a?.pid??Pc(s)??kp(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=Nc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?Dc(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: ${Rc(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 $ of f.steps)console.log(se.dim(` ${Ll($,c)}`));console.log();return}if(e.whenIdle){let $=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite($)||$<0)&&(console.log(se.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await Ic({read:()=>bp(i),intervalMs:E*1e3,timeoutMs:$*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 ${$} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(se.yellow(` Still ${v} task(s) running after ${$} 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=Fi(g,".agentx");try{jc(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 $ of f.steps){if(await xp($,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||$.kind==="exec"&&$.mayFail)continue;let S=$===f.steps[0];try{S&&$p(Fi(p,Cc))}catch{}console.log(se.red(` Step failed: ${Ll($,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,b=Date.now();for(;Date.now()-b<k;){let $=await Rt(`${i}/health`);if($&&typeof $.uptime=="number"&&$.uptime*1e3<=Date.now()-h+2e3){let E=await Rt(`${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 Wi(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 Ll(e,o){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${o??"<pid>"} (the daemon finishes running tasks, then exits)`;case"wait-exit":return"wait for the old daemon to exit";case"wait-unloaded":return"wait until launchd has unloaded the job";case"start-detached":return"agentx daemon start --detach"}}async function xp(e,o){switch(e.kind){case"exec":return await vp(e.argv)===0;case"sigterm":if(!o.pid)return!1;try{return process.kill(o.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!o.pid)return!0;let t=Date.now(),n=!1;for(;Bi(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(se.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await Wi(500);return Bi(o.pid)?(console.log(se.yellow(` The old daemon (PID ${o.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(o.service.kind!=="launchd")return!0;let t=Date.now();for(;Si(o.service)&&Date.now()-t<3e4;)await Wi(500);return!Si(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!yp(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=ql(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function Tp(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var to=new Sp().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");to.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(b){console.error(T.red(` Failed to open ${h} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${h}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${h} for the error:`)),console.log(T.dim(` tail -n 40 ${h}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Tp(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Op(i(process.cwd(),".env"))}catch{}await new _i(e.config).start()});function Op(e){if(!Ep(e))return;let o=Ap(e,"utf-8");for(let t of o.split(`
12
- `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}to.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-SNI2B4LI.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;Fl(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(Fl(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(T.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(T.green("Daemon stopped"))}catch{console.log(T.yellow("No daemon process found"))}});to.addCommand(Ul);to.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=j(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(T.bold(` ${r.node.name}`)+T.dim(` (${r.node.id})`)),console.log(T.green(" Status: running")+T.dim(` \u2014 uptime ${Cp(r.uptime)}`)),console.log(),console.log(T.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?T.yellow(` [${c.active} active]`):"",g=c.errors>0?T.red(` (${c.errors} errors)`):"";console.log(` ${T.cyan(c.name)} ${T.dim(`(${c.tier})`)}${l}${g}`),console.log(T.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(T.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?T.green("\u25CF"):T.dim("\u25CB"),g=c.nextRun?T.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(T.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?T.green("\u25CF"):T.red("\u25CF"),g=c.skills?.length?T.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${T.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let t=j(e.config),n=Zn(t);if(console.log(),console.log(T.bold(` ${t.node.name}`)+T.dim(` (${t.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(T.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(T.red(` ${t.message}`))}}});to.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(T.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});to.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(j(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(T.dim(` Connecting to ${n}...`)),console.log(T.dim(` Press Ctrl+C to stop
8
+ The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{ql(g,{recursive:!0,force:!0})}});_t.command("start").description("start the installed desktop assistant").action(()=>{xs(),Wl(Ss().keep),console.log("Desktop assistant started.")});_t.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{xs(),await zi(Ss().keep),console.log("Desktop assistant stopped.")});_t.command("status").description("show the desktop login service status").action(()=>{xs();let{keep:e}=Ss();try{console.log(to("launchctl",["print",En(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(Yi(e.file)?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as Rp}from"commander";import{open as _p}from"fs/promises";import{existsSync as Ts,mkdirSync as Op,readFileSync as Os,writeFileSync as Bl}from"fs";import{homedir as Cp}from"os";import{dirname as jp,resolve as Vi}from"path";var Ki="/attach/",Jl="/guard/check";function Hl(e,o,t=""){return`curl -s --max-time 3 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${o}${e}${t}`}' 2>/dev/null || true`}function Es(e,o,t){let n={hooks:[{type:"command",command:Hl(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function Ip(e){return{SessionStart:[Es("/attach/session-start",e,"")],UserPromptSubmit:[Es("/attach/prompt",e)],Stop:[Es("/attach/stop",e)],SessionEnd:[Es("/attach/session-end",e)]}}function Np(e){let o=Hl("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function As(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function An(){return Vi(Cp(),".claude/settings.json")}function tt(e=process.cwd()){for(let o of[e,Vi(e,"..")]){let t=Vi(o,"agentx.json");if(Ts(t))try{let n=JSON.parse(Os(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Gl(e,o={}){let t=o.path??An(),n=o.withGuard!==!1,s={};if(Ts(t))try{s=JSON.parse(Os(t,"utf-8"))}catch(g){throw new Error(`${t} is not valid JSON (${g?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[g,d]of Object.entries(Ip(e))){let u=Array.isArray(r[g])?r[g].filter(f=>!As(f,Ki)):[];r[g]=[...u,...d],a.push(g)}let c=!1;if(n){let g=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(d=>!As(d,Jl)):[];r.PreToolUse=[...g,...Np(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(Op(jp(t),{recursive:!0}),Bl(t,`${JSON.stringify(s,null,2)}
9
+ `)),{path:t,changed:l,events:a,guardInstalled:c}}function zl(e={}){let o=e.path??An();if(!Ts(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(Os(o,"utf-8"))}catch(a){throw new Error(`${o} is not valid JSON (${a?.message}) \u2014 refusing to rewrite it`)}let n=JSON.stringify(t),s=t.hooks,i=[];if(s&&typeof s=="object"){for(let a of Object.keys(s)){if(!Array.isArray(s[a]))continue;let c=a==="PreToolUse"?Jl:Ki;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(g=>!As(g,c));l.length!==s[a].length&&i.push(a),l.length===0?delete s[a]:s[a]=l}Object.keys(s).length===0&&delete t.hooks}let r=JSON.stringify(t)!==n;return r&&Bl(o,`${JSON.stringify(t,null,2)}
10
+ `),{path:o,changed:r,events:i,guardInstalled:!1}}function Tn(e=An()){if(!Ts(e))return!1;try{return!!JSON.parse(Os(e,"utf-8"))?.hooks?.Stop?.some?.(t=>As(t,Ki))}catch{return!1}}var Cs=new Rp("monitor").description("Register external CLI sessions and report ended runs to the briefing"),Yl=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${tt()}`;async function Vl(e,o,t){let n=process.env.MESH_TOKEN,s=await fetch(e.replace(/\/$/,"")+"/monitor/"+o,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(8e3)});if(!s.ok)throw new Error(`Monitor HTTP ${s.status}: ${(await s.text()).slice(0,300)}`)}Cs.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 Vl(e.url,"register",cc.parse({id:e.session,runtime:e.runtime,label:e.label})),console.log("Session registered. Report each stopped run with agentx monitor ended.")}catch(o){console.error(o.message),process.exitCode=1}});Cs.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 o=await _p(e.transcript,"r"),t;try{let n=await o.stat();if(!n.isFile())throw new Error("Transcript must be a regular file");let s=Math.min(n.size,9e4),i=Buffer.alloc(s),{bytesRead:r}=await o.read(i,0,s,Math.max(0,n.size-s));t=(n.size>s?`[Transcript truncated: last 90 KB only]
11
+ `:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await Vl(e.url,"ended",lc.parse({sessionId:e.session,runId:e.run,transcript:t})),console.log("Run queued for review.")}catch(o){console.error(o.message),process.exitCode=1}});import{Command as mb}from"commander";import{Command as Bp}from"commander";ee();import T from"chalk";import{existsSync as Jp,readFileSync as Hp}from"fs";ee();import{Command as Dp}from"commander";import ie from"chalk";import{spawn as Xl}from"child_process";import{existsSync as Pp,readFileSync as Mp,unlinkSync as Lp}from"fs";import{resolve as Xi}from"path";var Qi=e=>new Promise(o=>setTimeout(o,e));function Zi(e){try{return process.kill(e,0),!0}catch{return!1}}async function Dt(e){try{let o=await fetch(e,{signal:AbortSignal.timeout(3e3)});return o.ok?await o.json():null}catch{return null}}async function qp(e){let o=await Dt(`${e}/daemon/restart`);if(typeof o?.inflight?.total=="number")return o.inflight.total;let t=await Dt(`${e}/health`);return t?typeof t.inflight?.total=="number"?t.inflight.total:Array.isArray(t.agents)?t.agents.reduce((n,s)=>n+(Number(s.active)||0),0):null:null}function Up(e){for(let o of[Xi(e,".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"])try{let t=parseInt(Mp(o,"utf-8").trim(),10);if(Number.isFinite(t)&&Zi(t))return t}catch{}return null}function Fp(e){return new Promise(o=>{let t=Xl(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("exit",n=>o(n??1))})}var Ql=new Dp("restart").description("restart the daemon through launchd, systemd or a plain stop + start; --when-idle waits for running tasks first").option("-c, --config <path>","path to agentx.json").option("--when-idle","wait until no task is running before restarting").option("--timeout <minutes>","how long --when-idle waits","30").option("--abort-on-timeout","with --when-idle: give up instead of restarting when the wait runs out").option("--interval <seconds>","how often --when-idle checks","5").option("--reload-service","also re-read the service's settings file (launchd plist / systemd unit)").option("--dry-run","show what would run, without restarting").action(async e=>{let o=O(e.config),[t,n]=o.node.bind.split(":"),s=parseInt(n||"18800",10),i=`http://${!t||t==="0.0.0.0"?"127.0.0.1":t}:${s}`,r=await Dt(`${i}/health`);r||(console.log(ie.red(` The daemon is not answering on ${i}; nothing to restart.`)),console.log(ie.dim(" Start it with: agentx daemon start --detach (or through its service)")),process.exit(1));let a=await Dt(`${i}/daemon/restart`),c=a?.pid??zc(s)??Up(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=Bc(l,{isRoot:u,reloadService:!!e.reloadService,plistPath:l.kind==="launchd"&&e.reloadService?Gc(l):null,interactive:!!process.stdin.isTTY});if(console.log(),console.log(` Daemon ${ie.bold(r.node?.name||r.node?.id||i)}${c?ie.dim(` (PID ${c})`):""}`),console.log(` Run by: ${Jc(l)}`),f.ok||(console.log(ie.red(` ${f.reason}`)),console.log(ie.dim(` Restart it by hand: ${f.manual}`)),process.exit(1)),l.kind==="none"&&!c&&(console.log(ie.red(" Can't find the daemon's process, so it can't be stopped safely.")),console.log(ie.dim(" Run `agentx daemon stop`, then `agentx daemon start --detach`, from the directory holding agentx.json.")),process.exit(1)),e.dryRun){console.log(ie.dim(" Would run:"));for(let $ of f.steps)console.log(ie.dim(` ${Kl($,c)}`));console.log();return}if(e.whenIdle){let $=Number(e.timeout),E=Math.max(1,Number(e.interval)||5);(!Number.isFinite($)||$<0)&&(console.log(ie.red(" --timeout must be a number of minutes")),process.exit(1));let S,x=await Wc({read:()=>qp(i),intervalMs:E*1e3,timeoutMs:$*6e4,onCheck:v=>{v!==S&&v!==null&&v>0&&console.log(ie.dim(` Waiting: ${v} task(s) running...`)),S=v}});if(x.outcome==="unreachable"&&(console.log(ie.red(" The daemon stopped answering while waiting. Not restarting it.")),console.log(ie.dim(" Check with: agentx daemon status")),process.exit(1)),x.outcome==="timeout"){let v=x.inflight??"some";e.abortOnTimeout&&(console.log(ie.yellow(` Still ${v} task(s) running after ${$} min. Not restarting (--abort-on-timeout).`)),process.exit(1)),console.log(ie.yellow(` Still ${v} task(s) running after ${$} min. Restarting anyway:`)),console.log(ie.yellow(" they get the usual time to finish, and anything cut off is picked up again after the restart."))}else console.log(ie.green(` No tasks running${x.waitedMs>=1e3?` (waited ${Math.round(x.waitedMs/1e3)}s)`:""}.`))}let p=Xi(g,".agentx");try{Fc(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(ie.dim(" Restarting..."));for(let $ of f.steps){if(await Wp($,{pid:c,daemonCwd:g,configPath:d,drainLimitMs:w,service:l})||$.kind==="exec"&&$.mayFail)continue;let S=$===f.steps[0];try{S&&Lp(Xi(p,Uc))}catch{}console.log(ie.red(` Step failed: ${Kl($,c)}`)),console.log(S?ie.dim(` The daemon is still running. Restart it with: ${f.manual}`):ie.red(` The daemon may be down. Start it with: ${f.manual}`)),process.exit(1)}let k=12e4,b=Date.now();for(;Date.now()-b<k;){let $=await Dt(`${i}/health`);if($&&typeof $.uptime=="number"&&$.uptime*1e3<=Date.now()-h+2e3){let E=await Dt(`${i}/daemon/restart`);console.log(ie.green(` Daemon is back${E?.pid?` (PID ${E.pid})`:""} after ${Math.round((Date.now()-h)/1e3)}s.`)),console.log();return}await Qi(1e3)}console.log(ie.red(` The daemon did not come back within ${k/6e4} min.`)),console.log(ie.dim(` Start it with: ${f.manual}`)),console.log(ie.dim(" Then check the log: agentx daemon logs")),process.exit(1)});function Kl(e,o){switch(e.kind){case"exec":return e.argv.join(" ");case"sigterm":return`kill -TERM ${o??"<pid>"} (the daemon finishes running tasks, then exits)`;case"wait-exit":return"wait for the old daemon to exit";case"wait-unloaded":return"wait until launchd has unloaded the job";case"start-detached":return"agentx daemon start --detach"}}async function Wp(e,o){switch(e.kind){case"exec":return await Fp(e.argv)===0;case"sigterm":if(!o.pid)return!1;try{return process.kill(o.pid,"SIGTERM"),!0}catch{return!1}case"wait-exit":{if(!o.pid)return!0;let t=Date.now(),n=!1;for(;Zi(o.pid)&&Date.now()-t<o.drainLimitMs;)!n&&Date.now()-t>3e3&&(console.log(ie.dim(" Waiting for the old daemon to finish its tasks and exit...")),n=!0),await Qi(500);return Zi(o.pid)?(console.log(ie.yellow(` The old daemon (PID ${o.pid}) is still finishing tasks; not starting a second one.`)),!1):!0}case"wait-unloaded":{if(o.service.kind!=="launchd")return!0;let t=Date.now();for(;Ri(o.service)&&Date.now()-t<3e4;)await Qi(500);return!Ri(o.service)}case"start-detached":{let t=process.argv[1];if(!t||!Pp(t))return!1;let n=[t,"daemon","start","--detach",...o.configPath?["-c",o.configPath]:[]];return new Promise(s=>{let i=Xl(process.execPath,n,{cwd:o.daemonCwd,stdio:"inherit"});i.on("error",()=>s(!1)),i.on("exit",r=>s(r===0))})}}}async function Gp(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var no=new Bp().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");no.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(b){console.error(T.red(` Failed to open ${h} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,p,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});k.unref(),d("/tmp/agentx-daemon.pid",String(k.pid)),console.log(T.green(`Daemon started in background (PID: ${k.pid})`)),console.log(T.dim(` Logs: tail -f ${h}`)),console.log(T.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(T.yellow(` Daemon exited within 1s \u2014 check ${h} for the error:`)),console.log(T.dim(` tail -n 40 ${h}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let g=!1;try{process.kill(l,0),g=!0}catch{}g&&await Gp(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{zp(i(process.cwd(),".env"))}catch{}await new Bi(e.config).start()});function zp(e){if(!Jp(e))return;let o=Hp(e,"utf-8");for(let t of o.split(`
12
+ `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}no.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);try{let{writeShutdownRequest:d}=await import("./shutdown-SNI2B4LI.js");d(n(process.cwd(),".agentx"),{by:"agentx daemon stop",pid:process.pid,at:new Date().toISOString()})}catch{}process.kill(a,"SIGTERM");let c=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10)+6e4,l=Date.now(),g=!1;for(;Zl(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(Zl(a)){console.log(T.yellow(`Daemon (PID: ${a}) is still finishing tasks. Check again with: agentx daemon status`));return}try{t(r)}catch{}console.log(T.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(T.green("Daemon stopped"))}catch{console.log(T.yellow("No daemon process found"))}});no.addCommand(Ql);no.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=O(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(T.bold(` ${r.node.name}`)+T.dim(` (${r.node.id})`)),console.log(T.green(" Status: running")+T.dim(` \u2014 uptime ${Yp(r.uptime)}`)),console.log(),console.log(T.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?T.yellow(` [${c.active} active]`):"",g=c.errors>0?T.red(` (${c.errors} errors)`):"";console.log(` ${T.cyan(c.name)} ${T.dim(`(${c.tier})`)}${l}${g}`),console.log(T.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(T.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?T.green("\u25CF"):T.dim("\u25CB"),g=c.nextRun?T.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(T.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?T.green("\u25CF"):T.red("\u25CF"),g=c.skills?.length?T.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${T.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(T.red(" Daemon is not running")),console.log(T.dim(" Start with: agentx daemon start"));else try{let t=O(e.config),n=ss(t);if(console.log(),console.log(T.bold(` ${t.node.name}`)+T.dim(` (${t.node.id})`)),console.log(T.yellow(" Status: stopped")),console.log(T.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(T.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(T.red(` ${t.message}`))}}});no.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(T.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});no.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(O(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."))}});to.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=j(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(T.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(T.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(T.dim(`
15
- (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(T.red(` Failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Try: agentx daemon status"))}});to.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(T.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Tests passed"))}catch{console.log(T.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(T.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(T.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(T.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),o.restart){console.log(T.dim(" Restarting remote daemon once no task is running..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} -t ${o.user}@${e} "cd ${o.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(T.green(" Remote daemon restarted"))}}catch(i){console.log(T.red(` Deploy failed: ${i.message}`))}});to.action(async e=>{await new _i(e.config).start()});function Cp(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 Fl(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as jp}from"commander";import no from"chalk";import{existsSync as En,readFileSync as Ip,writeFileSync as Wl,mkdirSync as Bl}from"fs";import{hostname as Jl}from"os";import{resolve as _t}from"path";var Hl=new jp().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=_t(o,"agentx.json"),n=_t(o,".env"),s=_t(o,".agentx/sessions");if(console.log(),console.log(no.bold(" agentx init")),console.log(),En(t)&&!e.force){console.log(no.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[_t(o,"agentx.example.json"),_t(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(En(c)){r=Ip(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Jl().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Jl(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),Wl(t,r),console.log(no.green(" \u2713 Created agentx.json")),En(n)||(Wl(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
- `)),console.log(no.green(" \u2713 Created .env template"))),En(s)||(Bl(s,{recursive:!0}),console.log(no.green(" \u2713 Created .agentx/sessions/")));let a=_t(o,".claude");En(a)||(Bl(a,{recursive:!0}),console.log(no.green(" \u2713 Created .claude/"))),console.log(),console.log(no.bold(" Next steps:")),console.log(` 1. Edit ${no.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${no.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${no.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${no.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Np}from"commander";import et from"chalk";import{spawn as zl}from"child_process";import{existsSync as Rp}from"fs";import{dirname as _p,resolve as Dp}from"path";import{fileURLToPath as Pp}from"url";ne();var Vl=new Np().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=dl(),t=e.port?parseInt(e.port,10):Mp(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(et.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(et.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(et.bold(` Opening ${n}`)),console.log(),await qp(n).catch(()=>!1))console.log(et.dim(" Dashboard is already running.")),e.open!==!1&&Gl(n);else{console.log(et.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Lp(),r=zl(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Gl(n),await new Promise(a=>r.on("exit",()=>a()))}});function Mp(){try{return j().dashboard.port||4202}catch{return 4202}}function Lp(){let e=Dp(_p(Pp(import.meta.url)),"cli.js");return Rp(e)?e:process.argv[1]||e}async function qp(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function Gl(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=zl(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(et.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(et.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Up}from"commander";import Ie from"chalk";var An=new Up().name("token").description("scoped API tokens for external access (mesh peers, integrations)");An.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new Ro,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Ie.bold(" Token created.")),console.log(),console.log(` id: ${Ie.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ie.dim("never")}`),console.log(),console.log(Ie.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ie.green.bold(s)}`),console.log(),console.log(Ie.dim(" Use it via the Authorization header:")),console.log(Ie.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});An.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Ro().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."))}});no.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=O(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;t.peer?(c=`${a}/mesh/task`,l={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(T.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(T.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(T.dim(`
15
+ (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(T.red(` Failed: ${s.message}`)),console.log(T.dim(" Is the daemon running? Try: agentx daemon status"))}});no.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,o)=>{let{execSync:t}=await import("child_process"),n=o.identity?`-e "ssh -i ${o.identity}"`:"",s=`${o.user}@${e}:${o.path}/dist/`;if(!o.skipChecks){try{console.log(T.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Tests passed"))}catch{console.log(T.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(T.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(T.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(T.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(T.green(" \u2713 Build complete")))}console.log(T.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(T.green(" \u2713 Deploy complete")),o.restart){console.log(T.dim(" Restarting remote daemon once no task is running..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} -t ${o.user}@${e} "cd ${o.path} && node dist/cli.js daemon restart --when-idle"`,{stdio:"inherit"}),console.log(T.green(" Remote daemon restarted"))}}catch(i){console.log(T.red(` Deploy failed: ${i.message}`))}});no.action(async e=>{await new Bi(e.config).start()});function Yp(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 Zl(e){try{return process.kill(e,0),!0}catch(o){return o?.code==="EPERM"}}import{Command as Vp}from"commander";import so from"chalk";import{existsSync as On,readFileSync as Kp,writeFileSync as ed,mkdirSync as od}from"fs";import{hostname as td}from"os";import{resolve as Pt}from"path";var nd=new Vp().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Pt(o,"agentx.json"),n=Pt(o,".env"),s=Pt(o,".agentx/sessions");if(console.log(),console.log(so.bold(" agentx init")),console.log(),On(t)&&!e.force){console.log(so.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Pt(o,"agentx.example.json"),Pt(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(On(c)){r=Kp(c,"utf-8");break}r||(r=JSON.stringify({node:{id:td().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:td(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:o,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),ed(t,r),console.log(so.green(" \u2713 Created agentx.json")),On(n)||(ed(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
16
+ `)),console.log(so.green(" \u2713 Created .env template"))),On(s)||(od(s,{recursive:!0}),console.log(so.green(" \u2713 Created .agentx/sessions/")));let a=Pt(o,".claude");On(a)||(od(a,{recursive:!0}),console.log(so.green(" \u2713 Created .claude/"))),console.log(),console.log(so.bold(" Next steps:")),console.log(` 1. Edit ${so.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${so.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${so.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${so.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as eu}from"commander";import Cn from"chalk";import{spawn as ou}from"child_process";import{existsSync as tu}from"fs";import{dirname as nu,resolve as su}from"path";import{fileURLToPath as iu}from"url";ee();import{spawn as Xp}from"child_process";import Qp from"chalk";function Zp(e=process.platform){return e==="darwin"?"open":e==="win32"?"start":"xdg-open"}function nt(e,o=Zp()){let t=()=>console.log(Qp.dim(` Couldn't open a browser. Visit ${e}`));try{let n=Xp(o,[e],{stdio:"ignore",detached:!0});n.once("error",t),n.unref()}catch{t()}}var sd=new eu().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let o=kl(),t=e.port?parseInt(e.port,10):ru(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Cn.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Cn.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Cn.bold(` Opening ${n}`)),console.log(),await cu(n).catch(()=>!1))console.log(Cn.dim(" Dashboard is already running.")),e.open!==!1&&nt(n);else{console.log(Cn.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=au(),r=ou(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&nt(n),await new Promise(a=>r.on("exit",()=>a()))}});function ru(){try{return O().dashboard.port||4202}catch{return 4202}}function au(){let e=su(nu(iu(import.meta.url)),"cli.js");return tu(e)?e:process.argv[1]||e}async function cu(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}import{Command as lu}from"commander";import Ie from"chalk";var jn=new lu().name("token").description("scoped API tokens for external access (mesh peers, integrations)");jn.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let o=new Do,t=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=o.create({name:e.name,scopes:t,expiresInDays:n});console.log(),console.log(Ie.bold(" Token created.")),console.log(),console.log(` id: ${Ie.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||Ie.dim("never")}`),console.log(),console.log(Ie.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${Ie.green.bold(s)}`),console.log(),console.log(Ie.dim(" Use it via the Authorization header:")),console.log(Ie.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});jn.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Do().list();if(e.length===0){console.log(Ie.dim(`
17
17
  No tokens issued.
18
- `));return}console.log();for(let o of e){let t=o.revokedAt?Ie.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Ie.red("expired"):Ie.green("active");console.log(` ${Ie.cyan(o.id)} ${t} ${o.name}`),console.log(Ie.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Ie.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ie.red(` ${e.message}`)),process.exit(1)}});An.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new Ro().revoke(e);o||(console.log(Ie.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ie.green(`
18
+ `));return}console.log();for(let o of e){let t=o.revokedAt?Ie.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?Ie.red("expired"):Ie.green("active");console.log(` ${Ie.cyan(o.id)} ${t} ${o.name}`),console.log(Ie.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(Ie.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(Ie.red(` ${e.message}`)),process.exit(1)}});jn.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new Do().revoke(e);o||(console.log(Ie.red(` Token ${e} not found.`)),process.exit(1)),console.log(Ie.green(`
19
19
  \u2713 Revoked ${e} (${o.name})
20
- `))}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});import{Command as Fp}from"commander";import Ae from"chalk";import{execFileSync as Kl}from"child_process";import{existsSync as Yl}from"fs";ne();var Dt=new Fp().name("app").description("pair phones with the AgentX phone app and manage paired devices");Dt.command("pair").description("pair a phone \u2014 prints a QR code to scan and a one-time code to type in the installed app").option("--name <name>","name for this phone (shown in `agentx app devices`)","Phone").option("--url <origin>","address the phone opens, e.g. https://my-mac.tailnet-name.ts.net (default: this machine's Tailscale name)").action(async e=>{try{let o=Hp(Gp(),Ji());if(o.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${o.join(", ")}`," Anyone on your tailnet can open it without a key. Serve only the app paths instead:"," tailscale serve reset",` tailscale serve --bg --set-path /app http://127.0.0.1:${Ji()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${Ji()}/api/app`].join(`
21
- `));let t=(e.url?String(e.url):Bp()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(t))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${t}`);let{token:n,record:s}=new Ro().create({name:String(e.name),scopes:["app"]}),{code:i}=new pl().create({token:n,tokenId:s.id,name:s.name}),r=`${t}/app/pair#token=${n}`,{default:a}=await import("qrcode-terminal");console.log(),a.generate(r,{small:!0},c=>console.log(c));for(let c of Wp({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!Yl("agentx.json")&&!Yl(".agentx/config.json")&&console.log(Ae.yellow(" \u26A0 No agentx.json here. The dashboard only accepts phones paired from the folder that holds agentx.json.")),console.log()}catch(o){console.log(Ae.red(` ${o.message}`)),process.exit(1)}});Dt.command("devices").description("list paired phones").action(()=>{let e=new Ro().list().filter(o=>o.scopes.includes("app"));if(e.length===0){console.log(Ae.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let o of e){let t=o.revokedAt?Ae.red("revoked"):Ae.green("active");console.log(` ${Ae.cyan(o.id)} ${t} ${o.name}`),console.log(Ae.dim(` paired: ${o.createdAt}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()});Dt.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new Ro,t=o.list().find(n=>n.id===e&&n.scopes.includes("app"));t||(console.log(Ae.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),o.revoke(e),console.log(Ae.green(`
20
+ `))}catch(o){console.log(Ie.red(` ${o.message}`)),process.exit(1)}});import{Command as du}from"commander";import Ae from"chalk";import{execFileSync as rd}from"child_process";import{existsSync as id}from"fs";ee();var Mt=new du().name("app").description("pair phones with the AgentX phone app and manage paired devices");Mt.command("pair").description("pair a phone \u2014 prints a QR code to scan and a one-time code to type in the installed app").option("--name <name>","name for this phone (shown in `agentx app devices`)","Phone").option("--url <origin>","address the phone opens, e.g. https://my-mac.tailnet-name.ts.net (default: this machine's Tailscale name)").action(async e=>{try{let o=uu(fu(),er());if(o.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the phone app: ${o.join(", ")}`," Anyone on your tailnet can open it without a key. Serve only the app paths instead:"," tailscale serve reset",` tailscale serve --bg --set-path /app http://127.0.0.1:${er()}/app`,` tailscale serve --bg --set-path /api/app http://127.0.0.1:${er()}/api/app`].join(`
21
+ `));let t=(e.url?String(e.url):mu()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(t))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${t}`);let{token:n,record:s}=new Do().create({name:String(e.name),scopes:["app"]}),{code:i}=new Sl().create({token:n,tokenId:s.id,name:s.name}),r=`${t}/app/pair#token=${n}`,{default:a}=await import("qrcode-terminal");console.log(),a.generate(r,{small:!0},c=>console.log(c));for(let c of gu({code:i,origin:t,deviceId:s.id,deviceName:s.name}))console.log(c);!id("agentx.json")&&!id(".agentx/config.json")&&console.log(Ae.yellow(" \u26A0 No agentx.json here. The dashboard only accepts phones paired from the folder that holds agentx.json.")),console.log()}catch(o){console.log(Ae.red(` ${o.message}`)),process.exit(1)}});Mt.command("devices").description("list paired phones").action(()=>{let e=new Do().list().filter(o=>o.scopes.includes("app"));if(e.length===0){console.log(Ae.dim("\n No paired phones. Run `agentx app pair`.\n"));return}console.log();for(let o of e){let t=o.revokedAt?Ae.red("revoked"):Ae.green("active");console.log(` ${Ae.cyan(o.id)} ${t} ${o.name}`),console.log(Ae.dim(` paired: ${o.createdAt}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()});Mt.command("revoke <id>").description("unpair a phone immediately").action(e=>{let o=new Do,t=o.list().find(n=>n.id===e&&n.scopes.includes("app"));t||(console.log(Ae.red(` No paired phone with id ${e}. See \`agentx app devices\`.`)),process.exit(1)),o.revoke(e),console.log(Ae.green(`
22
22
  \u2713 Unpaired ${e} (${t.name})
23
- `))});Dt.command("push-keys").description("create the key pair that lets this computer send notifications to paired phones").option("--force","replace existing keys (every phone must turn notifications on again)").action(async e=>{let o=yc;try{o=j().channels.push.keysFile}catch{}let t=wc(o),n=$c(t);if(n&&!e.force){console.log(Ae.green(`
23
+ `))});Mt.command("push-keys").description("create the key pair that lets this computer send notifications to paired phones").option("--force","replace existing keys (every phone must turn notifications on again)").action(async e=>{let o=Oc;try{o=O().channels.push.keysFile}catch{}let t=Cc(o),n=jc(t);if(n&&!e.force){console.log(Ae.green(`
24
24
  \u2713 Keys already exist in ${t} (created ${n.createdAt}).`)),console.log(Ae.dim(` Replacing them cuts off every phone; pass --force if you really mean to.
25
- `));return}let{default:s}=await import("web-push");bc(t,s.generateVAPIDKeys()),console.log(Ae.green(`
25
+ `));return}let{default:s}=await import("web-push");Ic(t,s.generateVAPIDKeys()),console.log(Ae.green(`
26
26
  \u2713 Saved new push keys to ${t}`)),console.log(Ae.dim(" Keep this file private. It is readable only by you, and agentx.json never contains it.")),n&&console.log(Ae.yellow(" \u26A0 Old keys replaced: open Alerts on each phone and turn notifications on again.")),console.log(Ae.dim(` Restart the daemon so it picks up the keys.
27
- `))});function Wp(e){let o=Math.round(gl/6e4),t=[` Pairing code: ${Ae.bold.cyan(ml(e.code))}`,Ae.dim(` Open the app from the phone's home screen and type this code. It works once, for ${o} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Ae.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Ae.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||t.push(Ae.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function Bp(){let e;try{e=JSON.parse(Kl("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let o=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!o)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${o}`}var Jp=new Set(["/app","/api/app"]);function Hp(e,o){let t=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of t)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===o&&!Jp.has(g)&&n.push(`${i}${a}`)}return n}function Gp(){try{return JSON.parse(Kl("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Ji(){try{return j().dashboard.port||4202}catch{return 4202}}ne();import{Command as ho}from"commander";import y from"chalk";import Pe from"prompts";import{readFileSync as Po,writeFileSync as Pt,existsSync as ye,mkdirSync as fo,cpSync as Hi,readdirSync as zi}from"fs";import{resolve as H,join as Do,dirname as zp}from"path";import{fileURLToPath as Vp}from"url";function le(){let e=H(process.cwd(),"agentx.json");if(!ye(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Po(e,"utf-8"))}function We(e){return pe(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(y.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var ot=new ho().name("agent").description("manage agents \u2014 add, list, remove");ot.command("list").alias("ls").description("list configured agents").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${y.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(y.dim(` workspace: ${t.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});ot.command("add").description("add a new agent interactively").action(async()=>{let e=le(),o=await Pe([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:H(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Do(o.workspace,o.id);fo(H(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(y.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(zp(Vp(import.meta.url)),"../wiki/SKILL.md"),c=ye(r)?r:a;ye(c)&&(fo(H(t,".claude/skills/wiki"),{recursive:!0}),Hi(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await We(e),console.log(y.green(`
28
- Agent "${o.id}" added`)),console.log(y.dim(` Workspace: ${t}`)),console.log(y.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});ot.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=le();if(!o.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete o.agents[e],await We(o),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});ot.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=le(),n=t.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(y.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(y.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(y.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await We(t),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Tn=new ho().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Tn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=le().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(y.dim(`
27
+ `))});function gu(e){let o=Math.round(vl/6e4),t=[` Pairing code: ${Ae.bold.cyan(xl(e.code))}`,Ae.dim(` Open the app from the phone's home screen and type this code. It works once, for ${o} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Ae.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Ae.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||t.push(Ae.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function mu(){let e;try{e=JSON.parse(rd("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let o=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!o)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${o}`}var pu=new Set(["/app","/api/app"]);function uu(e,o){let t=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of t)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===o&&!pu.has(g)&&n.push(`${i}${a}`)}return n}function fu(){try{return JSON.parse(rd("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function er(){try{return O().dashboard.port||4202}catch{return 4202}}ee();import{Command as yo}from"commander";import y from"chalk";import Pe from"prompts";import{readFileSync as Lo,writeFileSync as Lt,existsSync as ye,mkdirSync as ho,cpSync as or,readdirSync as nr}from"fs";import{resolve as H,join as Mo,dirname as hu}from"path";import{fileURLToPath as yu}from"url";function de(){let e=H(process.cwd(),"agentx.json");if(!ye(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Lo(e,"utf-8"))}function Be(e){return se(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(y.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var st=new yo().name("agent").description("manage agents \u2014 add, list, remove");st.command("list").alias("ls").description("list configured agents").action(()=>{let e=de();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${y.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(y.dim(` workspace: ${t.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});st.command("add").description("add a new agent interactively").action(async()=>{let e=de(),o=await Pe([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:H(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Mo(o.workspace,o.id);ho(H(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(y.dim(` ${l.join(" ")}`))}),r=H(process.cwd(),"src/wiki/SKILL.md"),a=H(hu(yu(import.meta.url)),"../wiki/SKILL.md"),c=ye(r)?r:a;ye(c)&&(ho(H(t,".claude/skills/wiki"),{recursive:!0}),or(c,H(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Be(e),console.log(y.green(`
28
+ Agent "${o.id}" added`)),console.log(y.dim(` Workspace: ${t}`)),console.log(y.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});st.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=de();if(!o.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete o.agents[e],await Be(o),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});st.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=de(),n=t.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(y.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(y.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(y.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Be(t),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var In=new yo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");In.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=de().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(y.dim(`
29
29
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
30
- `));return}console.log(),console.log(y.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?y.cyan(i.kind.padEnd(14)):y.dim(i.kind.padEnd(14))} ${y.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),r||console.log(` ${y.dim("(disabled)")}`)}console.log()});Tn.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=le();t.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-4WZ7Y34V.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Pe({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(y.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Pe({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(y.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Pe({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 Pe({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 Pe({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Pe({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...h]=f.split("=");p&&(g[p.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(y.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(y.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await We(t),console.log(y.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Tn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=le(),n=t.agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(y.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await We(t),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Tn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=le().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(y.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});ot.addCommand(Tn);var Es=new ho().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Es.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=le();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(y.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${y.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});Es.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=le(),o=Object.keys(e.agents||{});if(!o.length){console.log(y.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Pe({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 Pe([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(y.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(y.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await We(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Pe([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Pe([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await We(e),fo(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 Pe([{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 Pe([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await We(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 Mt=new ho().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Mt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(y.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});Mt.command("add").description("add a cron job").action(async()=>{let e=le(),o=Object.keys(e.agents||{}),t=await Pe([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await We(e),console.log(y.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Mt.command("enable <id>").description("enable a cron job").action(async e=>{let o=le();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await We(o),console.log(y.green(` Cron "${e}" enabled`))});Mt.command("disable <id>").description("disable a cron job").action(async e=>{let o=le();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await We(o),console.log(y.green(` Cron "${e}" disabled`))});var tt=new ho().name("mesh").description("manage mesh peers \u2014 add, list, remove");tt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=le();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=y.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(o.name)} ${y.dim(o.url)} ${t}`)}}console.log()});tt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=le(),o=await Pe([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await We(e),console.log(y.green(` Peer "${o.name}" added`)),console.log()}});tt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=le();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await We(o),console.log(y.green(` Peer "${e}" removed`)))});tt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=le();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(y.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(y.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await We(o),console.log(y.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});tt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=j().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(y.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+y.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(y.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var nt=new ho().name("skill").description("manage skills \u2014 add to agent(s), list");nt.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=le(),n=H(e);if(!ye(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=ye(Do(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Pe({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(y.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);fo(c,{recursive:!0}),ye(Do(n,"SKILL.md"))?Hi(n,c,{recursive:!0}):n.endsWith(".md")&&Hi(n,Do(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});nt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=le();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=ye(n)?zi(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(o)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});nt.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>ye(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=Po(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=j()}catch(k){console.log(y.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(y.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${i}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,h=0;for(let[k,b]of d){let $=b.workspace;if(!$||!ye($)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+($||"undefined")+")")}`),h++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!ye(S)){if(!o.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}o.dryRun||(fo(E,{recursive:!0}),Pt(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Po(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${k.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Pt(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});nt.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=le().agents?.[e.workspace];f||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(H(f.workspace))}else if(e.allWorkspaces){let u=le();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?y.green("PASS "):f.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${p} ${y.bold(f.name)}${f.skill?.path?y.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${u.PASS} PASS`)} ${y.yellow(`${u.REVIEW} REVIEW`)} ${y.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});nt.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=le(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(y.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-BUWOD47K.js"),c=await r(i.workspace);if(c.length===0){console.log(y.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
30
+ `));return}console.log(),console.log(y.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?y.cyan(i.kind.padEnd(14)):y.dim(i.kind.padEnd(14))} ${y.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),r||console.log(` ${y.dim("(disabled)")}`)}console.log()});In.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=de();t.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-JCETBKWT.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Pe({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(y.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Pe({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(y.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Pe({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 Pe({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 Pe({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Pe({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...h]=f.split("=");p&&(g[p.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(y.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(y.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Be(t),console.log(y.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});In.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=de(),n=t.agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(y.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Be(t),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});In.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=de().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(y.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){r+=1,console.log(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});st.addCommand(In);var js=new yo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");js.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=de();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(y.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${y.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});js.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=de(),o=Object.keys(e.agents||{});if(!o.length){console.log(y.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Pe({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 Pe([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(y.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(y.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Be(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Pe([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await Pe([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Be(e),ho(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 Pe([{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 Pe([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Be(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 qt=new yo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");qt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=de();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(y.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});qt.command("add").description("add a cron job").action(async()=>{let e=de(),o=Object.keys(e.agents||{}),t=await Pe([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Be(e),console.log(y.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});qt.command("enable <id>").description("enable a cron job").action(async e=>{let o=de();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Be(o),console.log(y.green(` Cron "${e}" enabled`))});qt.command("disable <id>").description("disable a cron job").action(async e=>{let o=de();if(!o.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Be(o),console.log(y.green(` Cron "${e}" disabled`))});var it=new yo().name("mesh").description("manage mesh peers \u2014 add, list, remove");it.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=de();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=y.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(o.name)} ${y.dim(o.url)} ${t}`)}}console.log()});it.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=de(),o=await Pe([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Be(e),console.log(y.green(` Peer "${o.name}" added`)),console.log()}});it.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=de();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Be(o),console.log(y.green(` Peer "${e}" removed`)))});it.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=de();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(y.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(y.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Be(o),console.log(y.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});it.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,o)=>{let t=o.node||"";if(!t)try{t=O().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(y.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+y.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(y.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var rt=new yo().name("skill").description("manage skills \u2014 add to agent(s), list");rt.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=de(),n=H(e);if(!ye(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=ye(Mo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Pe({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(y.yellow(` Agent "${r}" not found, skipping`));continue}let c=H(a.workspace,".claude/skills",s);ho(c,{recursive:!0}),ye(Mo(n,"SKILL.md"))?or(n,c,{recursive:!0}):n.endsWith(".md")&&or(n,Mo(c,"SKILL.md")),console.log(y.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});rt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=de();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=H(t.workspace,".claude/skills"),s=ye(n)?nr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${y.cyan(o)}: ${s.length?s.join(", "):y.dim("(none)")}`)}console.log()});rt.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[H(n,"src",e,"SKILL.md"),H(n,"skills",e,"SKILL.md")],i=s.find(k=>ye(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=Lo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=O()}catch(k){console.log(y.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(y.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${i}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,h=0;for(let[k,b]of d){let $=b.workspace;if(!$||!ye($)){console.log(` ${y.yellow("\u2717")} ${k.padEnd(22)} ${y.dim("(workspace missing: "+($||"undefined")+")")}`),h++;continue}let E=H($,".claude/skills",e),S=H(E,"SKILL.md");if(!ye(S)){if(!o.allWorkspaces){console.log(` ${y.dim("\xB7")} ${k.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}o.dryRun||(ho(E,{recursive:!0}),Lt(S,r)),console.log(` ${y.green("+")} ${k.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),u++;continue}let x=Lo(S,"utf-8");if(t("sha256").update(x).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${k.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),p++;continue}let R=(x.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Lt(S,r),console.log(` ${y.yellow("\u21BB")} ${k.padEnd(22)} ${y.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${h} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});rt.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=de().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=de();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(H(f.workspace))}else i.push(H(e.cwd));let r=H(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?y.green("PASS "):f.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${p} ${y.bold(f.name)}${f.skill?.path?y.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${u.PASS} PASS`)} ${y.yellow(`${u.REVIEW} REVIEW`)} ${y.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});rt.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,o)=>{let t=de(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(y.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-UKAOL7QB.js"),c=await r(i.workspace);if(c.length===0){console.log(y.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
31
31
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(y.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(y.dim(`
32
- (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var On=new ho().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");On.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=H(o.cwd),n=H(t,"references/example"),s=H(t,"references/recipes/example.yaml");ye(n)||(console.log(y.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(t,".agentx/references",e),r=H(t,".agentx/references/recipes");fo(i,{recursive:!0}),fo(r,{recursive:!0});let a=zi(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Do(i,d);if(ye(u)&&!o.force){console.log(y.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Po(Do(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Pt(u,p),console.log(y.green(` + ${u}`)),c++}let g=Do(r,`${e}.yaml`);if(ye(g)&&!o.force)console.log(y.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(ye(s)){let d=Po(s,"utf-8").replaceAll("example.",`${e}.`);Pt(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()});On.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(o.cwd),r=o.from?String(o.from).split(",").map(h=>h.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(y.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(y.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(y.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,w])=>[h,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(o.referencesCwd||o.cwd),u=H(d,".agentx/references",e);if(!o.write){console.log(),console.log(y.dim(` Dry-run \u2014 would write to ${u}/`));for(let[h,w]of Object.entries(g))console.log(y.cyan(`
32
+ (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Nn=new yo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Nn.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=H(o.cwd),n=H(t,"references/example"),s=H(t,"references/recipes/example.yaml");ye(n)||(console.log(y.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=H(t,".agentx/references",e),r=H(t,".agentx/references/recipes");ho(i,{recursive:!0}),ho(r,{recursive:!0});let a=nr(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Mo(i,d);if(ye(u)&&!o.force){console.log(y.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Lo(Mo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Lt(u,p),console.log(y.green(` + ${u}`)),c++}let g=Mo(r,`${e}.yaml`);if(ye(g)&&!o.force)console.log(y.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(ye(s)){let d=Lo(s,"utf-8").replaceAll("example.",`${e}.`);Lt(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()});Nn.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=H(o.cwd),r=o.from?String(o.from).split(",").map(h=>h.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(y.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(y.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(y.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,w])=>[h,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=H(o.referencesCwd||o.cwd),u=H(d,".agentx/references",e);if(!o.write){console.log(),console.log(y.dim(` Dry-run \u2014 would write to ${u}/`));for(let[h,w]of Object.entries(g))console.log(y.cyan(`
33
33
  --- ${h} ---`)),console.log(w.split(`
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}fo(u,{recursive:!0});let f=0,p=0;for(let[h,w]of Object.entries(g)){let k=Do(u,h);if(ye(k)&&!o.force){console.log(y.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}Pt(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()});On.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(H(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(y.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${y.cyan(s.id)} ${y.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(y.dim(` ${i}`))}console.log(),console.log(y.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Vi=new ho().name("hook").description("manage hooks \u2014 add to agent workspace");Vi.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=le().agents?.[e];if(!t){console.log(y.red(` Agent "${e}" not found`));return}let n=H(t.workspace,".claude/settings.json"),s=ye(n)?JSON.parse(Po(n,"utf-8")):{},i=await Pe([{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),fo(H(t.workspace,".claude"),{recursive:!0}),Pt(n,JSON.stringify(s,null,2)),console.log(y.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Yi=new ho().name("migrate").description("import configuration from OpenClaw or other tools");Yi.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ye(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(Po(n,"utf-8")),i=ye(H(process.cwd(),"agentx.json"))?le():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(w=>w===p)||h.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){fo(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(ye(u)){let f=JSON.parse(Po(u,"utf-8")),p=0;for(let h of f.jobs||[]){let w=h.name||h.id,k=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:k,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${y.green(p)} cron jobs imported`)}o.dryRun?(console.log(y.yellow(`
38
- Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await We(i),console.log(y.green(`
39
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Mo=new ho().name("config").description("validate and inspect configuration");Mo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=j(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(y.dim(` Bind: ${o.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(y.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Zn(o);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ye(H(r,".claude")),c=ye(H(r,"CLAUDE.md")),l=ye(H(r,".claude/settings.json")),g=ye(H(r,".claude/skills"))?zi(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(y.red(` \u2717 ${o.message}`))}console.log()});Mo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=j(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(y.red(o.message))}});function Yp(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function Gi(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Mo.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-5Z7EEB5N.js"),{expandEnvVars:r}=await import("./config-4WZ7Y34V.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(Gi(g))});Mo.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-5Z7EEB5N.js"),r=Yp(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${Gi(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${Gi(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})`)))});Mo.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-5Z7EEB5N.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(y.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),i.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});Mo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=j(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):r?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${o?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${t}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Kp}from"commander";import Lo from"chalk";import{resolve as qo}from"path";import{existsSync as Xp}from"fs";var vo=new Kp().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function st(e){let o=qo(e,".agentx/db.sqlite");Xp(o)||(console.log(Lo.red(` No SQLite at ${o}`)),console.log(Lo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=bt({path:o});return t||(console.log(Lo.red(` Could not open ${o}`)),console.log(Lo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function it(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Lo.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}vo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=st(qo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
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}ho(u,{recursive:!0});let f=0,p=0;for(let[h,w]of Object.entries(g)){let k=Mo(u,h);if(ye(k)&&!o.force){console.log(y.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}Lt(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()});Nn.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-KKMG24O5.js"),t=await o(H(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(y.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${y.cyan(s.id)} ${y.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(y.dim(` ${i}`))}console.log(),console.log(y.dim(` ${n.length} reference(s) loaded.`)),console.log()});var sr=new yo().name("hook").description("manage hooks \u2014 add to agent workspace");sr.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=de().agents?.[e];if(!t){console.log(y.red(` Agent "${e}" not found`));return}let n=H(t.workspace,".claude/settings.json"),s=ye(n)?JSON.parse(Lo(n,"utf-8")):{},i=await Pe([{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),ho(H(t.workspace,".claude"),{recursive:!0}),Lt(n,JSON.stringify(s,null,2)),console.log(y.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var ir=new yo().name("migrate").description("import configuration from OpenClaw or other tools");ir.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,H(process.env.HOME||"",".openclaw/openclaw.json"),H(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&ye(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(Lo(n,"utf-8")),i=ye(H(process.cwd(),"agentx.json"))?de():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(w=>w===p)||h.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){ho(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(ye(u)){let f=JSON.parse(Lo(u,"utf-8")),p=0;for(let h of f.jobs||[]){let w=h.name||h.id,k=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:k,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${y.green(p)} cron jobs imported`)}o.dryRun?(console.log(y.yellow(`
38
+ Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Be(i),console.log(y.green(`
39
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var qo=new yo().name("config").description("validate and inspect configuration");qo.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=O(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(y.dim(` Bind: ${o.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(y.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=ss(o);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ye(H(r,".claude")),c=ye(H(r,"CLAUDE.md")),l=ye(H(r,".claude/settings.json")),g=ye(H(r,".claude/skills"))?nr(H(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(y.red(` \u2717 ${o.message}`))}console.log()});qo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=O(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(y.red(o.message))}});function wu(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function tr(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}qo.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-YQWTY47O.js"),{expandEnvVars:r}=await import("./config-JCETBKWT.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(tr(g))});qo.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-YQWTY47O.js"),r=wu(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${tr(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${tr(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})`)))});qo.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-YQWTY47O.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(y.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),i.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});qo.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let d=O(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):r?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${o?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${t}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});ns();import{Command as $u}from"commander";import Uo from"chalk";import{resolve as Fo}from"path";import{existsSync as bu}from"fs";var xo=new $u().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function at(e){let o=Fo(e,".agentx/db.sqlite");bu(o)||(console.log(Uo.red(` No SQLite at ${o}`)),console.log(Uo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=No({path:o});return t||(console.log(Uo.red(` Could not open ${o}`)),console.log(Uo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function ct(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Uo.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}xo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=at(Fo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
40
40
  SELECT agent_id, channel, status, duration_ms,
41
41
  input_tokens, output_tokens,
42
42
  substr(message_preview, 1, 60) AS message,
@@ -45,7 +45,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
45
45
  ${t.length?"WHERE "+t.join(" AND "):""}
46
46
  ORDER BY started_at DESC
47
47
  LIMIT @limit
48
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});it(i,!!e.json)});vo.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=st(qo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
48
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});ct(i,!!e.json)});xo.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let o=at(Fo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(t.push("reason = @reason"),n.reason=e.reason);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
49
49
  SELECT agent_id, reason, COUNT(*) AS n,
50
50
  ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
51
51
  MAX(last_turn_input_tokens) AS max_input_tokens
@@ -59,14 +59,14 @@ The AgentX daemon and a speech transcription backend must also be available. Run
59
59
  ${s}
60
60
  ORDER BY rotated_at DESC
61
61
  LIMIT @limit
62
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});it(r,!!e.json)});vo.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=st(qo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
62
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});ct(r,!!e.json)});xo.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let o=at(Fo(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("day = @day"),n.day=e.day);let s=`
63
63
  SELECT day, agent_id, model, tasks,
64
64
  input_tokens AS in_tok, output_tokens AS out_tok,
65
65
  cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
66
66
  FROM usage_daily
67
67
  ${t.length?"WHERE "+t.join(" AND "):""}
68
68
  ORDER BY day DESC, agent_id
69
- `,i=o.prepare(s).all(n);it(i,!!e.json)});vo.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=st(qo(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
69
+ `,i=o.prepare(s).all(n);ct(i,!!e.json)});xo.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let o=at(Fo(e.cwd)),t=[],n={};e.channel&&(t.push("channel = @channel"),n.channel=e.channel),e.kind&&(t.push("kind = @kind"),n.kind=e.kind);let s=t.length?"WHERE "+t.join(" AND "):"",i=e.summary?`
70
70
  SELECT channel, kind, deciding_stage, COUNT(*) AS n
71
71
  FROM route_traces
72
72
  ${s}
@@ -79,7 +79,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
79
79
  ${s}
80
80
  ORDER BY at DESC
81
81
  LIMIT @limit
82
- `,r=o.prepare(i).all({...n,limit:Number(e.limit)});it(r,!!e.json)});vo.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=st(qo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
82
+ `,r=o.prepare(i).all({...n,limit:Number(e.limit)});ct(r,!!e.json)});xo.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=at(Fo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
83
83
  SELECT agent_id, channel, duration_ms,
84
84
  substr(error, 1, 120) AS error,
85
85
  started_at
@@ -87,12 +87,12 @@ The AgentX daemon and a speech transcription backend must also be available. Run
87
87
  WHERE ${t.join(" AND ")}
88
88
  ORDER BY started_at DESC
89
89
  LIMIT @limit
90
- `,i=o.prepare(s).all({...n,limit:Number(e.limit)});it(i,!!e.json)});vo.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=st(qo(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));it(n,!!e.json)});vo.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=st(qo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Lo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Lo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();it(n,!!o.json)}catch(n){console.log(Lo.red(` ${n.message}`)),process.exit(1)}});import{Command as eu}from"commander";import z from"chalk";import{mkdtempSync as ou}from"fs";import{tmpdir as tu}from"os";import{resolve as Ql,join as Zl}from"path";import{existsSync as nu}from"fs";import su from"better-sqlite3";function Xl(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(p){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${p?.message??p}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=Qp(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=ja(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:Zp(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Qp(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Zp(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var Uo=new eu().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Lt(e){let o=Ql(e.cwd??process.cwd()),t=Ql(o,e.path??".agentx/intent/ledger.sqlite");nu(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new su(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function rt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function iu(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function As(e){if(!e)return;let o=iu(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Uo.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=Lt(e),t=As(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),l=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),d=o.prepare(`
90
+ `,i=o.prepare(s).all({...n,limit:Number(e.limit)});ct(i,!!e.json)});xo.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=at(Fo(e.cwd)),n=o.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:o.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));ct(n,!!e.json)});xo.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,o)=>{let t=at(Fo(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Uo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Uo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();ct(n,!!o.json)}catch(n){console.log(Uo.red(` ${n.message}`)),process.exit(1)}});import{Command as xu}from"commander";import z from"chalk";import{mkdtempSync as Su}from"fs";import{tmpdir as Eu}from"os";import{resolve as cd,join as ld}from"path";import{existsSync as Au}from"fs";import Tu from"better-sqlite3";function ad(e,o,t,n=[]){let s=new Map;for(let c of o)s.set(c.id,c);let i=[];for(let c of t)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(p){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${p?.message??p}`})}continue}let l=c.decision,g=s.get(l.eventId);if(!g){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=ku(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=Wa(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:vu(l,f)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function ku(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function vu(e,o){return e.outcome==="dispatched"&&o.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&o.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==o.agentId?`agent-changed (recorded=${e.agentId} replayed=${o.agentId})`:e.outcome!==o.outcome?`outcome-changed (recorded=${e.outcome} replayed=${o.outcome})`:"unknown"}var Wo=new xu().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function Ut(e){let o=cd(e.cwd??process.cwd()),t=cd(o,e.path??".agentx/intent/ledger.sqlite");Au(t)||(console.log(z.red(` No ledger at ${t}`)),console.log(z.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Tu(t,{readonly:!0})}catch(n){console.log(z.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(z.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function lt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(z.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}function Ou(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Is(e){if(!e)return;let o=Ou(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(z.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}Wo.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let o=Ut(e),t=Is(e.since),n=t!==void 0?"WHERE ts >= @since":"",s=t!==void 0?"WHERE decided_at >= @since":"",i=n,r=o.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:t}),a=o.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:t}).n,c=o.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:t}),l=o.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:t}).n,g=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),d=o.prepare(`
91
91
  SELECT COUNT(*) as n FROM intent_decisions d
92
92
  LEFT JOIN intent_resolutions r
93
93
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
94
94
  WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
95
- `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),rt(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),rt(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),rt(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});Uo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Lt(e),t=As(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
95
+ `).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:g,inFlight:d},null,2));return}console.log(z.bold("Events by source")),lt(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),lt(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),lt(g,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${d}`))});Wo.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Ut(e),t=Is(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
96
96
  SELECT
97
97
  datetime(ts/1000, 'unixepoch') AS at,
98
98
  source,
@@ -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);rt(r,!!e.json)});Uo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Lt(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
109
+ `).all(s);lt(r,!!e.json)});Wo.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Ut(e),t=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(t.push("e.source = @source"),n.source=e.source);let s=o.prepare(`
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 ${t.join(" AND ")}
123
123
  ORDER BY d.decided_at DESC
124
124
  LIMIT @limit
125
- `).all(n);rt(s,!!e.json)});Uo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Lt(e),t=As(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
125
+ `).all(n);lt(s,!!e.json)});Wo.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Ut(e),t=Is(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=o.prepare(`
126
126
  SELECT
127
127
  datetime(ts/1000, 'unixepoch') AS at,
128
128
  source,
@@ -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);rt(r,!!e.json)});Uo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=Lt(o),n=null,s=null;if(o.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=t.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=t.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
136
+ `).all(s);lt(r,!!e.json)});Wo.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,o)=>{let t=Ut(o),n=null,s=null;if(o.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=t.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=t.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=t.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(o.json){let d=i.map(u=>({event:u,decisions:l.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let u=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${z.dim(u)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let p of f){let 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 b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),$=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim($)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});Uo.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=Lt(e),t=As(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
145
+ `).all(c);if(o.json){let d=i.map(u=>({event:u,decisions:l.filter(f=>f.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let g=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&g.add(d.agent_id);console.log(),console.log(z.bold(` Lineage for ${z.cyan(n+":"+s)}`)),console.log(z.dim(` ${i.length} event(s), ${l.length} decision(s), ${g.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let u=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${z.dim(u)} ${z.bold(d.id)} ${z.dim(`(${d.source}/${d.intent})`)}`);let f=l.filter(p=>p.event_id===d.id);if(f.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let p of f){let 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 b=p.resolution_status==="ok"?z.green(p.resolution_status):z.red(p.resolution_status),$=p.duration_ms?`${(p.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim($)}`)}else p.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});Wo.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let o=Ut(e),t=Is(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),t!==void 0&&(n.push("ts >= @since"),s.since=t);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=o.prepare(`
146
146
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
147
147
  FROM intent_events
148
148
  ${n.length?"WHERE "+n.join(" AND "):""}
@@ -156,7 +156,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
156
156
  SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
157
157
  FROM intent_resolutions
158
158
  WHERE decision_event_id IN (${c})
159
- `).all(l).map(p=>({decisionEventId:p.decision_event_id,decisionDecidedBy:p.decision_decided_by,resolvedAt:p.resolved_at,status:p.status,durationMs:p.duration_ms,resultSummary:p.result_summary})),u=ou(Zl(tu(),"agentx-ledger-replay-")),f=new va({path:Zl(u,"target.sqlite")});try{let p=Xl(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`)),rt(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()}});ta();Xm();Qm();Zm();Ym();ua();un();import{Command as ru}from"commander";import F from"chalk";import{existsSync as ed}from"fs";import{resolve as Ki}from"path";import au from"better-sqlite3";var He=new ru().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),so=".agentx/decisions/decisions.sqlite";function cu(e){return Ki(Ki(e.cwd??process.cwd()),e.path??so)}function wo(e,o=!1){let t=cu(e);ed(t)||(console.log(F.red(` No decision store at ${t}`)),console.log(F.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new Qn({path:t,readonly:!o})}catch(n){console.log(F.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(F.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function yo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(F.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(F.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function Xi(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Qi(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:Xi(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}He.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",so).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=wo(e),t=Xi(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
159
+ `).all(l).map(p=>({decisionEventId:p.decision_event_id,decisionDecidedBy:p.decision_decided_by,resolvedAt:p.resolved_at,status:p.status,durationMs:p.duration_ms,resultSummary:p.result_summary})),u=Su(ld(Eu(),"agentx-ledger-replay-")),f=new _a({path:ld(u,"target.sqlite")});try{let p=ad(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`)),lt(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()}});ma();hp();yp();wp();pp();Aa();yn();import{Command as Cu}from"commander";import F from"chalk";import{existsSync as dd}from"fs";import{resolve as rr}from"path";import ju from"better-sqlite3";var Ge=new Cu().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),io=".agentx/decisions/decisions.sqlite";function Iu(e){return rr(rr(e.cwd??process.cwd()),e.path??io)}function $o(e,o=!1){let t=Iu(e);dd(t)||(console.log(F.red(` No decision store at ${t}`)),console.log(F.dim(' Set decisions.enabled and give a seat mode "shadow" (or export AGENTX_DECISION_SEAT_<SEAT>=shadow). The file is created on the first recorded call.')),process.exit(1));try{return new ts({path:t,readonly:!o})}catch(n){console.log(F.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(F.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function wo(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(F.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(F.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function ar(e){if(!e)return;let o=e.match(/^(\d+)([dhm])$/);if(o){let n=Number(o[1]),s=o[2]==="d"?864e5:o[2]==="h"?36e5:6e4;return Date.now()-n*s}let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function cr(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:ar(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Ge.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",io).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=$o(e),t=ar(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
160
160
  COUNT(*) AS calls,
161
161
  SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
162
162
  SUM(retries) AS retries,
@@ -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(t);yo(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
169
+ ORDER BY calls DESC`).all(t);wo(n,e.json);let s=o.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(t);!e.json&&s.length>0&&(console.log(F.bold(`
172
- policy`)),yo(s,!1),console.log(F.dim(`
172
+ policy`)),wo(s,!1),console.log(F.dim(`
173
173
  explored=1 means the policy wanted to skip and the expensive path ran anyway.
174
- Those are the only rows in the skip region that can ever be graded.`))),o.close()});He.command("calls").description("recent calls").option("--path <file>","store path",so).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=wo(e),t=["ts >= ?"],n=[Xi(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
174
+ Those are the only rows in the skip region that can ever be graded.`))),o.close()});Ge.command("calls").description("recent calls").option("--path <file>","store path",io).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=$o(e),t=["ts >= ?"],n=[ar(e.since)??0];e.seat&&(t.push("seat = ?"),n.push(e.seat));let s=o.db.prepare(`SELECT id, datetime(ts/1000, 'unixepoch') AS at, seat, mode, backend, model,
175
175
  structure_mode AS structure, latency_ms AS ms, retries, truncated, error
176
176
  FROM decision_calls WHERE ${t.join(" AND ")}
177
- ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));yo(s,e.json),o.close()});He.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",so).option("--json").action((e,o)=>{let t=wo(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(F.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}yo(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});He.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",so).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=wo(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(F.green(` labeled ${e}.${o} = ${t}`)),s.close()});He.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",so).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=wo(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));yo(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});He.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",so).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=wo(e,!0),t=Ki(process.cwd(),e.db);ed(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new au(t,{readonly:!0});try{let s=Ka(n,o);console.log(F.green(` wrote ${s} label(s)`)),s===0&&console.log(F.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
178
- label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});He.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",so).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=wo(e),t=o.gradedRows(Qi(e)),n=da(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(F.bold(`
177
+ ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));wo(s,e.json),o.close()});Ge.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",io).option("--json").action((e,o)=>{let t=$o(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(F.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}wo(n.map(s=>({question:s.question,type:s.type,predicted:s.predicted,confidence:s.confidence.toFixed(3),incumbent:s.incumbent??"",truth:s.truth??""})),o.json),t.close()});Ge.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",io).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=$o(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(F.green(` labeled ${e}.${o} = ${t}`)),s.close()});Ge.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",io).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=$o(e),t=o.gradedRows({seat:e.seat}).filter(n=>n.truth===void 0).sort((n,s)=>n.confidence-s.confidence).slice(0,Number(e.limit));wo(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Ge.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",io).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=$o(e,!0),t=rr(process.cwd(),e.db);dd(t)||(console.log(F.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new ju(t,{readonly:!0});try{let s=ac(n,o);console.log(F.green(` wrote ${s} label(s)`)),s===0&&console.log(F.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
178
+ label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});Ge.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",io).requiredOption("--seat <seat>").option("--question <name>").option("--backend <name>","grade one backend in isolation").option("--model <id>").option("--structure-mode <mode>","never pool verbalized and logprob rows").option("--since <window>").option("--explored","only rows the policy wanted to skip \u2014 the unbiased skip-region sample").option("--min-n <n>","refuse to report below this many labeled rows","100").option("--bins <n>","default 10","10").option("--json").action(e=>{let o=$o(e),t=o.gradedRows(cr(e)),n=va(t,{minN:Number(e.minN),bins:Number(e.bins)});if(e.json){console.log(JSON.stringify(n,null,2)),o.close();return}if(console.log(F.bold(`
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(F.yellow(`
180
180
  Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(F.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(F.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
181
181
  accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+F.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${F.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${F.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${F.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
@@ -183,21 +183,21 @@ The AgentX daemon and a speech transcription backend must also be available. Run
183
183
  skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(F.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(F.bold(`
186
- reliability (equal-width bins)`)),yo(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});He.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",so).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=wo(e),t=o.gradedRows(Qi(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=ga(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(F.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(F.bold(`
186
+ reliability (equal-width bins)`)),wo(n.bins.map(a=>({bin:`${a.lo.toFixed(2)}\u2013${a.hi.toFixed(2)}`,n:a.n,claimed:a.meanConfidence.toFixed(3),actual:a.accuracy.toFixed(3),gap:(a.accuracy-a.meanConfidence).toFixed(3)})),!1),o.close()});Ge.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",io).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--by <names>","comma-separated covariates","agent,question").option("--folds <n>","cross-validation folds","5").option("--min-n <n>","default 100","100").option("--json").action(e=>{let o=$o(e),t=o.gradedRows(cr(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=xa(t,{covariates:n},{folds:Number(e.folds),minN:Number(e.minN)});if(e.json){console.log(JSON.stringify(s,null,2)),o.close();return}if(s.insufficient){console.log(F.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(F.bold(`
187
187
  ${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(F.dim(` Cross-validated, because more parameters always fit training data better.
188
- `)),yo(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(F.green(`
188
+ `)),wo(s.scores.map(i=>({model:i.name,logLoss:i.logLoss.toFixed(4),brier:i.brier.toFixed(4),best:i.name===s.best?"<-":""})),!1),s.best==="covariate"?(console.log(F.green(`
189
189
  Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(F.dim(" that need different corrections."))):s.best==="temperature"?console.log(F.dim(`
190
190
  One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(F.dim(`
191
- Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});He.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",so).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=wo(e),t=o.gradedRows({...Qi(e),labeledOnly:!0}),n=la(t,Number(e.steps));if(n.length===0){console.log(F.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}yo(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});He.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",so).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=>{wt();let o=wo(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
191
+ Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});Ge.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",io).requiredOption("--seat <seat>").option("--question <name>").option("--since <window>").option("--explored","only rows the policy wanted to skip").option("--steps <n>","default 20","20").option("--json").action(e=>{let o=$o(e),t=o.gradedRows({...cr(e),labeledOnly:!0}),n=ka(t,Number(e.steps));if(n.length===0){console.log(F.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}wo(n.map(s=>({threshold:s.threshold.toFixed(2),coverage:`${(s.coverage*100).toFixed(1)}%`,accuracy:`${(s.accuracy*100).toFixed(1)}%`,n:s.n})),e.json),o.close()});Ge.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",io).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=>{kt();let o=$o(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
192
192
  WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
193
193
  ${e.call?"AND id = ?":""}
194
- ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(F.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(F.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await ma(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(F.bold(`
194
+ ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(F.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(F.dim(" State is kept for the first `keepStateRows` per seat; see decisions.redactState.")),o.close();return}let n=e.backend??t.backend,s=e.model??(n===t.backend?t.model:void 0),i=await Sa(n,JSON.parse(t.state_json),JSON.parse(t.questions_json),{samples:Number(e.samples),model:s});if(e.json){console.log(JSON.stringify(i,null,2)),o.close();return}console.log(F.bold(`
195
195
  ${e.seat} on ${i.backend} (${i.model})`)),console.log(F.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
196
- `)),yo(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?F.red("NO"):"yes"})),!1),console.log(`
196
+ `)),wo(i.questions.map(r=>({question:r.question,mean:r.mean.toFixed(4),stdev:r.stdev.toFixed(4),min:r.min.toFixed(3),max:r.max.toFixed(3),answers:r.distinctAnswers.join("/"),band:r.bands.join("/"),stable:r.crossesThreshold?F.red("NO"):"yes"})),!1),console.log(`
197
197
  mean stdev ${i.meanStdev.toFixed(4)}`),console.log(F.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(F.red(`
198
198
  Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(F.dim(` not merely by how much. Usually a compound question: one name, several questions.
199
199
  Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(F.green(`
200
- Every question held its decision across all samples.`)),console.log(F.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});He.command("backends").description("registered decision backends and what they claim").action(()=>{wt();let e=oa().map(o=>{let t=ui(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});yo(e,!1),console.log(F.dim(`
200
+ Every question held its decision across all samples.`)),console.log(F.dim("\n Stability is not correctness. A question can hold perfectly still and be\n perfectly wrong \u2014 that is what `decisions calibrate` is for.")),o.close()});Ge.command("backends").description("registered decision backends and what they claim").action(()=>{kt();let e=ga().map(o=>{let t=bi(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});wo(e,!1),console.log(F.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\`.`))});He.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=>{wt();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=yt(s,"Which option fits this state?")}e.noul&&(o.verdict=ko(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await ui(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as pu}from"commander";import O from"chalk";import{resolve as ad}from"path";import{existsSync as uu}from"fs";import fu from"better-sqlite3";var od=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],lu=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function nd(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...lu,...od,"num_turns","injected_context"].map(d=>t.has(d)?d:`NULL AS ${d}`).join(", "),i=["status IN ('ok', 'error', 'timeout')"],r=[];o.since!==void 0&&(i.push("started_at >= ?"),r.push(o.since)),o.agentId&&(i.push("agent_id = ?"),r.push(o.agentId));let a=i.join(" AND "),c=e.prepare(`
208
+ labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Ge.command("ask").description("one-off smoke test against a backend (does not record)").requiredOption("--state <text>","the state to evaluate").option("--backend <name>","default mock","mock").option("--model <id>").option("--choice <labels>","comma-separated options for a choice question").option("--noul <question>","a yes/no question").action(async e=>{kt();let o={};if(e.choice){let s={};for(let i of String(e.choice).split(",").map(r=>r.trim()))i&&(s[i]=null);o.answer=bt(s,"Which option fits this state?")}e.noul&&(o.verdict=vo(String(e.noul))),Object.keys(o).length===0&&(console.log(F.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await bi(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Pu}from"commander";import C from"chalk";import{resolve as yd}from"path";import{existsSync as Mu}from"fs";import Lu from"better-sqlite3";var gd=["input_tokens","output_tokens","cache_read_tokens","cache_create_tokens","tier2_input_tokens","tier2_output_tokens","tier2_cache_read_tokens","tier2_cache_create_tokens"],Nu=["task_id","agent_id","channel","chat_id","started_at","status","duration_ms","original_message","message_preview"];function pd(e,o={}){let t=new Set(e.prepare("PRAGMA table_info(task_traces)").all().map(d=>d.name)),s=[...Nu,...gd,"num_turns","injected_context"].map(d=>t.has(d)?d:`NULL AS ${d}`).join(", "),i=["status IN ('ok', 'error', 'timeout')"],r=[];o.since!==void 0&&(i.push("started_at >= ?"),r.push(o.since)),o.agentId&&(i.push("agent_id = ?"),r.push(o.agentId));let a=i.join(" AND "),c=e.prepare(`
209
209
  SELECT ${s} FROM task_traces WHERE ${a} ORDER BY started_at
210
210
  `).all(...r),l=new Map,g=e.prepare(`
211
211
  SELECT task_id, action FROM task_trace_steps
212
212
  WHERE name = 'tool_use' AND action IS NOT NULL
213
213
  AND task_id IN (SELECT task_id FROM task_traces WHERE ${a})
214
214
  ORDER BY task_id, seq
215
- `).all(...r);for(let d of g){let u=l.get(d.task_id)??[];u.push(d.action),l.set(d.task_id,u)}return c.map(d=>{let u=d.task_id,f=d.agent_id,p=Za({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=od.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:Ia(d.injected_context)}})}function Zi(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function er(e){let o=e.filter(n=>n!==null).sort((n,s)=>n-s);if(o.length===0)return null;let t=Math.floor(o.length/2);return o.length%2?o[t]:(o[t-1]+o[t])/2}function td(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:er(e.map(o=>o.tokens)),medianTurns:er(e.map(o=>o.turns)),medianDurationMs:er(e.map(o=>o.durationMs))}}function sd(e,o={}){let t=Math.max(1,o.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of Zi(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(Zi));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=>Zi(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:td(u),after:td(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Fo from"chalk";function du(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function gu(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function mu(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function or(e,o){if(e==null||o==null||e===0)return"";let t=Math.round((o-e)/e*100);return t===0?" (=)":` (${t>0?"+":""}${t}%)`}function id(e,o,t){let n=`${Math.round(o.successRate*100)}%`,s=t?` (${o.successRate>=t.successRate?"+":""}${Math.round((o.successRate-t.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(o.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${du(o.medianTokens)}${t?or(t.medianTokens,o.medianTokens):""}`,`turns ${mu(o.medianTurns)}${t?or(t.medianTurns,o.medianTurns):""}`,`time ${gu(o.medianDurationMs)}${t?or(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function rd(e,o){if(e.length===0)return[Fo.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Fo.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let t=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&t.push(""),t.push(`${Fo.bold(s.agentId)} ${Fo.cyan(s.cluster)}`),n=i),t.push(` ${Fo.yellow(s.lesson)} ${Fo.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Fo.dim(id("before",s.before))),t.push(id("after",s.after,s.before))}return t.push(""),t.push(Fo.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var qt=new pu().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Os(e){let o=ad(e.cwd??process.cwd()),t=ad(o,e.path??".agentx/db.sqlite");uu(t)||(console.log(O.red(` No db at ${t}`)),console.log(O.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new fu(t,{readonly:!0})}catch(n){console.log(O.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(O.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function hu(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function cd(e){if(!e)return;let o=hu(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(O.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function yu(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function tr(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}qt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Os(e),t=Na(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:cd(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(O.dim(" (no traces)"));return}for(let n of t){let s=tr(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?O.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?O.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${O.dim(n.taskId)} ${s} ${O.bold(n.agentId)}${O.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${O.dim("\xB7")} ${i}${a} ${O.dim(yu(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});qt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=Os(o),n=$i(t,e);if(n||(console.log(O.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}wu(n.task,n.steps)});function wu(e,o){let t=tr(e.status)(e.status);if(console.log(O.bold(`Trace ${e.taskId}`)),console.log(` ${O.dim("agent")} ${e.agentId}`),console.log(` ${O.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${O.dim("workflow")} ${O.cyan(e.workflowRunId)}${n?O.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${O.dim("intent")} ${e.intentEventId} ${O.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${O.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${O.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${O.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${O.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${O.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${O.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.numTurns!=null&&console.log(` ${O.dim("turns")} ${e.numTurns}`),e.injectedContext){let{memory:n,procedures:s,wiki:i}=e.injectedContext,r=[...n.map(a=>`memory:${a}`),...s.map(a=>`procedure:${a}`),...i?["wiki"]:[]];console.log(` ${O.dim("lessons")} ${r.length?r.join(" "):O.dim("none")}`)}if(e.error&&console.log(` ${O.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${O.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(O.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(O.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?tr(n.status)(n.status):O.dim("\u2014"),i=n.action?O.cyan(n.action):"";if(console.log(` ${O.dim(`#${n.seq}`)} ${O.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?O.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
216
- `).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2192")} ${a}`).join(`
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=dc({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=gd.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:Ba(d.injected_context)}})}function lr(e){return e.injected?[...e.injected.memory.map(o=>`memory:${o}`),...e.injected.procedures.map(o=>`procedure:${o}`),...e.injected.wiki?["wiki"]:[]]:[]}function dr(e){let o=e.filter(n=>n!==null).sort((n,s)=>n-s);if(o.length===0)return null;let t=Math.floor(o.length/2);return o.length%2?o[t]:(o[t-1]+o[t])/2}function md(e){return{n:e.length,successRate:e.length?e.filter(o=>o.ok).length/e.length:0,medianTokens:dr(e.map(o=>o.tokens)),medianTurns:dr(e.map(o=>o.turns)),medianDurationMs:dr(e.map(o=>o.durationMs))}}function ud(e,o={}){let t=Math.max(1,o.minSamples??2),n=new Map,s=new Map;for(let r of e){for(let l of lr(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(lr));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=>lr(p).includes(g));u.length<t||f.length<t||i.push({agentId:a,cluster:c,lesson:g,addedAt:d,before:md(u),after:md(f)})}}return i.sort((r,a)=>r.agentId.localeCompare(a.agentId)||r.cluster.localeCompare(a.cluster)||r.addedAt-a.addedAt)}import Bo from"chalk";function Ru(e){return e==null?"\u2014":e>=1e3?`${(e/1e3).toFixed(1)}k`:`${Math.round(e)}`}function _u(e){return e==null?"\u2014":e>=6e4?`${(e/6e4).toFixed(1)}m`:`${(e/1e3).toFixed(1)}s`}function Du(e){return e==null?"\u2014":Number.isInteger(e)?`${e}`:e.toFixed(1)}function gr(e,o){if(e==null||o==null||e===0)return"";let t=Math.round((o-e)/e*100);return t===0?" (=)":` (${t>0?"+":""}${t}%)`}function fd(e,o,t){let n=`${Math.round(o.successRate*100)}%`,s=t?` (${o.successRate>=t.successRate?"+":""}${Math.round((o.successRate-t.successRate)*100)} pts)`:"";return[` ${e.padEnd(6)} n=${String(o.n).padEnd(4)}`,`success ${n}${s}`,`tokens ${Ru(o.medianTokens)}${t?gr(t.medianTokens,o.medianTokens):""}`,`turns ${Du(o.medianTurns)}${t?gr(t.medianTurns,o.medianTurns):""}`,`time ${_u(o.medianDurationMs)}${t?gr(t.medianDurationMs,o.medianDurationMs):""}`].join(" ")}function hd(e,o){if(e.length===0)return[Bo.dim(` No lesson has at least ${o.minSamples} recorded task(s) before and after it yet.`),Bo.dim(" Tasks record which lessons they used from this version on; repeated tasks need time to build up.")];let t=[],n="";for(let s of e){let i=`${s.agentId} ${s.cluster}`;i!==n&&(n&&t.push(""),t.push(`${Bo.bold(s.agentId)} ${Bo.cyan(s.cluster)}`),n=i),t.push(` ${Bo.yellow(s.lesson)} ${Bo.dim(`first used ${new Date(s.addedAt).toISOString().slice(0,10)}`)}`),t.push(Bo.dim(fd("before",s.before))),t.push(fd("after",s.after,s.before))}return t.push(""),t.push(Bo.dim(" Medians per task. Small samples are noisy: treat a change as a hint until n grows.")),t}var Ft=new Pu().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Rs(e){let o=yd(e.cwd??process.cwd()),t=yd(o,e.path??".agentx/db.sqlite");Mu(t)||(console.log(C.red(` No db at ${t}`)),console.log(C.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Lu(t,{readonly:!0})}catch(n){console.log(C.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(C.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function qu(e){let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!o)return null;let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function wd(e){if(!e)return;let o=qu(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(C.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Uu(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s ago`:o<3600?`${Math.round(o/60)}m ago`:o<86400?`${Math.round(o/3600)}h ago`:`${Math.round(o/86400)}d ago`}function mr(e){return e==="ok"?C.green:e==="error"||e==="timeout"?C.red:e==="in-flight"?C.yellow:C.dim}Ft.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=Rs(e),t=Ja(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:wd(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(C.dim(" (no traces)"));return}for(let n of t){let s=mr(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?C.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?C.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${C.dim(n.taskId)} ${s} ${C.bold(n.agentId)}${C.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${C.dim("\xB7")} ${i}${a} ${C.dim(Uu(n.startedAt))}`),n.error&&console.log(` ${C.red("error:")} ${n.error}`)}});Ft.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=Rs(o),n=Oi(t,e);if(n||(console.log(C.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Fu(n.task,n.steps)});function Fu(e,o){let t=mr(e.status)(e.status);if(console.log(C.bold(`Trace ${e.taskId}`)),console.log(` ${C.dim("agent")} ${e.agentId}`),console.log(` ${C.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${C.dim("workflow")} ${C.cyan(e.workflowRunId)}${n?C.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${C.dim("intent")} ${e.intentEventId} ${C.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${C.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${C.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${C.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${C.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${C.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${C.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(` ${C.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(` ${C.dim("lessons")} ${r.length?r.join(" "):C.dim("none")}`)}if(e.error&&console.log(` ${C.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${C.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(C.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(C.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?mr(n.status)(n.status):C.dim("\u2014"),i=n.action?C.cyan(n.action):"";if(console.log(` ${C.dim(`#${n.seq}`)} ${C.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?C.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
216
+ `).slice(0,8);console.log(r.map(a=>` ${C.dim("\u2192")} ${a}`).join(`
217
217
  `)),n.inputSummary.split(`
218
- `).length>8&&console.log(` ${O.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
219
- `).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2190")} ${a}`).join(`
218
+ `).length>8&&console.log(` ${C.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
219
+ `).slice(0,8);console.log(r.map(a=>` ${C.dim("\u2190")} ${a}`).join(`
220
220
  `)),n.outputSummary.split(`
221
- `).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}qt.command("lessons").description("compare repeated tasks before and after each lesson (memory, procedure, wiki) was used").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","only this agent").option("--since <duration>","only tasks newer than (e.g. 7d, 30d)","30d").option("--min <n>","minimum tasks on each side of a lesson","2").option("--json","emit JSON").action(e=>{let o=Os(e),t=Math.max(1,parseInt(e.min,10)||2),n=nd(o,{since:cd(e.since),agentId:e.agent}),s=sd(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of rd(s,{minSamples:t}))console.log(i)});qt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Os(o),n=$i(t,e);n||(console.log(O.red(` task not found: ${e}`)),console.log(O.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(O.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(O.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(O.bold(` replay ${O.cyan(e)}`)),console.log(O.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(O.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},l=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(O.red(` daemon unreachable at ${a}: ${f.message||f}`)),process.exit(1)}let d=await g.json().catch(()=>({})),u=Date.now()-l;if(g.ok||(console.log(O.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(O.bold(" INPUT (replayed verbatim)")),console.log(),Ts(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Ts(s.finalResponse):console.log(O.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(O.bold(` CURRENT OUTPUT ${O.dim(`status=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Ts(d.content??"(empty reply)"),d.error&&console.log(O.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?O.dim(" outputs are identical"):O.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(O.green(` \u2713 replayed in ${u}ms`)),console.log(),Ts(d.content??"(empty reply)"),d.error&&console.log(O.red(`
222
- error: ${d.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Ts(e){let o=e.split(`
223
- `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${O.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${O.dim("\u2502")} ${O.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as vu}from"commander";import ue from"chalk";import{existsSync as xu,mkdirSync as Su,writeFileSync as Eu}from"fs";import{resolve as gd,join as dd,dirname as Au}from"path";var $u=`# AgentX destructive-action guardrails \u2014 global policy
221
+ `).length>8&&console.log(` ${C.dim("\u2026")}`)}n.error&&console.log(` ${C.red("error:")} ${n.error}`)}}Ft.command("lessons").description("compare repeated tasks before and after each lesson (memory, procedure, wiki) was used").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","only this agent").option("--since <duration>","only tasks newer than (e.g. 7d, 30d)","30d").option("--min <n>","minimum tasks on each side of a lesson","2").option("--json","emit JSON").action(e=>{let o=Rs(e),t=Math.max(1,parseInt(e.min,10)||2),n=pd(o,{since:wd(e.since),agentId:e.agent}),s=ud(n,{minSamples:t});if(e.json){console.log(JSON.stringify(s,null,2));return}for(let i of hd(s,{minSamples:t}))console.log(i)});Ft.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=Rs(o),n=Oi(t,e);n||(console.log(C.red(` task not found: ${e}`)),console.log(C.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(C.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(C.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(C.bold(` replay ${C.cyan(e)}`)),console.log(C.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(C.dim(` original status=${s.status} duration=${s.durationMs??"?"}ms tokens=in:${s.inputTokens??0}/out:${s.outputTokens??0}`)),console.log();let a=String(o.daemon).replace(/\/+$/,""),c={agent:s.agentId,message:i,freshSession:o.fresh!==!1,context:{channel:s.channel??"api",chatId:`replay-${e.toLowerCase().slice(-8)}-${Date.now().toString(36)}`}},l=Date.now(),g;try{g=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(f){console.log(C.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(C.red(` replay failed (${g.status}): ${d.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(C.bold(" INPUT (replayed verbatim)")),console.log(),Ns(i),console.log(),console.log(C.bold(` ORIGINAL OUTPUT ${C.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?Ns(s.finalResponse):console.log(C.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(C.bold(` CURRENT OUTPUT ${C.dim(`status=${d.error?"error":"ok"} ${u}ms tokens=in:${d.usage?.inputTokens??0}/out:${d.usage?.outputTokens??0}`)}`)),console.log(),Ns(d.content??"(empty reply)"),d.error&&console.log(C.red(` error: ${d.error}`)),console.log();let f=(s.finalResponse??"").trim()===(d.content??"").trim();s.finalResponse&&(console.log(f?C.dim(" outputs are identical"):C.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(C.green(` \u2713 replayed in ${u}ms`)),console.log(),Ns(d.content??"(empty reply)"),d.error&&console.log(C.red(`
222
+ error: ${d.error}`)),console.log(),console.log(C.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function Ns(e){let o=e.split(`
223
+ `),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${C.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${C.dim("\u2502")} ${C.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Hu}from"commander";import ue from"chalk";import{existsSync as Gu,mkdirSync as zu,writeFileSync as Yu}from"fs";import{resolve as kd,join as bd,dirname as Vu}from"path";var Wu=`# 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
- `,bu=`# Production protected resources.
249
+ `,Bu=`# 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
- `,ku=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
271
+ `,Ju=`# 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
- `,ld=[{relPath:"policy.yaml",content:$u},{relPath:"environments/production.yaml",content:bu},{relPath:"agents/coder-agent.yaml",content:ku}];var Wo=new vu().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function nr(e){return e==="deny"?ue.red:e==="escalate"||e==="ask"?ue.yellow:e==="warn"?ue.magenta:ue.green}function Cs(e){return e.root?gd(e.root):Fc()}Wo.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 Uc({root:Cs(e),agentId:e.agent,env:e.env}),process.exit(0)});Wo.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=Cs(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=qc({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}Tu(s,i,r)});function Tu(e,o,t){let n=nr(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ue.dim(" (no rule matched)")}`),console.log(` enforced as ${nr(e.effectiveAction)(e.effectiveAction)} ${ue.dim(`(mode=${o})`)}`),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 ${t}ms`)}`),console.log()}Wo.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=$a({root:Cs(e),verdict:e.verdict,agentId:e.agent,taskId:e.task,limit:parseInt(e.limit,10)||30});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ue.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=nr(t.verdict),i=t.effective_action!==t.verdict?ue.dim(`->${t.effective_action}`):"";console.log(` ${ue.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ue.cyan((t.agent_id??"?").padEnd(16))} ${ue.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ue.dim(` target: ${t.resolved_target}`))}});Wo.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=dd(gd(e.root),Mc),t=0;for(let n of ld){let s=dd(o,n.relPath);if(xu(s)&&!e.force){console.log(ue.dim(` skip (exists) ${n.relPath}`));continue}Su(Au(s),{recursive:!0}),Eu(s,n.content),console.log(ue.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ue.cyan(o)}`),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.'))});Wo.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(ue.green(` daemon reloaded (${e.url})`)):console.log(ue.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ue.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Wo.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Lc(Cs(e),e.agent);console.log(JSON.stringify(o,null,2))});fn();import{Command as Ou}from"commander";import{execFile as Cu}from"child_process";import{promisify as ju}from"util";import{existsSync as Iu}from"fs";import io from"chalk";un();var jn="ui-element";function js(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:Cn(t.tried,80),screenChanged:t.changed,note:t.note?Cn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:md(t.role),label:Cn(t.label,120),value:t.value?Cn(t.value,80):null,enabled:t.enabled}))}}function Is(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${md(t.role)}: ${Cn(n,80)}`}return{target:yt(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:ko("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 Ns(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function md(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Cn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var pd=ju(Cu),ud=new Ou().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{Iu(De)||(console.log(io.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await ps({max:Number(o.max)||40})}catch(d){console.log(io.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(io.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=kn(t,n[0].id);d&&(console.log(io.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+io.bold(n[0].label)),await pd(De,["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 po(jn,js({request:e,app:t.app,window:t.window,candidates:n}),Is(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(io.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${jn}.mode`)),process.exit(1));let i=Ns(s.answers,n),r=kn(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(io.yellow(` nothing on screen matches "${e}"`)+io.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${io.green("\u2192")} ${io.bold(g)} `+io.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await pd(De,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as Zu}from"commander";import Ge from"chalk";import{readFileSync as fd}from"fs";import{homedir as Nu}from"os";import{join as Ru}from"path";var hd=12e5,_u="https://openrouter.ai/api/v1/chat/completions",Du=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Pu(e={kind:"window"},o=hd,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return jt(e,{},n);try{return await jt(e,{untilStable:!0},n)}catch(s){if(s instanceof cl)return jt(e,{},n);throw s}}var Mu=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
280
+ `,$d=[{relPath:"policy.yaml",content:Wu},{relPath:"environments/production.yaml",content:Bu},{relPath:"agents/coder-agent.yaml",content:Ju}];var Jo=new Hu().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function pr(e){return e==="deny"?ue.red:e==="escalate"||e==="ask"?ue.yellow:e==="warn"?ue.magenta:ue.green}function _s(e){return e.root?kd(e.root):Qc()}Jo.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 Xc({root:_s(e),agentId:e.agent,env:e.env}),process.exit(0)});Jo.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=_s(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=Kc({tool:o.tool,command:e,cwd:o.cwd,agentId:o.agent,env:o.env},{root:t,agentId:o.agent,env:o.env,modeOverride:n,noAudit:!0});if(o.json){console.log(JSON.stringify({verdict:s,mode:i,ms:r},null,2));return}Ku(s,i,r)});function Ku(e,o,t){let n=pr(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ue.dim(" (no rule matched)")}`),console.log(` enforced as ${pr(e.effectiveAction)(e.effectiveAction)} ${ue.dim(`(mode=${o})`)}`),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 ${t}ms`)}`),console.log()}Jo.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Ia({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(o,null,2));return}if(o.length===0){console.log(ue.dim(" (no guardrail decisions recorded yet)"));return}for(let t of o){let n=new Date(t.ts).toISOString().replace("T"," ").slice(0,19),s=pr(t.verdict),i=t.effective_action!==t.verdict?ue.dim(`->${t.effective_action}`):"";console.log(` ${ue.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ue.cyan((t.agent_id??"?").padEnd(16))} ${ue.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ue.dim(` target: ${t.resolved_target}`))}});Jo.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=bd(kd(e.root),Yc),t=0;for(let n of $d){let s=bd(o,n.relPath);if(Gu(s)&&!e.force){console.log(ue.dim(` skip (exists) ${n.relPath}`));continue}zu(Vu(s),{recursive:!0}),Yu(s,n.content),console.log(ue.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ue.cyan(o)}`),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.'))});Jo.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(ue.green(` daemon reloaded (${e.url})`)):console.log(ue.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ue.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});Jo.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Vc(_s(e),e.agent);console.log(JSON.stringify(o,null,2))});wn();import{Command as Xu}from"commander";import{execFile as Qu}from"child_process";import{promisify as Zu}from"util";import{existsSync as ef}from"fs";import ro from"chalk";yn();var _n="ui-element";function Ds(e){let o=(e.priorAttempts??[]).slice(-4);return{request:e.request,app:e.app,window:e.window??null,...o.length?{alreadyTried:o.map(t=>({control:Rn(t.tried,80),screenChanged:t.changed,note:t.note?Rn(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:vd(t.role),label:Rn(t.label,120),value:t.value?Rn(t.value,80):null,enabled:t.enabled}))}}function Ps(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${vd(t.role)}: ${Rn(n,80)}`}return{target:bt(o,"Which control does the request refer to? If `alreadyTried` shows a control was clicked and the screen did not change, that one did not work \u2014 choose differently."),present:vo("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 Ms(e,o){let t=e.target,n=o.map(s=>({id:s.id,score:t.probabilities[String(s.id)]??0})).sort((s,i)=>i.score-s.score);return{id:Number(t.choice),confidence:t.confidence,present:e.present.noul,ranked:n}}function vd(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Rn(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}var xd=Zu(Qu),Sd=new Xu().name("point").description("point at the on-screen control matching a description (does not click)").argument("<request>",'what you mean, e.g. "the send button"').option("--max <n>","candidates to consider","40").option("--json","emit the decision as JSON instead of pointing").option("--min-present <p>","refuse below this P(control exists)","0.5").action(async(e,o)=>{ef(De)||(console.log(ro.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await ws({max:Number(o.max)||40})}catch(d){console.log(ro.red(` could not read the screen: ${d?.message??d}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(ro.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let d=Sn(t,n[0].id);d&&(console.log(ro.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+ro.bold(n[0].label)),await xd(De,["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 uo(_n,Ds({request:e,app:t.app,window:t.window,candidates:n}),Ps(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(ro.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${_n}.mode`)),process.exit(1));let i=Ms(s.answers,n),r=Sn(t,i.id),a=n.find(d=>d.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(ro.yellow(` nothing on screen matches "${e}"`)+ro.dim(` (P(exists)=${i.present.toFixed(2)} below ${l})`)),process.exit(2)),o.json){console.log(JSON.stringify({app:t.app,request:e,chosen:{...r,label:a,fromOCR:c},present:i.present,confidence:i.confidence,ranked:i.ranked.slice(0,5).map(d=>({...d,label:n.find(u=>u.id===d.id)?.label}))},null,2));return}let g=a;console.log(` ${ro.green("\u2192")} ${ro.bold(g)} `+ro.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await xd(De,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",g])});import{Command as xf}from"commander";import ze from"chalk";import{readFileSync as Ed}from"fs";import{homedir as of}from"os";import{join as tf}from"path";var Ad=12e5,nf="https://openrouter.ai/api/v1/chat/completions",sf=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function rf(e={kind:"window"},o=Ad,t={}){let n={...t.deps,maxPixels:o,settings:t.screen??t.deps?.settings};if(!t.settle)return Nt(e,{},n);try{return await Nt(e,{untilStable:!0},n)}catch(s){if(s instanceof $l)return Nt(e,{},n);throw s}}var af=`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 Lu(e,o,t,n){let s=Uu();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=fd(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
288
+ Answer "unclear" when the deciding detail is not in frame, too small to read, or covered. "unclear" is a useful answer. A confident guess is not.`;async function cf(e,o,t,n){let s=df();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=Ed(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
289
289
 
290
- The image is the region ${qu(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:Mu,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(_u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${p.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(d.function.arguments),f=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Rs(e,o={}){let t=Date.now(),n=await Pu(o.region??{kind:"window"},o.maxPixels??hd,{settle:o.settle,screen:o.screen}),s=await Lu(e,n,o.model??Du,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function qu(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var In;function Uu(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(In!==void 0)return In??void 0;try{let e=fd(Ru(Nu(),".agentx","openrouter-key.txt"),"utf-8").trim();In=e.length>0?e:null}catch{In=null}return In??void 0}import{execFile as Fu}from"child_process";import{promisify as Wu}from"util";var Bu=Wu(Fu),Ju=["screencapture"],Hu=["Screen Studio","OBS","QuickTime Player","Zoom"];async function wd(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Gu()),t}async function Gu(){let e=await yd(Ju);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await yd(Hu);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function yd(e){let o=[];for(let t of e)try{let{stdout:n}=await Bu("pgrep",["-x",t]),s=n.trim().split(`
291
- `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}fn();un();var $d="screen-state",bd={observable:ko("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:ko("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 kd(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 vd(e){return{observable:e.observable.noul,holds:e.holds.noul}}var zu=.6,Vu=.7,Yu=.3;async function Nn(e,o={}){let[t,n]=await Promise.all([Rs(e,o),wd(e).catch(()=>[])]),s=o.observableFloor??zu,i=await po($d,kd({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Qu(t),treeNote:o.treeNote,probes:n}),bd,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:Xu(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=vd(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 (${_s(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Vu?"confirmed":a<=Yu?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Ku(c,a,t),sighting:t,probes:n}}function Ku(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${_s(o)}). ${n}`:e==="refuted"?`Not true (${_s(1-o)} it is false). ${n}`:`Inconclusive (${_s(o)}, between the thresholds). ${n}`}function Xu(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function Qu(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var _s=e=>`${Math.round(e*100)}%`;var xd=new Zu().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--settle","wait for the region to stop moving before capturing it").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(Ge.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Nn(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?uo():void 0});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?Ge.green("\u2713"):s.outcome==="refuted"?Ge.red("\u2717"):Ge.yellow("?");console.log(` ${i} ${Ge.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(Ge.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(Ge.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 Rs(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?uo():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${Ge.bold(n.observation)}`),n.evidence&&console.log(Ge.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${ef(n.reading)}`),console.log(Ge.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(Ge.red(` ${n?.message??n}`)),process.exit(1)}});function ef(e){return e==="yes"?Ge.green(e):e==="no"?Ge.red(e):Ge.yellow(e)}import{Command as of}from"commander";import ro from"chalk";import{spawn as tf}from"child_process";function Bo(e){console.log(ro.red(` ${e}`)),process.exit(1)}function Sd(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?ro.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(ro.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function nf(e){return new Promise(o=>{let t=tf(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var Rn=new of("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");Rn.command("capture").description("capture a region, optionally waiting for it to change or settle, or around a command").argument("[command...]","run this after arming; capture what it changes (put it after --)").option("--region <name|x,y,w,h>","window, screen, menubar, notifications, a name from screen.regions, or x,y,w,h","window").option("--until-changed","wait for the region to change first").option("--until-stable","wait for the region to stop changing").option("--max-pixels <n>","pixel budget for this capture (default screen.maxPixels)").option("--out <path>","where to write the PNG").option("-c, --config <path>","agentx.json to read screen settings from").option("--json","print the result as JSON").action(async(e,o)=>{let t=uo(o.config),n;try{n=us(o.region,t)}catch(r){Bo(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Bo("--max-pixels must be a whole number above 0");let i={settings:t,maxPixels:s};try{if(e.length){let r=o.untilStable||!o.untilChanged,{result:a,shot:c,error:l}=await fs(()=>nf(e),n,{out:o.out,untilStable:r},i);c||(console.log(ro.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),Sd(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}Sd(await jt(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){Bo(r?.message??String(r))}});Rn.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:${Zo()}`).option("--json","print the result as JSON").action(async e=>{let o=process.env.MESH_TOKEN,t=e.seconds?`?seconds=${encodeURIComponent(e.seconds)}`:"";try{let n=await fetch(`${String(e.url).replace(/\/$/,"")}/screen/recent${t}`,{headers:o?{Authorization:`Bearer ${o}`}:{},signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));if(n.ok||Bo(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(ro.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${ro.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Bo(`could not reach the daemon: ${n?.message??n}`)}});Rn.command("config").description("show or change screen capture settings (agentx.json `screen`)").option("--max-pixels <n>","pixel budget for a captured frame").option("--timeout <ms>","longest a capture waits").option("--interval <ms>","time between samples while waiting").option("--threshold <0-1>","difference that counts as a change").option("--stable-ms <ms>","how long a region must hold still to be stable").option("--region <name=x,y,w,h>","add or change a named region",(e,o)=>[...o,e],[]).option("--remove-region <name>","remove a named region",(e,o)=>[...o,e],[]).option("--buffer <state>","on | off: keep recent frames in memory").option("--buffer-seconds <n>","how many seconds the buffer keeps").option("--buffer-fps <n>","samples per second").option("--buffer-region <name|x,y,w,h>","region the buffer watches").option("--buffer-max-pixels <n>","pixel budget per buffered frame").option("-c, --config <path>","agentx.json to read and change (default: ./agentx.json)").action(e=>{let o={};e.maxPixels!==void 0&&(o.maxPixels=e.maxPixels),e.timeout!==void 0&&(o.timeoutMs=e.timeout),e.interval!==void 0&&(o.intervalMs=e.interval),e.threshold!==void 0&&(o.changeThreshold=e.threshold),e.stableMs!==void 0&&(o.stableMs=e.stableMs);let t={};for(let s of e.region){let i=s.indexOf("=");i<1&&Bo(`--region wants name=x,y,w,h, got "${s}"`),t[s.slice(0,i)]=s.slice(i+1)}for(let s of e.removeRegion)t[s]=null;Object.keys(t).length&&(o.regions=t);let n={};if(e.buffer!==void 0){let s=String(e.buffer).toLowerCase();["on","off"].includes(s)||Bo("--buffer must be on|off"),n.enabled=s==="on"}if(e.bufferSeconds!==void 0&&(n.seconds=e.bufferSeconds),e.bufferFps!==void 0&&(n.fps=e.bufferFps),e.bufferRegion!==void 0&&(n.region=e.bufferRegion),e.bufferMaxPixels!==void 0&&(n.maxPixels=e.bufferMaxPixels),Object.keys(n).length&&(o.buffer=n),Object.keys(o).length===0){let s=uo(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(" "):ro.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":ro.dim("off")} ${ro.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
293
- `);return}try{let{summary:s,backupPath:i}=Ze(r=>{let a=al(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(ro.green(`
294
- \u2713 ${s}`)),i&&console.log(ro.dim(` Backup: ${i}`)),console.log()}catch(s){Bo(s?.message??String(s))}});fn();import{Command as af}from"commander";import{execFile as Nd}from"child_process";import{promisify as cf}from"util";import{existsSync as lf,readFileSync as df,writeFileSync as Rd,mkdirSync as gf}from"fs";import{homedir as mf}from"os";import{join as pf,dirname as uf}from"path";import Le from"chalk";un();var sr="paste-transform";function Ed(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 o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:ko("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:yt(o,"What shape should this paste arrive in?")}}function Td(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var sf=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"]),rf=e=>/^https?:\/\/\S+$/i.test(e.trim()),ir=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
290
+ The image is the region ${lf(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:af,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(nf,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"HTTP-Referer":"https://github.com/acme/agentx","X-Title":"agentx"},body:JSON.stringify(r),signal:a.signal})}finally{clearTimeout(c)}if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${p.slice(0,300)}`)}let g=await l.json(),d=g?.choices?.[0]?.message?.tool_calls?.[0];if(!d?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(d.function.arguments),f=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.evidence??"").trim(),reading:f,model:typeof g.model=="string"?g.model:t,usage:{inputTokens:g?.usage?.prompt_tokens??0,outputTokens:g?.usage?.completion_tokens??0}}}async function Ls(e,o={}){let t=Date.now(),n=await rf(o.region??{kind:"window"},o.maxPixels??Ad,{settle:o.settle,screen:o.screen}),s=await cf(e,n,o.model??sf,o.timeoutMs??45e3);return{question:e,observation:s.observation,evidence:s.evidence,reading:s.reading,shot:n,model:s.model,latencyMs:Date.now()-t,usage:s.usage}}function lf(e){let{x:o,y:t,width:n,height:s}=e.region;return t<=1&&s<=40?"the macOS menu bar at the top of the screen":`x=${Math.round(o)} y=${Math.round(t)} ${Math.round(n)}x${Math.round(s)} points`}var Dn;function df(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Dn!==void 0)return Dn??void 0;try{let e=Ed(tf(of(),".agentx","openrouter-key.txt"),"utf-8").trim();Dn=e.length>0?e:null}catch{Dn=null}return Dn??void 0}import{execFile as gf}from"child_process";import{promisify as mf}from"util";var pf=mf(gf),uf=["screencapture"],ff=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Od(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await hf()),t}async function hf(){let e=await Td(uf);if(e.length)return{checked:"running screen-capture processes (pgrep)",found:`A screen capture is definitely in progress: ${e.join(", ")}. This process only exists while it is recording, so this settles the question on its own.`};let o=await Td(ff);return o.length?{checked:"running screen-capture processes (pgrep)",found:`No standalone capture process. A recorder application IS open (${o.join(", ")}), but its process exists whether or not it is recording, so this neither confirms nor denies. macOS does not expose in-app recording state to this tool, and the menu bar indicator is about six points \u2014 measured as below what the vision models here resolve reliably. Unless something else settles it, this claim cannot be verified.`}:{checked:"running screen-capture processes (pgrep)",found:"No screen-capture process is running and no recorder application is open. Nothing that records the screen from outside an app is active."}}async function Td(e){let o=[];for(let t of e)try{let{stdout:n}=await pf("pgrep",["-x",t]),s=n.trim().split(`
291
+ `)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}wn();yn();var Cd="screen-state",jd={observable:vo("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:vo("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 Id(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 yf=.6,wf=.7,$f=.3;async function Pn(e,o={}){let[t,n]=await Promise.all([Ls(e,o),Od(e).catch(()=>[])]),s=o.observableFloor??yf,i=await uo(Cd,Id({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:vf(t),treeNote:o.treeNote,probes:n}),jd,{incumbent:{holds:t.reading==="yes"?1:0},features:{model:t.model,region:t.shot.region.height<=40?"menubar":"window"}});if(!i){let l=t.reading==="yes"?"confirmed":t.reading==="no"?"refuted":"unknown";return{claim:e,outcome:l,ok:l==="confirmed",observable:null,holds:null,calibrated:!1,reason:kf(l,t),sighting:t,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 (${qs(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=wf?"confirmed":a<=$f?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:bf(c,a,t),sighting:t,probes:n}}function bf(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${qs(o)}). ${n}`:e==="refuted"?`Not true (${qs(1-o)} it is false). ${n}`:`Inconclusive (${qs(o)}, between the thresholds). ${n}`}function kf(e,o){let t=o.evidence||o.observation||"no specific detail",n=" \u2014 uncalibrated, the screen-state seat is off";return e==="unknown"?`Could not tell${n}. ${t}`:`${e==="confirmed"?"Looks true":"Looks false"}${n}. ${t}`}function vf(e){let o=e.shot.region;return o.y<=1&&o.height<=40?"the macOS menu bar":`a ${Math.round(o.width)}x${Math.round(o.height)} region of the screen`}var qs=e=>`${Math.round(e*100)}%`;var Rd=new xf().name("look").description("look at the screen with a vision model \u2014 for state the tree and OCR cannot see").argument("<question>",'what you want to know, e.g. "is a dialog covering the page?"').option("--verify","treat the argument as a claim and judge it (exit 3 refuted, 4 unknown)").option("--menubar","capture the menu bar instead of the focused window").option("--screen","capture the whole screen instead of the focused window").option("--rect <x,y,w,h>","capture an explicit region").option("--settle","wait for the region to stop moving before capturing it").option("--model <id>","vision model to use").option("--json","emit the result as JSON").action(async(e,o)=>{let t={kind:"window"};if(o.menubar)t={kind:"menubar"};else if(o.screen)t={kind:"screen"};else if(o.rect){let n=String(o.rect).split(",").map(Number);(n.length!==4||n.some(Number.isNaN))&&(console.log(ze.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await Pn(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?fo():void 0});if(o.json)console.log(JSON.stringify({claim:s.claim,outcome:s.outcome,ok:s.ok,observable:s.observable,holds:s.holds,calibrated:s.calibrated,reason:s.reason,evidence:s.sighting.evidence,probes:s.probes,observation:s.sighting.observation,shot:s.sighting.shot.path,model:s.sighting.model,latencyMs:s.sighting.latencyMs},null,2));else{let i=s.outcome==="confirmed"?ze.green("\u2713"):s.outcome==="refuted"?ze.red("\u2717"):ze.yellow("?");console.log(` ${i} ${ze.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(ze.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(ze.dim(` ${s.sighting.model} \xB7 ${s.sighting.latencyMs}ms \xB7 ${s.sighting.shot.path}`))}process.exit(s.outcome==="confirmed"?0:s.outcome==="refuted"?3:4)}let n=await Ls(e,{region:t,model:o.model,settle:o.settle,screen:o.settle?fo():void 0});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${ze.bold(n.observation)}`),n.evidence&&console.log(ze.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Sf(n.reading)}`),console.log(ze.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(ze.red(` ${n?.message??n}`)),process.exit(1)}});function Sf(e){return e==="yes"?ze.green(e):e==="no"?ze.red(e):ze.yellow(e)}import{Command as Ef}from"commander";import ao from"chalk";import{spawn as Af}from"child_process";function Ho(e){console.log(ao.red(` ${e}`)),process.exit(1)}function _d(e,o,t={}){if(o){console.log(JSON.stringify({...e,...t},null,2));return}let n=e.waitedMs===void 0?"":` \xB7 ${e.timedOut?ao.yellow("timed out"):[e.changed&&"changed",e.stable&&"stable"].filter(Boolean).join(", ")} after ${e.waitedMs}ms`;console.log(` ${e.path}`),console.log(ao.dim(` ${e.region.width}\xD7${e.region.height} at ${e.region.x},${e.region.y} \xB7 ${Math.round(e.bytes/1024)}KB${n}`))}function Tf(e){return new Promise(o=>{let t=Af(e[0],e.slice(1),{stdio:"inherit"});t.on("error",()=>o(127)),t.on("close",n=>o(n??1))})}var Mn=new Ef("screen").description("capture the screen at the right moment: after an action, a change, or once it settles");Mn.command("capture").description("capture a region, optionally waiting for it to change or settle, or around a command").argument("[command...]","run this after arming; capture what it changes (put it after --)").option("--region <name|x,y,w,h>","window, screen, menubar, notifications, a name from screen.regions, or x,y,w,h","window").option("--until-changed","wait for the region to change first").option("--until-stable","wait for the region to stop changing").option("--max-pixels <n>","pixel budget for this capture (default screen.maxPixels)").option("--out <path>","where to write the PNG").option("-c, --config <path>","agentx.json to read screen settings from").option("--json","print the result as JSON").action(async(e,o)=>{let t=fo(o.config),n;try{n=$s(o.region,t)}catch(r){Ho(r.message)}let s=o.maxPixels===void 0?void 0:Number(o.maxPixels);s!==void 0&&!(Number.isInteger(s)&&s>0)&&Ho("--max-pixels must be a whole number above 0");let i={settings:t,maxPixels:s};try{if(e.length){let r=o.untilStable||!o.untilChanged,{result:a,shot:c,error:l}=await bs(()=>Tf(e),n,{out:o.out,untilStable:r},i);c||(console.log(ao.red(` command exited ${a}; no capture: ${l}`)),process.exit(a!==0?a:1)),_d(c,o.json,{exitCode:a}),a!==0&&process.exit(a);return}_d(await Nt(n,{untilChanged:o.untilChanged,untilStable:o.untilStable,out:o.out},i),o.json)}catch(r){Ho(r?.message??String(r))}});Mn.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:${tt()}`).option("--json","print the result as JSON").action(async e=>{let o=process.env.MESH_TOKEN,t=e.seconds?`?seconds=${encodeURIComponent(e.seconds)}`:"";try{let n=await fetch(`${String(e.url).replace(/\/$/,"")}/screen/recent${t}`,{headers:o?{Authorization:`Bearer ${o}`}:{},signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));if(n.ok||Ho(s.error??`daemon ${n.status}`),e.json){console.log(JSON.stringify(s,null,2));return}if(!s.frames.length){console.log(ao.dim(" no frames yet"));return}for(let i of s.frames)console.log(` ${i.path} ${ao.dim(`${(i.ageMs/1e3).toFixed(1)}s ago \xB7 ${i.width}\xD7${i.height}`)}`)}catch(n){Ho(`could not reach the daemon: ${n?.message??n}`)}});Mn.command("config").description("show or change screen capture settings (agentx.json `screen`)").option("--max-pixels <n>","pixel budget for a captured frame").option("--timeout <ms>","longest a capture waits").option("--interval <ms>","time between samples while waiting").option("--threshold <0-1>","difference that counts as a change").option("--stable-ms <ms>","how long a region must hold still to be stable").option("--region <name=x,y,w,h>","add or change a named region",(e,o)=>[...o,e],[]).option("--remove-region <name>","remove a named region",(e,o)=>[...o,e],[]).option("--buffer <state>","on | off: keep recent frames in memory").option("--buffer-seconds <n>","how many seconds the buffer keeps").option("--buffer-fps <n>","samples per second").option("--buffer-region <name|x,y,w,h>","region the buffer watches").option("--buffer-max-pixels <n>","pixel budget per buffered frame").option("-c, --config <path>","agentx.json to read and change (default: ./agentx.json)").action(e=>{let o={};e.maxPixels!==void 0&&(o.maxPixels=e.maxPixels),e.timeout!==void 0&&(o.timeoutMs=e.timeout),e.interval!==void 0&&(o.intervalMs=e.interval),e.threshold!==void 0&&(o.changeThreshold=e.threshold),e.stableMs!==void 0&&(o.stableMs=e.stableMs);let t={};for(let s of e.region){let i=s.indexOf("=");i<1&&Ho(`--region wants name=x,y,w,h, got "${s}"`),t[s.slice(0,i)]=s.slice(i+1)}for(let s of e.removeRegion)t[s]=null;Object.keys(t).length&&(o.regions=t);let n={};if(e.buffer!==void 0){let s=String(e.buffer).toLowerCase();["on","off"].includes(s)||Ho("--buffer must be on|off"),n.enabled=s==="on"}if(e.bufferSeconds!==void 0&&(n.seconds=e.bufferSeconds),e.bufferFps!==void 0&&(n.fps=e.bufferFps),e.bufferRegion!==void 0&&(n.region=e.bufferRegion),e.bufferMaxPixels!==void 0&&(n.maxPixels=e.bufferMaxPixels),Object.keys(n).length&&(o.buffer=n),Object.keys(o).length===0){let s=fo(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(" "):ao.dim("built-in only")}`);let r=s.buffer;console.log(` buffer ${r.enabled?"on":ao.dim("off")} ${ao.dim(`${r.region} \xB7 ${r.seconds}s \xB7 ${r.fps} fps \xB7 ${r.maxPixels} px`)}
293
+ `);return}try{let{summary:s,backupPath:i}=eo(r=>{let a=wl(r.screen,o);return r.screen=a,`screen = ${JSON.stringify(a)}`},{configPath:e.config});console.log(ao.green(`
294
+ \u2713 ${s}`)),i&&console.log(ao.dim(` Backup: ${i}`)),console.log()}catch(s){Ho(s?.message??String(s))}});wn();import{Command as jf}from"commander";import{execFile as Wd}from"child_process";import{promisify as If}from"util";import{existsSync as Nf,readFileSync as Rf,writeFileSync as Bd,mkdirSync as _f}from"fs";import{homedir as Df}from"os";import{join as Pf,dirname as Mf}from"path";import qe from"chalk";yn();var ur="paste-transform";function Dd(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Pd(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:vo("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:bt(o,"What shape should this paste arrive in?")}}function Md(e){let o=e.worthChanging,t=e.shape,n=Object.entries(t.probabilities??{}).map(([s,i])=>({id:s,p:Number(i)||0})).sort((s,i)=>i.p-s.p);return{worthChanging:o.noul,id:t.choice,confidence:t.confidence,ranked:n}}var Of=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"]),Cf=e=>/^https?:\/\/\S+$/i.test(e.trim()),fr=[{id:"asIs",criterion:"Paste it unchanged. The text is already in the right shape for where it is going, or it is something whose exact bytes matter \u2014 a password, a token, a command, code, an identifier.",label:"unchanged",apply:e=>e},{id:"unwrap",criterion:"Join lines that were hard-wrapped back into continuous paragraphs, keeping blank lines as paragraph breaks. For text copied out of a PDF, an email or a terminal, where every line ends at a fixed width mid-sentence.",label:"unwrap lines",apply:e=>{let o=e.split(`
295
295
  `);if(o.length<3)return null;let t=0;for(let n=0;n<o.length-1;n++){let s=o[n].trim(),i=o[n+1].trim();s.length>40&&i.length>0&&!/[.!?:;]$/.test(s)&&t++}return t<2?null:e.split(/\n\s*\n/).map(n=>n.split(`
296
296
  `).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
297
297
 
@@ -299,29 +299,29 @@ The image is the region ${qu(o)}.`},{type:"image_url",image_url:{url:`data:image
299
299
  `).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
300
300
  `)}},{id:"quote",criterion:"Prefix every line with a markdown blockquote marker. For quoting someone else's words into a document, an issue or a message.",label:"blockquote",apply:e=>{let o=e.split(`
301
301
  `);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
302
- `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!rf(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])sf.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
302
+ `)}},{id:"codeFence",criterion:"Wrap it in a fenced code block. For code, a command, a log line or structured output going somewhere that renders markdown.",label:"code block",apply:e=>e.trim().startsWith("```")?null:"```\n"+e.replace(/\n+$/,"")+"\n```"},{id:"prettyJson",criterion:"Re-indent it as readable JSON. Only for text that already parses as JSON.",label:"format JSON",apply:e=>{let o=e.trim();if(!/^[[{]/.test(o))return null;try{let t=JSON.parse(o),n=JSON.stringify(t,null,2);return n===o?null:n}catch{return null}}},{id:"cleanUrl",criterion:"Strip campaign and tracking parameters from the link, keeping the rest of it intact. For a URL copied out of a share sheet, a newsletter or a social post.",label:"clean the link",apply:e=>{let o=e.trim();if(!Cf(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Of.has(s.toLowerCase())&&(t.searchParams.delete(s),n++);return n===0?null:t.toString().replace(/\?$/,"")}catch{return null}}},{id:"slug",criterion:"Convert to a lowercase hyphenated slug. For a title or phrase going into a branch name, a filename or a URL path.",label:"slug",apply:e=>{let o=e.trim();if(o.includes(`
303
303
  `)||o.length>90||o.length<3)return null;let t=o.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t!==o?t:null}},{id:"collapseSpace",criterion:"Collapse runs of whitespace and trim the ends, leaving one clean line. For text copied out of a web page that arrived padded with stray spaces, tabs and newlines.",label:"tidy whitespace",apply:e=>{let o=e.replace(/[ \t]+/g," ").replace(/\s*\n\s*/g,`
304
- `).trim();return o===e?null:o}}];function Od(e){let o=[];for(let t of ir){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Cd(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
304
+ `).trim();return o===e?null:o}}];function Ld(e){let o=[];for(let t of fr){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function qd(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
305
305
  \u2026[${e.length-o} more characters]\u2026
306
- ${e.slice(-n)}`}function jd(e){let o=e.trim();return o.includes(`
307
- `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var rr=cf(Nd),_d=new af().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 (${ir.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=hf();c===null&&(console.log(Le.yellow(" nothing to undo")),process.exit(2)),await Pd(c),console.log(` ${Le.green("\u2192")} clipboard restored`);return}let o=await yf();if(o||(console.log(Le.yellow(" clipboard is empty")),process.exit(2)),jd(o)){Dd(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Od(o),n=await wf();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Le.red(` "${e.as}" does not apply to this clipboard`)),console.log(Le.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Ut(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Ut(e,"asIs",o,o,"nothing else applies",0);return}let s=await po(sr,Ed({preview:Cd(o),length:o.length,lineCount:o.split(`
308
- `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Ad(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Ut(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${sr}.mode`,0);return}let i=Td(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Ut(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await Ut(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Ut(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Ut(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(ff(n),await Pd(t)),Dd(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await rr(De,["key","--name","v","--mod","command"]).catch(a=>{console.log(Le.red(` could not paste: ${a?.message??a}`))})}function Dd(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Le.dim("\u2192")} ${Le.bold("unchanged")} ${Le.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Le.green("\u2192")} ${Le.bold(o.applied)} ${Le.dim(`\xB7 ${o.reason}`)}`),console.log(Le.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Le.dim(Id(o.original))),console.log(Le.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Id(o.result)),!e.apply&&!e.paste&&console.log(Le.dim(`
309
- (dry run \u2014 pass --apply to write it back)`))}var Id=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
306
+ ${e.slice(-n)}`}function Ud(e){let o=e.trim();return o.includes(`
307
+ `)||o.length>200?!1:/^(sk|pk|ghp|gho|ghs|glpat|xox[abps])[-_][A-Za-z0-9_-]{16,}$/.test(o)||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(o)||/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\./.test(o)||o.length>=20&&!/\s/.test(o)&&/[A-Z]/.test(o)&&/[a-z]/.test(o)&&/\d/.test(o)&&!/^https?:\/\//i.test(o)&&!/\.(com|org|net|io|ai|tn)$/i.test(o)}var hr=If(Wd),Jd=new jf().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 (${fr.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=qf();c===null&&(console.log(qe.yellow(" nothing to undo")),process.exit(2)),await Gd(c),console.log(` ${qe.green("\u2192")} clipboard restored`);return}let o=await Uf();if(o||(console.log(qe.yellow(" clipboard is empty")),process.exit(2)),Ud(o)){Hd(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Ld(o),n=await Ff();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(qe.red(` "${e.as}" does not apply to this clipboard`)),console.log(qe.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await Wt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await Wt(e,"asIs",o,o,"nothing else applies",0);return}let s=await uo(ur,Dd({preview:qd(o),length:o.length,lineCount:o.split(`
308
+ `).length,app:n.app,destination:n.role,destinationLabel:n.label}),Pd(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await Wt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${ur}.mode`,0);return}let i=Md(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await Wt(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await Wt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await Wt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function Wt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(Lf(n),await Gd(t)),Hd(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await hr(De,["key","--name","v","--mod","command"]).catch(a=>{console.log(qe.red(` could not paste: ${a?.message??a}`))})}function Hd(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${qe.dim("\u2192")} ${qe.bold("unchanged")} ${qe.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${qe.green("\u2192")} ${qe.bold(o.applied)} ${qe.dim(`\xB7 ${o.reason}`)}`),console.log(qe.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(qe.dim(Fd(o.original))),console.log(qe.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Fd(o.result)),!e.apply&&!e.paste&&console.log(qe.dim(`
309
+ (dry run \u2014 pass --apply to write it back)`))}var Fd=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
310
310
  `).map(t=>` ${t}`).join(`
311
- `),Ds=pf(mf(),".agentx","paste-undo.txt");function ff(e){try{gf(uf(Ds),{recursive:!0}),Rd(Ds,e,{mode:384})}catch{}}function hf(){try{let e=df(Ds,"utf-8");return Rd(Ds,"",{mode:384}),e.length?e:null}catch{return null}}async function yf(){let{stdout:e}=await rr("pbpaste",[],{maxBuffer:16777216});return e}async function Pd(e){await new Promise((o,t)=>{Nd("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function wf(){if(!lf(De))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await rr(De,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:$f(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function $f(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as bf}from"commander";import Be from"chalk";ne();function Md(e,o,t={}){let n={shot:null,error:"no banner was shown (held for Focus, or the banner is off)"};return{alert:async(s,i)=>{let{shot:r,error:a}=await fs(()=>e(s,i),o,{},t);n=r?.timedOut&&!r.changed?{shot:r,error:"the banner region did not change \u2014 Do Not Disturb, or notifications not allowed"}:{shot:r,error:a}},proof:()=>n}}var kf=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function vf(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
312
- ${n}`:n,a=await fetch(`${kf}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function xf(e){let o;try{o=j(e.config)}catch{o=void 0}let t=as(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??cs(o);return{alert:pc(t),banner:t.banner,channel:n}}var Ld=new bf().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","AgentX").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel (default: notifications.channel, else push when it is on, else ntfy)").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").option("--proof","capture the banner as it shows and print the frame's path").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new nc,n=La(),{alert:s,banner:i,channel:r}=xf(o),a=s,c;if(o.proof&&!i)c=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(o.proof){let g=uo(o.config),d=Md(s,us("notifications",g),{settings:g});a=d.alert,c=d.proof}if(o.status){let g=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:g},null,2));return}console.log(` ${n.active?Be.yellow("\u25D0"):Be.green("\u25CB")} ${qa(n)} ${Be.dim(`\xB7 ${n.reason}`)}`),console.log(` ${g.length} held`);for(let d of g.slice(0,8)){let u=new Date(d.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(Be.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=vf(r,o.chatId);if(o.flush){let g=await hc(l,{queue:t,alert:s});console.log(g?Be.green(` delivered ${g} held notification(s)`):Be.dim(" nothing was held"));return}e?.trim()||(console.log(Be.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await fc({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:r,chatId:o.chatId},l,{queue:t,alert:a,focus:n}),d=c?.();if(o.json){console.log(JSON.stringify(d?{...g,proof:d}:g,null,2));return}let u=g.delivered?Be.green("\u2192"):Be.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Be.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Be.yellow("?"):Be.green("\u2713")} banner: ${d.shot.path}${Be.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Be.yellow(` ${d.error}`))}catch(g){console.log(Be.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});import{Command as Ft}from"commander";import ao from"chalk";var qd=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function co(e,o,t,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${qd}${o}`,{method:e,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...n},body:t===void 0?void 0:JSON.stringify(t)}).catch(a=>{throw new Error(`daemon not reachable at ${qd}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function Sf(e,o,t){e.calls=e.calls??{};let n=Array.isArray(e.calls.allow)?e.calls.allow:[],s=n.includes(o);return t===s?`${o} is ${t?"already":"not"} in calls.allow`:(e.calls.allow=t?[...n,o]:n.filter(i=>i!==o),t?`${o} may now call you`:`${o} may no longer call you`)}function cr(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?ao.yellow("missed"):e.status==="ringing"?ao.green("ringing"):ao.dim(e.status),n=e.note?ao.dim(` (${e.note})`):"";return` ${ao.dim(e.id)} ${o} ${e.agentId} ${t}${n}
313
- ${e.reason}${e.summary?ao.dim(`
314
- summary: ${e.summary}`):""}`}async function _n(e){try{await e()}catch(o){console.log(ao.red(` ${o?.message??o}`)),process.exit(1)}}var Ef=new Ft("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=>_n(async()=>{let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let t=await co("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},yn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang==="widget"?"ringing on AgentX Voice":t.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${t.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${t.rang?ao.green("\u260E"):ao.yellow("\u23F8")} ${t.call.id} ${n}`)})),Af=new Ft("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=>_n(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await co("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ao.dim(" no calls"));return}for(let n of t)console.log(cr(n))}));function ar(e,o){return new Ft(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>_n(async()=>{let{call:n}=await co("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(cr(n))}))}var Tf=new Ft("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>_n(async()=>{let{call:t}=await co("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(cr(t))}));function Ud(e,o){return new Ft(e).description(o?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((t,n)=>_n(()=>{let{summary:s}=Ze(i=>Sf(i,t,o),{configPath:n.config});console.log(ao.green(` ${s}`))}))}var Fd=new Ft("call").description("agents ring you for a live voice call").addCommand(Ef).addCommand(Af).addCommand(ar("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(ar("decline","decline a ringing call")).addCommand(Tf).addCommand(ar("hangup","end an answered call")).addCommand(Ud("allow",!0)).addCommand(Ud("disallow",!1));import{Command as at}from"commander";import ze from"chalk";function Wd(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?ze.yellow("missed"):e.status==="ringing"?ze.green("asking"):e.status==="answered"?ze.green("showing"):ze.dim(e.status),n=e.note?ze.dim(` (${e.note})`):"";return` ${ze.dim(e.id)} ${o} ${e.agentId} ${t}${n}
315
- ${e.reason}`}async function Wt(e){try{await e()}catch(o){console.log(ze.red(` ${o?.message??o}`)),process.exit(1)}}function Bd(e){let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error(`no agent: ${e} happens from inside an agent's run, which sets AGENTX_AGENT_ID`);return o}var Of=new at("ask").description("ask the owner to show you their phone camera; runs inside an agent's turn").requiredOption("--reason <text>","what you want to see, in one line: shown on the phone").option("--urgent","ask even during Focus").option("--json","print the ask as JSON").action(e=>Wt(async()=>{let o=Bd("a camera ask"),t=await co("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal",kind:"camera"},yn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang?"the owner's phone was told; when they tap Show, use `agentx camera look` for the newest picture":`not asked now: ${t.call.note??"held"} \u2014 it is listed as missed`;console.log(` ${t.rang?ze.green("\u{1F4F7}"):ze.yellow("\u23F8")} ${t.call.id} ${n}`)})),Cf=new at("look").description("the newest picture from the owner's camera, as a PNG path to open; runs inside an agent's turn").option("--json","print the frame as JSON").action(e=>Wt(async()=>{let o=Bd("a look"),t=await co("POST","/webrtc/camera/look",{agentId:o},yn());if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(` ${t.frame.path}`),console.log(ze.dim(` ${t.frame.width}x${t.frame.height}, taken ${new Date(t.frame.takenAt).toLocaleTimeString()} (share ${t.callId})`))})),jf=new at("list").description("recent camera asks, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Wt(async()=>{let o=new URLSearchParams({limit:String(e.limit),kind:"camera"});e.status&&o.set("status",e.status);let{calls:t}=await co("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ze.dim(" no camera asks"));return}for(let n of t)console.log(Wd(n))})),If=new at("watching").description("agents watching a phone camera right now").option("--json","print as JSON").action(e=>Wt(async()=>{let{active:o}=await co("GET","/webrtc/camera/watch");if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(ze.dim(" no agent is watching a camera"));return}for(let t of o){let n=Math.max(0,Math.round((t.until-Date.now())/6e4));console.log(` ${ze.dim(t.callId)} ${t.agentId} ${t.frames} frames, ${t.looks} looks, ${n} min left`)}})),Nf=new at("decline").description("turn down a camera ask").argument("<id>","ask id, from `agentx camera list`").action(e=>Wt(async()=>{let{call:o}=await co("POST",`/calls/${encodeURIComponent(e)}/decline`,{});console.log(Wd(o))})),Rf=new at("stop").description("end a live watch (the share id from `agentx camera watching`)").argument("<id>","share id").action(e=>Wt(async()=>{await co("POST",`/webrtc/camera/watch/${encodeURIComponent(e)}/stop`,{}),console.log(ze.green(` ${e} stopped`))})),Jd=new at("camera").description("agents ask to see through your phone camera").addCommand(Of).addCommand(Cf).addCommand(jf).addCommand(If).addCommand(Nf).addCommand(Rf);fn();ua();ta();un();import{Command as _f}from"commander";import{readFileSync as Df}from"fs";var Hd=new _f().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?Df(e.file,"utf8"):await Pf()}catch(r){ct(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return ct("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return ct(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return ct("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return ct("spec needs at least one entry in `questions`");try{ca(t.questions)}catch(r){return ct(r?.message??String(r))}let n=t.seat||e.seat;wt(),process.env[ha(n)]="active";let s=null;if(e.record!==!1)try{s=new Qn({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
316
- `)}fa({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await po(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return ct(`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 ct(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Pf(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}fn();import{Command as ph}from"commander";import{execFile as uh,spawn as rg}from"child_process";import{promisify as fh}from"util";import{existsSync as hh,statSync as yh}from"fs";import{join as ag}from"path";import{tmpdir as wh}from"os";import oe from"chalk";var Mf={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."}]},qf={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."}]},lr=[Mf,Lf,qf];ne();ne();import lo from"chalk";import{execFile as Uf}from"child_process";import{promisify as Ff}from"util";import{createInterface as Wf}from"readline";var Gd=Ff(Uf);function Bf(e){e.type==="step"?console.log(`${lo.cyan(` ${e.n}. ${e.action}`)}${e.target?lo.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(lo.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?lo.red(` failed: ${e.error}`):lo.dim(" done it")):e.type==="replanned"?console.log(lo.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(lo.cyan(` you: ${e.text}`)):e.type==="error"?console.log(lo.red(` error: ${e.error}`)):e.type==="end"&&console.log(lo.dim(` \xB7 ended (${e.reason})`))}async function Jf(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await Gd("open",["-a",e]).catch(()=>{});try{let s=(await ji()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function zd(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await Gd("open",["-a",o.app]),i=await Jf(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=gs(n,t.agents,!1),a=t.voice.listener??Zc,c=Tt(n,t.agents[n]),l=new tl({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:ji,presence:new ms(c,De,n),speech:new Ot,model:Ct({system:ol(r.persona,a)}),act:nl});l.on(Bf),console.log(lo.bold(`
317
- ${c.name} teaches: ${e}`)+lo.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
318
- `));let g=Wf({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 go from"chalk";import{execFile as sh}from"child_process";import{existsSync as mr,writeFileSync as ih}from"fs";import{homedir as rh}from"os";import{join as sg,resolve as ah}from"path";import{promisify as ch}from"util";var Je={w:1e3,h:640},dr=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Kd=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],Vd=["none","semi","solid","fill","pattern"],gr=180,Xd=48,Hf=["s","m","l","xl"],Gf=["draw","sans","serif","mono"];function Qd(){return[`You are an illustrator drawing on a tldraw canvas ${Je.w} wide and ${Je.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 ${gr}. 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 ${Xd} 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: ${Kd.join(", ")}.`,`color is one of: ${dr.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(`
319
- `)}function Bt(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function lt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var dt=(e,o,t)=>Math.min(t,Math.max(o,e)),Yd=e=>dt(lt(e)??1,.1,1),zf=/^#[0-9a-f]{6}$/i;function Vf(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))dr.includes(t)&&typeof n=="string"&&zf.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function Yf(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,Xd)){if(!Array.isArray(t))return null;let n=lt(t[0]),s=lt(t[1]);if(n===null||s===null)return null;o.push([dt(n,0,Je.w),dt(s,0,Je.h)])}return o.length>=2?o:null}function Zd(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=Vf(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Bt(n.color,dr,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=Yf(n.path),g=Bt(n.fill,Vd,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:Yd(n.opacity)}}let a=lt(n.x),c=lt(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:dt(a,0,Je.w-20),y:dt(c,0,Je.h-20),size:Bt(n.size,Hf,"l"),color:r,font:Bt(n.font,Gf,"draw")};if(typeof n.geo=="string"){let l=lt(n.w),g=lt(n.h);if(l===null||g===null||l<4||g<4)return null;let d=dt(a,0,Je.w-4),u=dt(c,0,Je.h-4);return{kind:"geo",id:s,say:i,geo:Bt(n.geo,Kd,"rectangle"),x:d,y:u,w:Math.min(l,Je.w-d),h:Math.min(g,Je.h-u),color:r,fill:Bt(n.fill,Vd,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:Yd(n.opacity)}}return null}var Ps=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
320
- `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var Kf=500,Xf=e=>`
321
- editor.zoomToBounds({ x: 0, y: 0, w: ${Je.w}, h: ${Je.h} }, { inset: ${e}, immediate: true })
322
- const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${Je.w}, y: 0 })
311
+ `),Us=Pf(Df(),".agentx","paste-undo.txt");function Lf(e){try{_f(Mf(Us),{recursive:!0}),Bd(Us,e,{mode:384})}catch{}}function qf(){try{let e=Rf(Us,"utf-8");return Bd(Us,"",{mode:384}),e.length?e:null}catch{return null}}async function Uf(){let{stdout:e}=await hr("pbpaste",[],{maxBuffer:16777216});return e}async function Gd(e){await new Promise((o,t)=>{Wd("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Ff(){if(!Nf(De))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await hr(De,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Wf(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Wf(e,o){return{AXTextField:"a single-line text field",AXTextArea:"a multi-line text area",AXSearchField:"a search field",AXComboBox:"a combo box",AXSecureTextField:"a password field"}[e]??(o?"an editable control":`a ${e||"unknown"} control`)}import{Command as Bf}from"commander";import Je from"chalk";ee();function zd(e,o,t={}){let n={shot:null,error:"no banner was shown (held for Focus, or the banner is off)"};return{alert:async(s,i)=>{let{shot:r,error:a}=await bs(()=>e(s,i),o,{},t);n=r?.timedOut&&!r.changed?{shot:r,error:"the banner region did not change \u2014 Do Not Disturb, or notifications not allowed"}:{shot:r,error:a}},proof:()=>n}}var Jf=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function Hf(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
312
+ ${n}`:n,a=await fetch(`${Jf}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s??e,chatId:i??o,text:r})});if(!a.ok)throw new Error(`daemon ${a.status}: ${(await a.text().catch(()=>"")).slice(0,200)}`)}}function Gf(e){let o;try{o=O(e.config)}catch{o=void 0}let t=ms(o?.notifications.local);e.sound||(t.sound=!1),e.banner||(t.banner=!1);let n=e.channel??ps(o);return{alert:Sc(t),banner:t.banner,channel:n}}var Yd=new Bf().name("notify").description("tell the operator something, holding it if they are in Focus").argument("[message]","what to say").option("--from <who>","who is speaking","agentx").option("--title <text>","notification title","AgentX").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel (default: notifications.channel, else push when it is on, else ntfy)").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").option("--no-banner","do not show a banner on this machine").option("-c, --config <path>","agentx.json to read local settings from (default: ./agentx.json)").option("--proof","capture the banner as it shows and print the frame's path").option("--status","show Focus state and anything being held").option("--flush","deliver everything held, as one message").option("--json","emit the result as JSON").action(async(e,o)=>{let t=new uc,n=Va(),{alert:s,banner:i,channel:r}=Gf(o),a=s,c;if(o.proof&&!i)c=()=>({shot:null,error:"the banner is off, so there is nothing to capture"});else if(o.proof){let g=fo(o.config),d=zd(s,$s("notifications",g),{settings:g});a=d.alert,c=d.proof}if(o.status){let g=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:g},null,2));return}console.log(` ${n.active?Je.yellow("\u25D0"):Je.green("\u25CB")} ${Ka(n)} ${Je.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(Je.dim(` ${u} ${d.from}: ${d.message.slice(0,70)}`))}return}let l=Hf(r,o.chatId);if(o.flush){let g=await Tc(l,{queue:t,alert:s});console.log(g?Je.green(` delivered ${g} held notification(s)`):Je.dim(" nothing was held"));return}e?.trim()||(console.log(Je.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let g=await Ac({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:r,chatId:o.chatId},l,{queue:t,alert:a,focus:n}),d=c?.();if(o.json){console.log(JSON.stringify(d?{...g,proof:d}:g,null,2));return}let u=g.delivered?Je.green("\u2192"):Je.yellow("\u23F8");console.log(` ${u} ${g.reason}`),g.held&&console.log(Je.dim(" it will arrive with the others when Focus ends")),d?.shot&&console.log(` ${d.error?Je.yellow("?"):Je.green("\u2713")} banner: ${d.shot.path}${Je.dim(` \xB7 ${d.shot.waitedMs}ms`)}`),d?.error&&console.log(Je.yellow(` ${d.error}`))}catch(g){console.log(Je.red(` ${g?.message??g}`)),await s(o.title,e.trim()),process.exit(1)}});import{Command as Bt}from"commander";import co from"chalk";var Vd=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";async function lo(e,o,t,n={}){let s=process.env.MESH_TOKEN,i=await fetch(`${Vd}${o}`,{method:e,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...n},body:t===void 0?void 0:JSON.stringify(t)}).catch(a=>{throw new Error(`daemon not reachable at ${Vd}: ${a?.message??a}`)}),r=await i.json().catch(()=>({}));if(!i.ok)throw new Error(r?.error||`daemon ${i.status}`);return r}function zf(e,o,t){e.calls=e.calls??{};let n=Array.isArray(e.calls.allow)?e.calls.allow:[],s=n.includes(o);return t===s?`${o} is ${t?"already":"not"} in calls.allow`:(e.calls.allow=t?[...n,o]:n.filter(i=>i!==o),t?`${o} may now call you`:`${o} may no longer call you`)}function wr(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?co.yellow("missed"):e.status==="ringing"?co.green("ringing"):co.dim(e.status),n=e.note?co.dim(` (${e.note})`):"";return` ${co.dim(e.id)} ${o} ${e.agentId} ${t}${n}
313
+ ${e.reason}${e.summary?co.dim(`
314
+ summary: ${e.summary}`):""}`}async function Ln(e){try{await e()}catch(o){console.log(co.red(` ${o?.message??o}`)),process.exit(1)}}var Yf=new Bt("request").description("ask the owner for a live voice call (rings AgentX Voice); runs inside an agent's turn").requiredOption("--reason <text>","why, in one line: said aloud when they answer").option("--urgent","ring even during Focus").option("--json","print the call as JSON").action(e=>Ln(async()=>{let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error("no agent: calls are placed from inside an agent's run, which sets AGENTX_AGENT_ID");let t=await lo("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal"},bn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang==="widget"?"ringing on AgentX Voice":t.rang==="notify"?"AgentX Voice is not running; sent a notification instead":`not rung: ${t.call.note??"held"} \u2014 it is listed as a missed call`;console.log(` ${t.rang?co.green("\u260E"):co.yellow("\u23F8")} ${t.call.id} ${n}`)})),Vf=new Bt("list").description("recent calls, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed, later (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Ln(async()=>{let o=new URLSearchParams({limit:String(e.limit)});e.status&&o.set("status",e.status);let{calls:t}=await lo("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(co.dim(" no calls"));return}for(let n of t)console.log(wr(n))}));function yr(e,o){return new Bt(e).description(o).argument("<id>","call id, from `agentx call list`").action(t=>Ln(async()=>{let{call:n}=await lo("POST",`/calls/${encodeURIComponent(t)}/${e}`,{});console.log(wr(n))}))}var Kf=new Bt("later").description("ring again in N minutes").argument("<id>","call id").argument("[minutes]","minutes from now","10").action((e,o)=>Ln(async()=>{let{call:t}=await lo("POST",`/calls/${encodeURIComponent(e)}/later`,{minutes:Number(o)});console.log(wr(t))}));function Kd(e,o){return new Bt(e).description(o?'let an agent call you ("*" for every agent)':"stop an agent calling you").argument("<agent>",'agent id, or "*"').option("-c, --config <path>","agentx.json to edit (default: ./agentx.json)").action((t,n)=>Ln(()=>{let{summary:s}=eo(i=>zf(i,t,o),{configPath:n.config});console.log(co.green(` ${s}`))}))}var Xd=new Bt("call").description("agents ring you for a live voice call").addCommand(Yf).addCommand(Vf).addCommand(yr("answer","pick up a ringing call (AgentX Voice does this for you)")).addCommand(yr("decline","decline a ringing call")).addCommand(Kf).addCommand(yr("hangup","end an answered call")).addCommand(Kd("allow",!0)).addCommand(Kd("disallow",!1));import{Command as dt}from"commander";import Ye from"chalk";function Qd(e){let o=new Date(e.createdAt).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),t=e.status==="missed"?Ye.yellow("missed"):e.status==="ringing"?Ye.green("asking"):e.status==="answered"?Ye.green("showing"):Ye.dim(e.status),n=e.note?Ye.dim(` (${e.note})`):"";return` ${Ye.dim(e.id)} ${o} ${e.agentId} ${t}${n}
315
+ ${e.reason}`}async function Jt(e){try{await e()}catch(o){console.log(Ye.red(` ${o?.message??o}`)),process.exit(1)}}function Zd(e){let o=process.env.AGENTX_AGENT_ID;if(!o)throw new Error(`no agent: ${e} happens from inside an agent's run, which sets AGENTX_AGENT_ID`);return o}var Xf=new dt("ask").description("ask the owner to show you their phone camera; runs inside an agent's turn").requiredOption("--reason <text>","what you want to see, in one line: shown on the phone").option("--urgent","ask even during Focus").option("--json","print the ask as JSON").action(e=>Jt(async()=>{let o=Zd("a camera ask"),t=await lo("POST","/calls",{agentId:o,reason:e.reason,urgency:e.urgent?"urgent":"normal",kind:"camera"},bn());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.rang?"the owner's phone was told; when they tap Show, use `agentx camera look` for the newest picture":`not asked now: ${t.call.note??"held"} \u2014 it is listed as missed`;console.log(` ${t.rang?Ye.green("\u{1F4F7}"):Ye.yellow("\u23F8")} ${t.call.id} ${n}`)})),Qf=new dt("look").description("the newest picture from the owner's camera, as a PNG path to open; runs inside an agent's turn").option("--json","print the frame as JSON").action(e=>Jt(async()=>{let o=Zd("a look"),t=await lo("POST","/webrtc/camera/look",{agentId:o},bn());if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(` ${t.frame.path}`),console.log(Ye.dim(` ${t.frame.width}x${t.frame.height}, taken ${new Date(t.frame.takenAt).toLocaleTimeString()} (share ${t.callId})`))})),Zf=new dt("list").description("recent camera asks, newest first").option("--status <list>","only these: ringing, answered, ended, declined, missed (comma-separated)").option("--limit <n>","how many","20").option("--json","print as JSON").action(e=>Jt(async()=>{let o=new URLSearchParams({limit:String(e.limit),kind:"camera"});e.status&&o.set("status",e.status);let{calls:t}=await lo("GET",`/calls?${o}`);if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(Ye.dim(" no camera asks"));return}for(let n of t)console.log(Qd(n))})),eh=new dt("watching").description("agents watching a phone camera right now").option("--json","print as JSON").action(e=>Jt(async()=>{let{active:o}=await lo("GET","/webrtc/camera/watch");if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(Ye.dim(" no agent is watching a camera"));return}for(let t of o){let n=Math.max(0,Math.round((t.until-Date.now())/6e4));console.log(` ${Ye.dim(t.callId)} ${t.agentId} ${t.frames} frames, ${t.looks} looks, ${n} min left`)}})),oh=new dt("decline").description("turn down a camera ask").argument("<id>","ask id, from `agentx camera list`").action(e=>Jt(async()=>{let{call:o}=await lo("POST",`/calls/${encodeURIComponent(e)}/decline`,{});console.log(Qd(o))})),th=new dt("stop").description("end a live watch (the share id from `agentx camera watching`)").argument("<id>","share id").action(e=>Jt(async()=>{await lo("POST",`/webrtc/camera/watch/${encodeURIComponent(e)}/stop`,{}),console.log(Ye.green(` ${e} stopped`))})),eg=new dt("camera").description("agents ask to see through your phone camera").addCommand(Xf).addCommand(Qf).addCommand(Zf).addCommand(eh).addCommand(oh).addCommand(th);wn();Aa();ma();yn();import{Command as nh}from"commander";import{readFileSync as sh}from"fs";var og=new nh().name("decide").description("ask a typed question about some state and get a calibrated answer back").option("--file <path>","spec JSON file (default: stdin)").option("--backend <name>","decision backend","typesafe").option("--seat <name>","seat name the answers are recorded under","adhoc").option("--no-record","answer without writing a row").option("--timeout <ms>","abandon the call after this long","20000").action(async e=>{let o;try{o=e.file?sh(e.file,"utf8"):await ih()}catch(r){gt(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return gt("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return gt(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return gt("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return gt("spec needs at least one entry in `questions`");try{ba(t.questions)}catch(r){return gt(r?.message??String(r))}let n=t.seat||e.seat;kt(),process.env[Oa(n)]="active";let s=null;if(e.record!==!1)try{s=new ts({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
316
+ `)}Ta({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await uo(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return gt(`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 gt(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function ih(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}wn();import{Command as Ph}from"commander";import{execFile as Mh,spawn as hg}from"child_process";import{promisify as Lh}from"util";import{existsSync as qh,statSync as Uh}from"fs";import{join as yg}from"path";import{tmpdir as Fh}from"os";import te from"chalk";var rh={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."}]},ah={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."}]},ch={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."}]},$r=[rh,ah,ch];ee();ee();import go from"chalk";import{execFile as lh}from"child_process";import{promisify as dh}from"util";import{createInterface as gh}from"readline";var tg=dh(lh);function mh(e){e.type==="step"?console.log(`${go.cyan(` ${e.n}. ${e.action}`)}${e.target?go.dim(` "${e.target}"`):""} ${e.say}`):e.type==="changed"?console.log(go.dim(` ${e.changed?"screen changed":"no change"}`)):e.type==="acted"?console.log(e.error?go.red(` failed: ${e.error}`):go.dim(" done it")):e.type==="replanned"?console.log(go.yellow(` screen changed, looking again: ${e.reason}`)):e.type==="door"?console.log(go.cyan(` you: ${e.text}`)):e.type==="error"?console.log(go.red(` error: ${e.error}`)):e.type==="end"&&console.log(go.dim(` \xB7 ended (${e.reason})`))}async function ph(e,o){let t=Date.now()+o;for(let n=0;Date.now()<t;n++){n&&n%10===0&&await tg("open",["-a",e]).catch(()=>{});try{let s=(await qi()).app;if(s.toLowerCase()===e.replace(/\.app$/i,"").toLowerCase())return s}catch{}await new Promise(s=>setTimeout(s,500))}return null}async function ng(e,o){let t=O(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=["teach","watch","act"].includes(o.mode??"")?o.mode:"teach",i;if(o.app&&(await tg("open",["-a",o.app]),i=await ph(o.app,15e3)??void 0,!i))throw new Error(`${o.app} did not come to the front`);let r=hs(n,t.agents,!1),a=t.voice.listener??dl,c=Ct(n,t.agents[n]),l=new pl({goal:e,app:i,mode:s,speaker:r,actionsAllowed:c.allowActions,maxSteps:Number(o.steps)||void 0,listener:a},{readScreen:qi,presence:new ys(c,De,n),speech:new jt,model:It({system:ml(r.persona,a)}),act:ul});l.on(mh),console.log(go.bold(`
317
+ ${c.name} teaches: ${e}`)+go.dim(` (${s}${s==="act"&&!c.allowActions?", actions not allowed":""}; type to cut in, "stop" to end)
318
+ `));let g=gh({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close()}ee();import mo from"chalk";import{execFile as Th}from"child_process";import{existsSync as vr,writeFileSync as Oh}from"fs";import{homedir as Ch}from"os";import{join as ug,resolve as jh}from"path";import{promisify as Ih}from"util";var He={w:1e3,h:640},br=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],rg=["rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","cloud","heart"],sg=["none","semi","solid","fill","pattern"],kr=180,ag=48,uh=["s","m","l","xl"],fh=["draw","sans","serif","mono"];function cg(){return[`You are an illustrator drawing on a tldraw canvas ${He.w} wide and ${He.h} tall (x right, y down, origin top-left).`,`Reply with JSON Lines only: one element per line, no prose, no code fences. Scale the number of elements to the brief: a quick sketch needs 10 to 20, a finished, ambitious piece up to ${kr}. 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 ${ag} 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: ${rg.join(", ")}.`,`color is one of: ${br.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(`
319
+ `)}function Ht(e,o,t){return typeof e=="string"&&o.includes(e)?e:t}function mt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}var pt=(e,o,t)=>Math.min(t,Math.max(o,e)),ig=e=>pt(mt(e)??1,.1,1),hh=/^#[0-9a-f]{6}$/i;function yh(e){if(!e||typeof e!="object")return null;let o={};for(let[t,n]of Object.entries(e))br.includes(t)&&typeof n=="string"&&hh.test(n)&&(o[t]=n);return Object.keys(o).length?o:null}function wh(e){if(!Array.isArray(e))return null;let o=[];for(let t of e.slice(0,ag)){if(!Array.isArray(t))return null;let n=mt(t[0]),s=mt(t[1]);if(n===null||s===null)return null;o.push([pt(n,0,He.w),pt(s,0,He.h)])}return o.length>=2?o:null}function lg(e,o){let t=e.trim().replace(/,$/,"");if(!t.startsWith("{"))return null;let n;try{n=JSON.parse(t)}catch{return null}if("palette"in n){let l=yh(n.palette);return!l||o.has("palette")?null:{kind:"palette",id:"palette",say:typeof n.say=="string"?n.say.slice(0,80):"",colors:l}}let s=typeof n.id=="string"&&n.id?n.id.slice(0,40):null;if(!s||o.has(s))return null;let i=typeof n.say=="string"?n.say.slice(0,80):"",r=Ht(n.color,br,"black");if(Array.isArray(n.arrow)){let[l,g]=n.arrow;return typeof l!="string"||typeof g!="string"||!o.has(l)||!o.has(g)||l===g?null:{kind:"arrow",id:s,say:i,from:l,to:g,label:typeof n.label=="string"?n.label.slice(0,40):"",color:r}}if("path"in n){let l=wh(n.path),g=Ht(n.fill,sg,"fill");return!l||g!=="none"&&l.length<3?null:{kind:"path",id:s,say:i,pts:l,color:r,fill:g,opacity:ig(n.opacity)}}let a=mt(n.x),c=mt(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:pt(a,0,He.w-20),y:pt(c,0,He.h-20),size:Ht(n.size,uh,"l"),color:r,font:Ht(n.font,fh,"draw")};if(typeof n.geo=="string"){let l=mt(n.w),g=mt(n.h);if(l===null||g===null||l<4||g<4)return null;let d=pt(a,0,He.w-4),u=pt(c,0,He.h-4);return{kind:"geo",id:s,say:i,geo:Ht(n.geo,rg,"rectangle"),x:d,y:u,w:Math.min(l,He.w-d),h:Math.min(g,He.h-u),color:r,fill:Ht(n.fill,sg,"solid"),label:typeof n.label=="string"?n.label.slice(0,40):"",opacity:ig(n.opacity)}}return null}var Fs=class{buf="";push(o){this.buf+=o;let t=this.buf.split(`
320
+ `);return this.buf=t.pop()??"",t}flush(){let o=this.buf;return this.buf="",o.trim()?[o]:[]}};var $h=500,bh=e=>`
321
+ editor.zoomToBounds({ x: 0, y: 0, w: ${He.w}, h: ${He.h} }, { inset: ${e}, immediate: true })
322
+ const o = editor.pageToScreen({ x: 0, y: 0 }), e = editor.pageToScreen({ x: ${He.w}, y: 0 })
323
323
  const chrome = window.outerHeight - window.innerHeight
324
- return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${Je.w} }`;function eg(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function og(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function Qf(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function tg(e){return`const hex = ${JSON.stringify(e.colors)}
324
+ return { ox: window.screenX + o.x, oy: window.screenY + chrome + o.y, scale: (e.x - o.x) / ${He.w} }`;function dg(e,o,t,n=0,s=0){return{x:e.ox+o*e.scale,y:e.oy+t*e.scale,width:n*e.scale,height:s*e.scale}}function gg(e){let o={s:18,m:24,l:32,xl:44}[e.size]??32;return{x:e.x,y:e.y,w:e.text.length*o*.6,h:o*1.3}}function kh(e){let o=e.map(i=>i[0]),t=e.map(i=>i[1]),n=Math.min(...o),s=Math.min(...t);return{x:n,y:s,w:Math.max(...o)-n,h:Math.max(...t)-s}}function mg(e){return`const hex = ${JSON.stringify(e.colors)}
325
325
  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('')
326
326
  const th = editor.getTheme('default')
327
327
  const colors = structuredClone(th.colors)
@@ -329,9 +329,9 @@ for (const mode of Object.keys(colors)) for (const [name, v] of Object.entries(h
329
329
  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 })
330
330
  }
331
331
  editor.updateTheme({ ...th, colors })
332
- return true`}function Zf(e,o){if(e.kind==="palette")return tg(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
332
+ return true`}function vh(e,o){if(e.kind==="palette")return mg(e);let t=s=>JSON.stringify(`${o}-${s}`),n=`const { createShapeId, toRichText } = await import('tldraw')
333
333
  const el = ${JSON.stringify(e)}
334
- const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round(Kf/10)}))
334
+ const frames = 10, wait = () => new Promise((r) => setTimeout(r, ${Math.round($h/10)}))
335
335
  const ease = (t) => 1 - Math.pow(1 - t, 3)`;return e.kind==="geo"?`${n}
336
336
  const id = createShapeId(${t(e.id)})
337
337
  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' } })
@@ -371,83 +371,93 @@ return id`:`${n}
371
371
  const arrow = helpers.createArrowBetweenShapes(createShapeId(${t(e.from)}), createShapeId(${t(e.to)}), el.label ? { richText: toRichText(el.label) } : {})
372
372
  const aid = typeof arrow === 'string' ? arrow : arrow?.id
373
373
  if (aid) editor.updateShape({ id: aid, type: 'arrow', props: { color: el.color } })
374
- return aid ?? null`}function eh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[xo(s[0][0],s[0][1]),xo(i[0],i[1])]}if(e.kind==="geo")return[xo(e.x,e.y),xo(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=og(e);return[xo(s.x,s.y+s.h/2),xo(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[xo(t.x+t.w/2,t.y+t.h/2),xo(n.x+n.w/2,n.y+n.h/2)]}var xo=(e,o)=>({x:e,y:o,w:0,h:0});async function ng(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise(v=>setTimeout(v,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,Xf(60)),g=new Set,d=new Map,u=[],f=!1,p=0,h=null,w=null,k=null,b=()=>{k?.(),k=null},$=x=>{if(g.size>=gr)return;let v=Zd(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}),b()},E=(async()=>{let x=new Ps;try{for await(let v of o.model.reply(`Draw: ${e}`,t.signal))x.push(v).forEach($);x.flush().forEach($)}catch(v){w=v?.message??String(v)}finally{p=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let v=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,tg(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-v});continue}let[R,I]=eh(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(eg(l,R.x,R.y)),await s(250),o.presence.moveTo(eg(l,I.x,I.y));try{await o.api.exec(t.docId,Zf(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"?og(x):x.kind==="path"?Qf(x.pts):xo(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-v});let C=(x.say?r:0)-(i()-v);C>0&&await s(C)}return await E,w&&n({type:"error",error:`plan: ${w}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:h,planMs:p}}import{readFileSync as oh}from"fs";import{homedir as th}from"os";import{join as nh}from"path";var Dn=nh(th(),"Library","Application Support","tldraw","server.json"),Ms=class{constructor(o=Dn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=oh(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var lh=ch(sh),dh="claude-sonnet-5";function gh(e){e.type==="planned"?console.log(go.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${go.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${go.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(go.yellow(` skipped: ${e.line}`)):console.log(go.red(` error: ${e.error}`))}async function mh(){if(!mr(Dn)){await lh("open",["-a","tldraw offline"]);for(let e=0;e<40&&!mr(Dn);e++)await new Promise(o=>setTimeout(o,500));if(!mr(Dn))throw new Error("tldraw offline did not start")}}async function ig(e,o){let t=j(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||dh,i=ah(o.out||sg(rh(),"Documents")),r=Tt(n,t.agents[n]),a=Ct({system:Qd(),model:s}),c=new ms(r,De,n),l=new Ms;try{await mh();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(go.bold(`
375
- ${r.name} draws: ${e}`)+go.dim(` (${s}, ${d.filePath})
376
- `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await ng(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},gh);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"):sg(i,`agentx-draw-${g}.png`);ih(h,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(go.bold(`
377
- ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+go.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(go.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(go.dim(` ${d.filePath}
374
+ return aid ?? null`}function xh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.floor(s.length/2)];return[So(s[0][0],s[0][1]),So(i[0],i[1])]}if(e.kind==="geo")return[So(e.x,e.y),So(e.x+e.w,e.y+e.h)];if(e.kind==="text"){let s=gg(e);return[So(s.x,s.y+s.h/2),So(s.x+s.w,s.y+s.h/2)]}let t=o.get(e.from),n=o.get(e.to);return[So(t.x+t.w/2,t.y+t.h/2),So(n.x+n.w/2,n.y+n.h/2)]}var So=(e,o)=>({x:e,y:o,w:0,h:0});async function pg(e,o,t,n=()=>{}){let s=o.sleep??(x=>new Promise(v=>setTimeout(v,x))),i=o.now??Date.now,r=t.stepMs??1500,a=t.runTag??i().toString(36),c=i(),l=await o.api.exec(t.docId,bh(60)),g=new Set,d=new Map,u=[],f=!1,p=0,h=null,w=null,k=null,b=()=>{k?.(),k=null},$=x=>{if(g.size>=kr)return;let v=lg(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}),b()},E=(async()=>{let x=new Fs;try{for await(let v of o.model.reply(`Draw: ${e}`,t.signal))x.push(v).forEach($);x.flush().forEach($)}catch(v){w=v?.message??String(v)}finally{p=i()-c,f=!0,b()}})(),S=0;for(;!t.signal?.aborted;){let x=u.shift();if(!x){if(f)break;await new Promise(P=>{k=P});continue}if(x.kind==="arrow"&&!(d.has(x.from)&&d.has(x.to))){n({type:"error",error:`${x.id}: an end was not drawn`});continue}let v=i();if(x.kind==="palette"){x.say&&o.presence.say(x.say);try{await o.api.exec(t.docId,mg(x))}catch(P){n({type:"error",error:`palette: ${P?.message??P}`});continue}S++,n({type:"drawn",n:S,el:x,ms:i()-v});continue}let[R,I]=xh(x,d);x.say&&o.presence.say(x.say),o.presence.moveTo(dg(l,R.x,R.y)),await s(250),o.presence.moveTo(dg(l,I.x,I.y));try{await o.api.exec(t.docId,vh(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"?gg(x):x.kind==="path"?kh(x.pts):So(0,0)),S++,n({type:"drawn",n:S,el:x,ms:i()-v});let j=(x.say?r:0)-(i()-v);j>0&&await s(j)}return await E,w&&n({type:"error",error:`plan: ${w}`}),o.presence.park(),{steps:S,totalMs:i()-c,firstLineMs:h,planMs:p}}import{readFileSync as Sh}from"fs";import{homedir as Eh}from"os";import{join as Ah}from"path";var qn=Ah(Eh(),"Library","Application Support","tldraw","server.json"),Ws=class{constructor(o=qn,t=fetch){this.serverJson=o;this.fetchFn=t}server(){let o;try{o=Sh(this.serverJson,"utf8")}catch{throw new Error("tldraw offline is not running (no server.json)")}let{port:t,token:n}=JSON.parse(o);return{port:t,token:n}}async post(o,t){let{port:n,token:s}=this.server(),i=await this.fetchFn(`http://localhost:${n}${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify(t)}),r=await i.json();if(!i.ok||r.success===!1)throw new Error(`tldraw ${o}: ${r.error??i.status}`);return r.result}createDoc(o,t){return this.post("/api/docs/create",{name:o,...t?{directory:t}:{}})}exec(o,t){return this.post(`/api/doc/${o}/exec`,{code:t})}search(o){return this.post("/api/search",{code:o})}};var Nh=Ih(Th),Rh="claude-sonnet-5";function _h(e){e.type==="planned"?console.log(mo.dim(` planned ${e.n}: ${e.el.kind} ${e.el.id} at ${(e.atMs/1e3).toFixed(1)} s`)):e.type==="drawn"?console.log(`${mo.cyan(` ${e.n}. ${e.el.kind} ${e.el.id}`)} ${e.el.say}${mo.dim(` (${(e.ms/1e3).toFixed(1)} s)`)}`):e.type==="skipped"?console.log(mo.yellow(` skipped: ${e.line}`)):console.log(mo.red(` error: ${e.error}`))}async function Dh(){if(!vr(qn)){await Nh("open",["-a","tldraw offline"]);for(let e=0;e<40&&!vr(qn);e++)await new Promise(o=>setTimeout(o,500));if(!vr(qn))throw new Error("tldraw offline did not start")}}async function fg(e,o){let t=O(o.config),n=o.agent||process.env.AGENTX_VOICE_AGENT||t.node.defaultAgent;if(!n||!t.agents[n])throw new Error(`Unknown agent: ${n}`);let s=o.model||Rh,i=jh(o.out||ug(Ch(),"Documents")),r=Ct(n,t.agents[n]),a=It({system:cg(),model:s}),c=new ys(r,De,n),l=new Ws;try{await Dh();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(mo.bold(`
375
+ ${r.name} draws: ${e}`)+mo.dim(` (${s}, ${d.filePath})
376
+ `));let u=new AbortController;process.once("SIGINT",()=>u.abort());let f=await pg(e,{api:l,presence:c,model:a},{docId:d.id,signal:u.signal},_h);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"):ug(i,`agentx-draw-${g}.png`);Oh(h,Buffer.from(p.slice(p.indexOf(",")+1),"base64")),console.log(mo.bold(`
377
+ ${f.steps} steps in ${(f.totalMs/1e3).toFixed(1)} s`)+mo.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(mo.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(mo.dim(` ${d.filePath}
378
378
  ${h}
379
- `))}finally{a.close(),c.close()}}var ur=fh(uh),cg=new ph().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, "${_o}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await ig(String(o.live),o):await zd(String(o.live),o),process.exit(0)}catch(g){console.log(oe.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(oe.bold(`
379
+ `))}finally{a.close(),c.close()}}var Sr=Lh(Mh),wg=new Ph().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, "${Po}" for the OS default, or ElevenLabs voice id (overrides the agent's)`).option("--agent <id>","speak in this agent's voice (default: AGENTX_VOICE_AGENT or node.defaultAgent)").option("--no-speak","point only, print the narration").option("--no-hud","skip the on-screen callout").option("--record","record the screen (screencapture) around the lesson").option("--record-dir <path>","where to write the recording").option("--live <goal>","no lesson: the agent reads the screen and teaches this, step by step").option("--mode <mode>","with --live: teach (you do each step), watch (you drive, it coaches) act (it does it, if allowed) or draw (plans a tldraw offline illustration in one model turn and draws it)").option("--app <name>","with --live: open this app first").option("-c, --config <path>","with --live: agentx.json to read the agent from").option("--steps <n>","with --live: most steps before it stops (default 12)").option("--model <id>","with --mode draw: the planning model (default claude-sonnet-5)").option("--out <dir>","with --mode draw: where the .tldraw file and the picture go (default ~/Documents)").action(async(e,o)=>{if(o.live)try{o.mode==="draw"?await fg(String(o.live),o):await ng(String(o.live),o),process.exit(0)}catch(g){console.log(te.red(` ${g?.message??g}`)),process.exit(1)}if(!e){console.log(te.bold(`
380
380
  lessons
381
- `));for(let g of lr)console.log(` ${oe.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${oe.dim(g.appHint)}
382
- `);return}let t=lr.find(g=>g.id===e);t||(console.log(oe.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),hh(De)||(console.log(oe.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:kh(o.voice,o.agent);console.log(oe.bold(`
383
- ${t.title}`)),console.log(oe.dim(` ${t.appHint}
384
- `));try{t.start&&(await ur("/usr/bin/open",$h(t.start)),await Jo(2e3),await Ls(t.start.ready))}catch(g){console.log(oe.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=ag(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(oe.dim(` recording \u2192 ${i}`)),s=rg("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Jo(2e3));let r=o.hud===!1?null:rg(De,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
385
- `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${oe.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await Ls(d.before)}let u=o.speak===!1?Promise.resolve():xh(d.say,n),f=d.find?await bh(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${d.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await ur(De,["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 pr(["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(oe.yellow(" \xB7 clicked, but the screen did not change")),await Jo(d.afterClickWaitMs??1500)}if(d.type){await Ls(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await pr(["type","--text",d.type]);if(p)throw console.log(oe.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 Ls(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await pr(["key","--name",d.key]);if(p)throw console.log(oe.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 Jo((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Jo(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),h;try{h=await Nn(d.verify,p?{settle:!0,screen:uo()}:{})}catch(w){h=null,console.log(oe.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"?oe.green("\u2713"):h.outcome==="refuted"?oe.red("\u2717"):oe.yellow("?");if(console.log(` ${w} ${oe.dim(h.reason)}`),!h.ok&&!d.verifyOptional){a("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(oe.red(`
386
- stopping: could not confirm \u2014 ${d.verify}`)),console.log(oe.dim(` ${h.reason}`)),console.log(oe.dim(` screenshot: ${h.sighting.shot.path}`)),await Jo(2500);try{r?.stdin?.end()}catch{}l=!0;break}}}}}catch(g){l=!0,console.log(oe.red(` stopping: ${g?.message??g}`)),a("Stopped",String(g?.message??g),"waiting")}finally{if(l)try{r?.stdin?.end()}catch{}}if(!l){a("Done",t.title,"done"),await Jo(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Jo(2500);try{let{size:g}=yh(i);console.log(oe.green(` recorded ${(g/1048576).toFixed(1)} MB \u2192 ${i}`))}catch{console.log(oe.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(l){console.log(oe.red(` lesson stopped before the end.
387
- `)),process.exitCode=3;return}console.log(oe.green(`
381
+ `));for(let g of $r)console.log(` ${te.cyan(g.id.padEnd(22))} ${g.title}`),console.log(` ${" ".repeat(22)} ${te.dim(g.appHint)}
382
+ `);return}let t=$r.find(g=>g.id===e);t||(console.log(te.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),qh(De)||(console.log(te.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let n=o.speak===!1?void 0:Jh(o.voice,o.agent);console.log(te.bold(`
383
+ ${t.title}`)),console.log(te.dim(` ${t.appHint}
384
+ `));try{t.start&&(await Sr("/usr/bin/open",Wh(t.start)),await Go(2e3),await Bs(t.start.ready))}catch(g){console.log(te.red(` setup stopped: ${g?.message??g}`)),process.exitCode=3;return}let s=null,i=null;o.record&&(i=yg(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(te.dim(` recording \u2192 ${i}`)),s=hg("/usr/sbin/screencapture",["-v","-x","-C",i],{stdio:["pipe","ignore","ignore"]}),await Go(2e3));let r=o.hud===!1?null:hg(De,["hud"],{stdio:["pipe","ignore","ignore"]}),a=(g,d,u,f)=>{try{r?.stdin?.write(JSON.stringify({title:g,body:d,state:u,avoid:f})+`
385
+ `)}catch{}},c=[],l=!1;try{for(let[g,d]of t.steps.entries()){if(console.log(` ${te.dim(String(g+1).padStart(2))} ${d.say}`),a(`Step ${g+1} of ${t.steps.length}`,d.say,"talking"),d.click||d.type||d.key){if(!d.before)throw new Error(`Step ${g+1} needs a before claim`);await Bs(d.before)}let u=o.speak===!1?Promise.resolve():Gh(d.say,n),f=d.find?await Bh(d.find,c):null;if(d.find&&!f)throw c.push({tried:d.find,changed:!1,note:"not found on screen"}),await u,new Error(`Could not find "${d.find}"; stopped before acting`);if(await u,f&&(a(`Step ${g+1} of ${t.steps.length}`,d.say,"pointing",{x:f.x,y:f.y,w:f.width,h:f.height}),await Sr(De,["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 xr(["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 Go(d.afterClickWaitMs??1500)}if(d.type){await Bs(d.before),a(`Step ${g+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await xr(["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 Bs(d.before),a(`Step ${g+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await xr(["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 Go((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await Go(d.holdSeconds*1e3),d.verify){a(`Step ${g+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p=!!(d.click||d.type||d.key),h;try{h=await Pn(d.verify,p?{settle:!0,screen:fo()}:{})}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(`
386
+ stopping: could not confirm \u2014 ${d.verify}`)),console.log(te.dim(` ${h.reason}`)),console.log(te.dim(` screenshot: ${h.sighting.shot.path}`)),await Go(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",t.title,"done"),await Go(1200);try{r?.stdin?.end()}catch{}}if(s&&i){s.kill("SIGINT"),await Go(2500);try{let{size:g}=Uh(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.
387
+ `)),process.exitCode=3;return}console.log(te.green(`
388
388
  done.
389
- `))});function $h(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${ag(wh(),"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 Ls(e){let o=await Nn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function pr(e){try{let{stdout:o}=await ur(De,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function bh(e,o=[]){try{let t=await ps({max:45});if(t.candidates.length<2)return null;let n=await po(jn,js({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Is(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Ns(n.answers,t.candidates);return s.present<.5?null:kn(t,s.id)}catch{return null}}function kh(e,o){if(e?.trim().toLowerCase()===_o)return{provider:"system",elevenlabs:bn(),system:null,fallback:!0};let t=e?ds(e,$n()):null;if(t)return{provider:"system",elevenlabs:bn(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=j(),s=o||process.env.AGENTX_VOICE_AGENT||n.node.defaultAgent;return s&&!n.agents[s]&&console.log(oe.yellow(` no agent "${s}" in agentx.json \u2014 using the default voice`)),s&&n.agents[s]?Hc(Bc(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:bn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(oe.dim(` no agent voice (${String(n?.message??n).split(`
390
- `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:bn(),system:null,fallback:!0}}}var vh=new Ot;async function xh(e,o){o&&await vh.say({voice:o,text:e})}var Jo=e=>new Promise(o=>setTimeout(o,e));ne();import{Command as lg}from"commander";import Ve from"chalk";import{createInterface as dg}from"readline";var Sh=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Jt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(Sh()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Eh(e){e.type==="line"?console.log(`${Ve.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ve.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ve.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ve.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ve.dim(" \xB7 hushed")):e.type==="error"?console.log(Ve.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ve.dim(` \xB7 ended (${e.reason})`))}function gg(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function Ah(e,o,t){let n=j(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await Jt("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new Qc(()=>n,()=>d),i.usePool(await Xc(Wc()))}let r=e.map(d=>s[d]?gs(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 el({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new Ot,listener:n.voice.listener,model:(d,u)=>Ct({system:u})});l.on(Eh),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ve.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=dg({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Ve.dim(` ${gg(l.gaps)}`))}async function Th(e,o,t){let n=await Jt("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=dg({input:process.stdin});s.on("line",a=>{a.trim()&&Jt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Jt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Jt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ve.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Ve.dim(` ${gg(r)}`))}var mg=new lg().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?Ah:Th)([e,o],s,n),process.exit(0)}catch(i){console.error(Ve.red(` ${i?.message??i}`)),process.exit(1)}}),pg=new lg().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Ve.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await Jt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ve.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ne();import{Command as Oh}from"commander";import X from"chalk";import{existsSync as Ch,readFileSync as fg,writeFileSync as hg}from"fs";import{resolve as ug}from"path";Km();var Ht=new Oh().name("voice").description("list installed system voices and pick each agent's voice");function fr(e){let o=e?[e]:[ug(process.cwd(),"agentx.json"),ug(process.cwd(),".agentx/config.json")],t=o.find(n=>Ch(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function jh(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=h=>{if(!a){l.system=h;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:h}},f=a?` for ${a}`:"";if(t){let h=t.trim().toLowerCase()===_o,w=h?null:ds(t,s,a??e?.voice?.locale),k=w?`system voice ${Ai(w)}`:"the OS default voice";if((w||h)&&g==="system")u(h?_o:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!h&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||h)u(h?_o:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}Ht.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=$n(),t;try{t=j(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?Jc(t.agents,t.voice,o):new Map;if(t)for(let[a,c]of Object.entries(t.agents)){let l=i.get(a),g=Object.values(Ti(a,c.voice?.system,c.voice?.gender,t.voice,o));for(let d of new Set([l,...g]))d&&s.set(d.id,[...s.get(d.id)??[],a])}if(!o.length)console.log(X.yellow(`
389
+ `))});function Wh(e){return e.cleanWindow?["-na",e.app,"--args",`--user-data-dir=${yg(Fh(),"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 Bs(e){let o=await Pn(e);if(!o.ok)throw new Error(`Not ready: ${e}. ${o.reason}`)}async function xr(e){try{let{stdout:o}=await Sr(De,e),t=JSON.parse(o||"{}");return t.ok===!1?{error:String(t.error??"refused")}:{error:null,changed:t.changed}}catch(o){try{let t=JSON.parse(o?.stdout||"{}");if(t.error)return{error:String(t.error)}}catch{}return{error:o?.message??"failed"}}}async function Bh(e,o=[]){try{let t=await ws({max:45});if(t.candidates.length<2)return null;let n=await uo(_n,Ds({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),Ps(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=Ms(n.answers,t.candidates);return s.present<.5?null:Sn(t,s.id)}catch{return null}}function Jh(e,o){if(e?.trim().toLowerCase()===Po)return{provider:"system",elevenlabs:xn(),system:null,fallback:!0};let t=e?fs(e,vn()):null;if(t)return{provider:"system",elevenlabs:xn(),system:t.id,fallback:!0};if(e)return{provider:"elevenlabs",elevenlabs:e,system:null,fallback:!0};try{let n=O(),s=o||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]?tl(el(s,n.agents,n.voice)):{provider:n.voice.provider,elevenlabs:xn(),system:null,fallback:n.voice.fallback==="system"}}catch(n){return console.log(te.dim(` no agent voice (${String(n?.message??n).split(`
390
+ `)[0]}) \u2014 using the default`)),{provider:"system",elevenlabs:xn(),system:null,fallback:!0}}}var Hh=new jt;async function Gh(e,o){o&&await Hh.say({voice:o,text:e})}var Go=e=>new Promise(o=>setTimeout(o,e));ee();import{Command as $g}from"commander";import Ve from"chalk";import{createInterface as bg}from"readline";var zh=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");async function Gt(e,o,t){let n={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(n.Authorization=`Bearer ${process.env.MESH_TOKEN}`);let s=await fetch(zh()+o,{method:e,headers:n,body:t?JSON.stringify(t):void 0});return{status:s.status,data:await s.json().catch(()=>({}))}}function Yh(e){e.type==="line"?console.log(`${Ve.bold(e.name)}: ${e.text}`):e.type==="gap"?console.log(Ve.dim(` \xB7 ${e.ms} ms between speakers`)):e.type==="door"?console.log(Ve.cyan(` you: ${e.text}`)):e.type==="answered"?console.log(Ve.dim(` \xB7 answered ${e.ms} ms after you spoke`)):e.type==="hush"?console.log(Ve.dim(" \xB7 hushed")):e.type==="error"?console.log(Ve.red(` error: ${e.error}`)):e.type==="end"&&console.log(Ve.dim(` \xB7 ended (${e.reason})`))}function kg(e){if(!e.length)return"no hand-overs measured";let o=[...e].sort((n,s)=>n-s);return`gap between speakers: median ${o[Math.floor(o.length/2)]} ms, max ${o.at(-1)} ms over ${e.length} hand-overs`}async function Vh(e,o,t){let n=O(t.config),s=n.agents,i;if(e.some(d=>!s[d])){let d=await Gt("GET","/mesh").then(u=>Array.isArray(u.data)?u.data:[]).catch(()=>[]);i=new ll(()=>n,()=>d),i.usePool(await cl(Zc()))}let r=e.map(d=>s[d]?hs(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 gl({topic:o,context:t.context,maxTurns:Number(t.turns)||10,speakers:r,speech:new jt,listener:n.voice.listener,model:(d,u)=>It({system:u})});l.on(Yh),l.on(d=>{d.type==="line"&&d.turn===0&&console.log(Ve.dim(` \xB7 first line written ${Date.now()-c} ms after start`))});let g=bg({input:process.stdin});g.on("line",d=>{d.trim()&&l.door(d)}),process.once("SIGINT",()=>l.stop("interrupted")),await l.run(),g.close(),console.log(Ve.dim(` ${kg(l.gaps)}`))}async function Kh(e,o,t){let n=await Gt("POST","/talk",{agents:e,topic:o,context:t.context,maxTurns:Number(t.turns)||void 0});if(n.status>=300)throw new Error(n.data.error||`HTTP ${n.status}`);let s=bg({input:process.stdin});s.on("line",a=>{a.trim()&&Gt("POST","/talk/door",{text:a})}),process.once("SIGINT",()=>void Gt("POST","/talk/stop"));let i=0,r=[];for(;;){let{data:a}=await Gt("GET","/talk"),c=a.transcript??[];for(;i<c.length;i++)console.log(`${Ve.bold(c[i].name)}: ${c[i].text}`);if(r=a.gaps??r,!a.active)break;await new Promise(l=>setTimeout(l,400))}s.close(),console.log(Ve.dim(` ${kg(r)}`))}var vg=new $g().name("talk").description('two agents, local or on a mesh peer, talk a topic through out loud; type to cut in, "stop" to end').argument("<agentA>").argument("<agentB>").argument("<topic...>").option("--context <text>","a few lines of context both agents should know").option("--turns <n>","most lines before they wrap up (default 10)").option("--local","run the talk in this process instead of the daemon").option("-c, --config <path>","agentx.json for --local (default: the usual lookup)").action(async(e,o,t,n)=>{let s=t.join(" ");try{await(n.local?Vh:Kh)([e,o],s,n),process.exit(0)}catch(i){console.error(Ve.red(` ${i?.message??i}`)),process.exit(1)}}),xg=new $g().name("narrate").description("switch spoken task narration on or off for an agent or one task").argument("<target>","agent id, or task id with --task").argument("<state>","on | off | default").option("--task","the target is a task id").action(async(e,o,t)=>{let n=o==="on"?!0:o==="off"?!1:o==="default"?null:void 0;n===void 0&&(console.error(Ve.red(" state must be on, off or default")),process.exit(1));let{status:s,data:i}=await Gt("POST","/narration",{[t.task?"taskId":"agentId"]:e,on:n});s>=300&&(console.error(Ve.red(` ${i.error||`HTTP ${s}`}`)),process.exit(1)),console.log(JSON.stringify(i))});ee();import{Command as Xh}from"commander";import X from"chalk";import{existsSync as Qh,readFileSync as Eg,writeFileSync as Ag}from"fs";import{resolve as Sg}from"path";up();var zt=new Xh().name("voice").description("list installed system voices and pick each agent's voice");function Er(e){let o=e?[e]:[Sg(process.cwd(),"agentx.json"),Sg(process.cwd(),".agentx/config.json")],t=o.find(n=>Qh(n));if(!t)throw new Error(`No config found. Searched: ${o.join(", ")}`);return t}function Zh(e,o,t,n,s){let{provider:i,gender:r}=n,a=n.lang?.toLowerCase().split(/[-_]/)[0],c=e?.agents?.[o];if(!c)throw new Error(`No agent "${o}" in agentx.json`);if(i&&i!=="system"&&i!=="elevenlabs")throw new Error("--provider must be system or elevenlabs");if(r&&!["female","male","neutral"].includes(r))throw new Error("--gender must be female, male or neutral");if(a&&!t)throw new Error("--lang needs a voice");if(!t&&!i&&!r)throw new Error("Give a voice, a --provider, a --gender, or a mix");let l={...c.voice??{}};i&&(l.provider=i),r&&(l.gender=r);let g=l.provider??e?.voice?.provider??"system",d=[i&&`provider ${i}`,r&&`gender ${r}`],u=h=>{if(!a){l.system=h;return}let w=typeof l.system=="string"?{[String(e?.voice?.locale??"en").toLowerCase().split(/[-_]/)[0]]:l.system}:{...l.system??{}};l.system={...w,[a]:h}},f=a?` for ${a}`:"";if(t){let h=t.trim().toLowerCase()===Po,w=h?null:fs(t,s,a??e?.voice?.locale),k=w?`system voice ${Di(w)}`:"the OS default voice";if((w||h)&&g==="system")u(h?Po:t),d.push(`${k}${f}`);else if(g==="elevenlabs"&&!w&&!h&&!a)l.elevenlabsVoiceId=t,d.push(`ElevenLabs voice ${t}`);else if(w||h)u(h?Po:t),d.push(`fallback ${k}${f}`);else throw new Error(`"${t}" is not an installed system voice. Run \`agentx voice list\`, or add --provider elevenlabs for an ElevenLabs voice id.`)}let p=d.filter(Boolean).join(", ");return{raw:{...e,agents:{...e.agents,[o]:{...c,voice:l}}},summary:p}}zt.command("list").alias("ls").description("installed system voices, best first, and which agent uses which").option("--all","every language, not only the configured one").option("-c, --config <path>","agentx.json to read").action(e=>{let o=vn(),t;try{t=O(e.config)}catch{}let n=t?.voice.locale??"en",s=new Map,i=t?ol(t.agents,t.voice,o):new Map;if(t)for(let[a,c]of Object.entries(t.agents)){let l=i.get(a),g=Object.values(Pi(a,c.voice?.system,c.voice?.gender,t.voice,o));for(let d of new Set([l,...g]))d&&s.set(d.id,[...s.get(d.id)??[],a])}if(!o.length)console.log(X.yellow(`
391
391
  No system voices found (system voices need macOS).
392
- `));else{let a=e.all?Ei(o,""):Ei(o,n);console.log(X.bold(`
392
+ `));else{let a=e.all?_i(o,""):_i(o,n);console.log(X.bold(`
393
393
  System voices${e.all?"":` (${n})`}, best first
394
394
  `));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):""}`)}o.some(c=>c.quality!=="standard")||(console.log(X.dim(`
395
- 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=t?zc(t,o):[];if(r.length){console.log(X.bold.yellow(`
395
+ 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=t?sl(t,o):[];if(r.length){console.log(X.bold.yellow(`
396
396
  Not installed
397
- `));for(let a of r)console.log(` ${Oi(a.voice).padEnd(24)} ${X.cyan(a.agents.join(", "))}`);console.log(X.dim(`
398
- Reinstall in ${Gc}.`)),console.log(X.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(t){console.log(X.bold(`
397
+ `));for(let a of r)console.log(` ${Mi(a.voice).padEnd(24)} ${X.cyan(a.agents.join(", "))}`);console.log(X.dim(`
398
+ Reinstall in ${nl}.`)),console.log(X.dim(" Until then each agent speaks with the voice shown below; a running daemon switches back on its own."))}if(t){console.log(X.bold(`
399
399
  Agents
400
- `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=h=>h?Ai(h):X.dim("system default"),d=Object.entries(Ti(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,h])=>(h?.id??null)!==(i.get(a)?.id??null)).map(([h,w])=>`${X.dim(`${h}:`)} ${g(w)}`).join(X.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??X.dim("(default voice)")}`:`system ${g(i.get(a))}${d?X.dim(" \xB7 ")+d:""}`,f=r.filter(h=>h.agents.includes(a)).map(h=>Oi(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()});Ht.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${_o}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=fr(t.config),{raw:s,summary:i}=jh(JSON.parse(fg(n,"utf8")),e,o,t,$n());hg(n,JSON.stringify(s,null,2)+`
401
- `),console.log(X.green(` ${e}: ${i}`)),console.log(X.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});function yg(e,o){let t=Yc(o,j(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
402
- `));let n=JSON.parse(fg(e,"utf8"));Kc(n,o),hg(e,JSON.stringify(n,null,2)+`
403
- `)}Ht.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${sa.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=fr(t.config);if(e&&o){let i=o==="default"?null:o;yg(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=j(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(X.bold(`
400
+ `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=h=>h?Di(h):X.dim("system default"),d=Object.entries(Pi(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,h])=>(h?.id??null)!==(i.get(a)?.id??null)).map(([h,w])=>`${X.dim(`${h}:`)} ${g(w)}`).join(X.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??X.dim("(default voice)")}`:`system ${g(i.get(a))}${d?X.dim(" \xB7 ")+d:""}`,f=r.filter(h=>h.agents.includes(a)).map(h=>Mi(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()});zt.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Po}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=Er(t.config),{raw:s,summary:i}=Zh(JSON.parse(Eg(n,"utf8")),e,o,t,vn());Ag(n,JSON.stringify(s,null,2)+`
401
+ `),console.log(X.green(` ${e}: ${i}`)),console.log(X.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(X.red(` ${n.message}`)),process.exit(1)}});function Tg(e,o){let t=rl(o,O(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
402
+ `));let n=JSON.parse(Eg(e,"utf8"));al(n,o),Ag(e,JSON.stringify(n,null,2)+`
403
+ `)}zt.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${ua.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=Er(t.config);if(e&&o){let i=o==="default"?null:o;Tg(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=O(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(X.bold(`
404
404
  Orb palettes
405
- `));for(let i of na)console.log(` ${i.id.padEnd(10)} ${X.dim(i.colors.join(" "))}`);console.log(X.bold(`
405
+ `));for(let i of pa)console.log(` ${i.id.padEnd(10)} ${X.dim(i.colors.join(" "))}`);console.log(X.bold(`
406
406
  Agents
407
- `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Tt(i,r).color,c=ia(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)}});Ht.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, ${Ci.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Ci.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=fr(e.config),t={};e.timeout!==void 0&&(t.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(t.maxHeight=Number(e.maxHeight)),Object.keys(t).length&&yg(o,{general:{card:t}});let n=j(o).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(t).length&&console.log(X.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(o){console.log(X.red(` ${o.message}`)),process.exit(1)}});import{Command as Ih}from"commander";import N from"chalk";var Ho=new Ih().name("attach").description("wear an agentx agent identity in this Claude Code session"),qs=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Zo()}`;function Us(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Fs(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function Ws(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:o}function $g(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function Nh(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(t)} ${$g(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function Rh(e){let o=e.filter(n=>n.agentIds.length>0),t=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:o,watching:t,idle:e.length-o.length-t.length}}function _h(e,o=!1){let t=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(t)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Ho.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${yi.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",qs).action(async(e,o)=>{let t=Us(o.session);t||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),Sa(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${yi.join(", ")}`)),process.exit(1)),Sn()||(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 Fs(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${$g(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(N.red(`Bind failed: ${Ws(n)}`)),process.exit(1)}});function wg(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function Dh(e){let o=wg(e.kinds),t=wg(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}Ho.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",qs).action(async e=>{let o=Us(e.session);o||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")}.`),process.exit(1)),Sn()||(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 Fs(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:Dh(e)}),console.log(`${N.green("\u2713")} This session is now ${N.bold("watching")}. It answers for no agent.`),console.log(N.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(N.gray(` Stop with ${N.cyan("agentx attach detach")}.`))}catch(t){console.error(N.red(`Watch failed: ${Ws(t)}`)),process.exit(1)}});Ho.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",qs).action(async e=>{let o=Us(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Fs(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(N.red(`Detach failed: ${Ws(t)}`)),process.exit(1)}});Ho.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",qs).option("--json","raw JSON output").action(async e=>{let o=Us();try{let n=(await Fs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Sn(),sessions:n},null,2));return}console.log(),console.log(Sn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(xn())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=Rh(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===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)_h(a,a.sessionId===o)}r>0&&console.log(N.gray(`
408
- ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(N.red(`Could not read attach state: ${Ws(t)}`)),process.exit(1)}});Ho.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||Zo()),t=_l(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${N.green("\u2713")} Installed attach hooks in ${N.gray(t.path)}`:`${N.green("\u2713")} Attach hooks already up to date in ${N.gray(t.path)}`),console.log(N.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(N.gray(" PreToolUse guard installed at user scope.")),console.log(N.gray(` (An attached session runs under your permissions, not the agent's workspace
407
+ `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Ct(i,r).color,c=fa(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)}});zt.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, ${Li.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Li.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=Er(e.config),t={};e.timeout!==void 0&&(t.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(t.maxHeight=Number(e.maxHeight)),Object.keys(t).length&&Tg(o,{general:{card:t}});let n=O(o).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(t).length&&console.log(X.dim(" AgentX Voice picks this up the next time it reads its settings."))}catch(o){console.log(X.red(` ${o.message}`)),process.exit(1)}});import{Command as ey}from"commander";import N from"chalk";var zo=new ey().name("attach").description("wear an agentx agent identity in this Claude Code session"),Js=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${tt()}`;function Hs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Gs(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function zs(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:o}function Cg(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function oy(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(t)} ${Cg(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function ty(e){let o=e.filter(n=>n.agentIds.length>0),t=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:o,watching:t,idle:e.length-o.length-t.length}}function ny(e,o=!1){let t=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(t)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}zo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ai.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Js).action(async(e,o)=>{let t=Hs(o.session);t||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),Pa(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Ai.join(", ")}`)),process.exit(1)),Tn()||(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 Gs(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${Cg(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(N.red(`Bind failed: ${zs(n)}`)),process.exit(1)}});function Og(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function sy(e){let o=Og(e.kinds),t=Og(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}zo.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",Js).action(async e=>{let o=Hs(e.session);o||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")}.`),process.exit(1)),Tn()||(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 Gs(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:sy(e)}),console.log(`${N.green("\u2713")} This session is now ${N.bold("watching")}. It answers for no agent.`),console.log(N.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(N.gray(` Stop with ${N.cyan("agentx attach detach")}.`))}catch(t){console.error(N.red(`Watch failed: ${zs(t)}`)),process.exit(1)}});zo.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",Js).action(async e=>{let o=Hs(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Gs(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(N.red(`Detach failed: ${zs(t)}`)),process.exit(1)}});zo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Js).option("--json","raw JSON output").action(async e=>{let o=Hs();try{let n=(await Gs(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Tn(),sessions:n},null,2));return}console.log(),console.log(Tn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(An())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=ty(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)oy(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)ny(a,a.sessionId===o)}r>0&&console.log(N.gray(`
408
+ ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(N.red(`Could not read attach state: ${zs(t)}`)),process.exit(1)}});zo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||tt()),t=Gl(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${N.green("\u2713")} Installed attach hooks in ${N.gray(t.path)}`:`${N.green("\u2713")} Attach hooks already up to date in ${N.gray(t.path)}`),console.log(N.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(N.gray(" PreToolUse guard installed at user scope.")),console.log(N.gray(` (An attached session runs under your permissions, not the agent's workspace
409
409
  settings \u2014 without this an attached production identity would be less
410
- guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(N.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Ho.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=Dl({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(o.path)} (${o.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(N.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ne();import{Command as Ph}from"commander";import $e from"chalk";var Bs=new Ph().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function kg(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=j(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function vg(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function bg(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Mh(e){return e==="busy"?$e.magenta:e==="warm-hot"?$e.green:e==="warm-cold"?$e.cyan:e==="idle"?$e.yellow:e==="dead"?$e.red:$e.dim}Bs.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=kg(e),n;try{n=await fetch(`${o}/api/processes`,{headers:vg(t)})}catch(r){console.log($e.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log($e.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log($e.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log($e.dim(" (no processes)"));return}for(let r of i){let a=Mh(r.state)(r.state.padEnd(9)),c=bg(r.spawnedAt),l=r.lastTurnAt?bg(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?$e.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?$e.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):$e.dim("sess=\u2014"),u=r.pendingTaskId?$e.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${$e.bold(r.key.agentId)}${$e.dim(":"+r.key.channel+":"+r.key.chatId)} ${$e.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${$e.red("dead:")} ${r.deadReason}`)}});Bs.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=kg(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:vg(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log($e.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log($e.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($e.red(` ${a}`)),process.exit(1)}console.log($e.green(` killed ${e}:${o}:${t}`))});import{Command as Lh}from"commander";import qe from"chalk";import{existsSync as hr,rmSync as qh}from"fs";import{resolve as yr}from"path";var Gt=new Lh().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Gt.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(qe.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Oa(e,o,{verbose:n}),r=Date.now()-s;console.log(qe.green(` \u2713 indexed ${i.docs} doc(s) for ${qe.bold(e)} in ${r}ms`)),console.log(qe.dim(` \u2192 ${i.path}`))});Gt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=yr(e.cwd,".agentx","rag");if(!hr(o)){console.log(qe.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>hr(yr(o,s,"index.json")));if(n.length===0){console.log(qe.dim(" (no indexes)"));return}for(let s of n.sort()){let i=wi(s);console.log(` ${qe.bold(s)} ${i.docs} doc(s) ${qe.dim(i.path)}`)}});Gt.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=Ca(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=wi(e);i.exists?console.log(qe.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(qe.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${qe.bold(i.title)} ${qe.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${qe.dim(i.path)}`),console.log(` ${qe.dim(i.snippet.slice(0,200))}`)});Gt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=yr(process.cwd(),".agentx","rag",e);if(!hr(o)){console.log(qe.dim(` no index for ${e} \u2014 nothing to clear`));return}qh(o,{recursive:!0,force:!0}),console.log(qe.green(` \u2713 cleared index for ${e}`))});ne();import{Command as Uh}from"commander";import Q from"chalk";import zt from"prompts";var gt=new Uh().name("backlog").description("manage the local backlog used by business workSource=backlog");function Pn(e){let o=j(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new sl(n)}}function Fh(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function Wh(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}gt.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Pn(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(Q.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${Wh(n.status).padEnd(7)} ${Fh(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});gt.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Pn(t.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=il([o],i.source,n.config),a=await Ni(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}`))}});gt.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Pn(o.config);t.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await Ni(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});gt.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Pn(o.config);t.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});gt.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Pn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(Q.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let w=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await zt({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Jh(o.config):Hh(o.config);w.length?(i=(await zt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await zt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await zt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await zt({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 Gh(o.config,i,a):await zh(o.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(w=>w.id)),d=c.map(w=>{let k=Ii({type:s,project:l,iid:w.iid,url:w.url}),b=g.has(k),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${b?Q.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await zt({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"?Bh(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Ii(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=o.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function Bh(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Jh(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function Hh(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Gh(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function zh(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(xg)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(xg):[]}function xg(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Vh}from"commander";import W from"chalk";import{existsSync as Yh,readFileSync as Kh}from"fs";import{resolve as Xh}from"path";import Qh from"prompts";ne();function Sg(e){let o=e||Xh(process.cwd(),"agentx.json");return Yh(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Kh(o,"utf-8"))}async function Zh(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Qh([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var So=new Vh().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');So.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: ${ki})`,ki).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){So.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=bi(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Sg(o.config),s=aa(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Zh(o.notify,s),r=o.id||Ua(t.matched,o.agent),a=Wa({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Fa(o.onError),enabled:!o.disabled}),c=a.onError,l=await pe(d=>je(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});So.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=Sg(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Ja(Ba(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])So.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await za(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});So.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await pe(t=>{if(!At(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);_a(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",Ha,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Ga,"reject an agent's pending create/delete request (drops the request)"]])So.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});So.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=bi(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as ey}from"commander";import be from"chalk";import Eo from"chalk";function Eg(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var Ag=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Tg(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(o,t)=>{if(process.platform!=="darwin"){console.error(Eo.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?Eg():n?xc(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(Eo.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={...It().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await Tc(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(Eo.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(Eo.dim(` not answered${r.why?` (${r.why})`:""}; the card is still waiting`));return}let a=await ls({root:process.cwd()},`card:${s.id}`,r.action,{by:"operator (popup)",...r.action==="yes"?{choice:r.choice,text:r.text}:{}});if(!a.ok){console.error(Eo.red(` ${a.error}`)),process.exitCode=1;return}console.log(Eo.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async o=>{let t={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(t.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${Ag()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(Eo.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(Eo.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(Eo.red(` couldn't reach the daemon at ${Ag()}: ${n?.message??n}`)),process.exitCode=1}})}var Ao=new ey("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),oy={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function Og(){return{root:process.cwd()}}function wr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function ty(e){console.log(` ${be.cyan(e.key)} ${be.dim(`[${oy[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?be.dim(` (later: until ${wr(e.snoozed_until)})`):""}`),console.log(` ${be.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${be.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,t)=>console.log(` ${be.magenta(`${t+1}.`)} ${o}`)),e.expires&&console.log(be.yellow(` Expires ${wr(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(be.dim(` ${e.detail}`)),e.source&&console.log(be.dim(` ${e.source}`)),console.log(be.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Ao.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let o=Ac(Og(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(be.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(be.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)ty(t),console.log();console.log(be.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function $r(e,o,t){let n=It(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(be.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await ls(Og(),e,o,{force:t.force,note:t.note,laterHours:s,choice:t.choice,text:t.text});if(!i.ok){console.error(be.red(` ${i.error}`)),process.exitCode=1;return}console.log(be.green(` \u2713 ${i.message}`))}Ao.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message: the message as you want it sent").action((e,o)=>$r(e,"yes",o));Ao.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,o)=>$r(e,"no",o));Ao.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,o)=>$r(e,"later",o));Ao.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: ${vc.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,o=[])=>[...o,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(e=>{let o=It(),t=Sc(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},{settings:o});if(!t.ok){console.error(be.red(` ${t.error}`)),process.exitCode=1;return}console.log(be.green(` \u2713 card:${t.card.id} raised; expires ${wr(t.card.expires)}, then: ${t.card.if_silent}`))});Tg(Ao);Ao.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let o={},t=(l,g)=>{if(g===void 0)return;let d=Number(g);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,g)=>{if(g!==void 0){if(g==="on")return!0;if(g==="off")return!1;throw new Error(`${l} takes on or off`)}};try{o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),o.popupEnabled=n("--popup",e.popup),o.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(o.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(o.popupSound=e.popupSound==="none"?"":e.popupSound),o.popupTimeoutSeconds=t("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(o.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(o.popupTheme=e.popupTheme),o.checkinEnabled=n("--checkin",e.checkin);let l=g=>g?.split(",").map(d=>d.trim()).filter(Boolean);if(o.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(o.checkinDailyAt=e.checkinDaily),o.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(o.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let g=hl(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=g}}catch(l){console.error(be.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(o).some(l=>l!==void 0)){let l=await yl(o);if(!l.success){console.error(be.red(` ${l.error}`)),process.exitCode=1;return}console.log(be.green(" \u2713 saved")+(l.reloaded?be.dim(" (daemon reloaded)"):""))}let i=It(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`);let a=i.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=i.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as ny}from"commander";import{existsSync as sy}from"fs";import fe from"chalk";var Vt=new ny("requests").description("what you asked agents for that is not finished, oldest first"),Cg={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function br(){if(!sy(Ra()))return console.error(fe.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=bt();return e?new Pa(e):(process.exitCode=1,null)}var Js=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function jg(e){let o=e.state==="needs_attention"?fe.red:e.state==="waiting_owner"?fe.yellow:fe.dim;console.log(` ${fe.cyan(e.id)} ${o(`[${Cg[e.state]??e.state}]`)} ${fe.dim(`${Js(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(fe.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(fe.red(` ${e.attentionReason}`)),e.evidence&&console.log(fe.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(fe.dim(` Reason: ${e.closeReason}`))}Vt.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=br();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(xi().enabled||console.log(fe.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(fe.dim(" no open requests"));return}for(let n of t)jg(n);console.log(fe.dim(`
411
- ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});Vt.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=br();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(fe.red(` no request "${e}"`)),process.exitCode=1;return}jg(t),console.log(fe.dim(` Last activity ${Js(t.updatedAt)}${t.closedAt?` \xB7 closed ${Js(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(fe.dim(` ${n.kind} ${n.ref} (${Js(n.at)})`))});function Ig(e,o,t,n){Vt.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=br();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(fe.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(fe.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(fe.red(` ${s} is already closed (${Cg[c.state]??c.state})`)),process.exitCode=1;return}console.log(fe.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}Ig("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");Ig("drop","drop a request you no longer want","--reason <text>","");Vt.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(fe.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await Ec(o);if(!n.success){console.error(fe.red(` ${n.error}`)),process.exitCode=1;return}console.log(fe.green(" \u2713 saved")+(n.reloaded?fe.dim(" (daemon reloaded)"):""))}let t=xi();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as Ty}from"commander";import Yt from"chalk";import ie from"chalk";import Ln from"prompts";import{readFileSync as iy,writeFileSync as ry,existsSync as ay}from"fs";import{resolve as Ng}from"path";var cy=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function ly(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function kr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Rg(e=".env"){let o=Ng(e);if(!ay(o))return[];let t=iy(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(cy);i?n.push({kind:"kv",key:i[1],value:ly(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function dy(e){return e.map(o=>o.kind==="kv"?`${o.key}=${kr(o.value)}`:o.raw).join(`
410
+ guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(N.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});zo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=zl({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(o.path)} (${o.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(N.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ee();import{Command as iy}from"commander";import $e from"chalk";var Ys=new iy().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ig(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=O(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Ng(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function jg(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function ry(e){return e==="busy"?$e.magenta:e==="warm-hot"?$e.green:e==="warm-cold"?$e.cyan:e==="idle"?$e.yellow:e==="dead"?$e.red:$e.dim}Ys.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Ig(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Ng(t)})}catch(r){console.log($e.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log($e.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log($e.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log($e.dim(" (no processes)"));return}for(let r of i){let a=ry(r.state)(r.state.padEnd(9)),c=jg(r.spawnedAt),l=r.lastTurnAt?jg(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?$e.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?$e.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):$e.dim("sess=\u2014"),u=r.pendingTaskId?$e.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${$e.bold(r.key.agentId)}${$e.dim(":"+r.key.channel+":"+r.key.chatId)} ${$e.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${$e.red("dead:")} ${r.deadReason}`)}});Ys.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Ig(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Ng(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log($e.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log($e.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($e.red(` ${a}`)),process.exit(1)}console.log($e.green(` killed ${e}:${o}:${t}`))});import{Command as ay}from"commander";import Ue from"chalk";import{existsSync as Ar,rmSync as cy}from"fs";import{resolve as Tr}from"path";var Yt=new ay().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Yt.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(Ue.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Ua(e,o,{verbose:n}),r=Date.now()-s;console.log(Ue.green(` \u2713 indexed ${i.docs} doc(s) for ${Ue.bold(e)} in ${r}ms`)),console.log(Ue.dim(` \u2192 ${i.path}`))});Yt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Tr(e.cwd,".agentx","rag");if(!Ar(o)){console.log(Ue.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Ar(Tr(o,s,"index.json")));if(n.length===0){console.log(Ue.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ti(s);console.log(` ${Ue.bold(s)} ${i.docs} doc(s) ${Ue.dim(i.path)}`)}});Yt.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=Fa(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ti(e);i.exists?console.log(Ue.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Ue.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Ue.bold(i.title)} ${Ue.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Ue.dim(i.path)}`),console.log(` ${Ue.dim(i.snippet.slice(0,200))}`)});Yt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Tr(process.cwd(),".agentx","rag",e);if(!Ar(o)){console.log(Ue.dim(` no index for ${e} \u2014 nothing to clear`));return}cy(o,{recursive:!0,force:!0}),console.log(Ue.green(` \u2713 cleared index for ${e}`))});ee();import{Command as ly}from"commander";import Q from"chalk";import Vt from"prompts";var ut=new ly().name("backlog").description("manage the local backlog used by business workSource=backlog");function Un(e){let o=O(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new fl(n)}}function dy(e){return e?Q.cyan(`${e.type}:${e.project}#${e.iid}`):Q.dim("manual")}function gy(e){return{todo:Q.gray("todo"),doing:Q.yellow("doing"),blocked:Q.red("blocked"),done:Q.green("done")}[e]}ut.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=Un(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(Q.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?Q.magenta(`@${n.assignee}`):Q.dim("unassigned");console.log(` ${gy(n.status).padEnd(7)} ${dy(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Q.dim(` ${n.source.url}`))}console.log(),console.log(Q.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});ut.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=Un(t.config);n.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(Q.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=hl([o],i.source,n.config),a=await Fi(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}`))}});ut.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=Un(o.config);t.store.findById(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(Q.green(` done: ${s.title}`)),s.source){let i=await Fi(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(Q.dim(" sync:"),...r));console.log(i.ok?Q.dim(` synced -> ${i.url??s.source.type}`):Q.yellow(` sync failed: ${i.error}`))}});ut.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=Un(o.config);t.remove(e)||(console.error(Q.red(` item ${e} not found`)),process.exit(1)),console.log(Q.green(` removed ${e}`))});ut.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=Un(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(Q.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let w=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Vt({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(Q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?py(o.config):uy(o.config);w.length?(i=(await Vt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Vt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Vt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Vt({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 fy(o.config,i,a):await hy(o.config,i,a);if(!c.length){console.log(Q.yellow(" no open issues matched"));return}console.log(Q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(w=>w.id)),d=c.map(w=>{let k=Ui({type:s,project:l,iid:w.iid,url:w.url}),b=g.has(k),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${b?Q.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Vt({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"?my(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Ui(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),h=o.store.addMany(p);console.log(Q.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(Q.dim(` ${w.id} \u2014 ${w.title}`))});function my(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function py(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function uy(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function fy(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function hy(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Rg)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Rg):[]}function Rg(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as yy}from"commander";import W from"chalk";import{existsSync as wy,readFileSync as $y}from"fs";import{resolve as by}from"path";import ky from"prompts";ee();function _g(e){let o=e||by(process.cwd(),"agentx.json");return wy(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse($y(o,"utf-8"))}async function vy(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await ky([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Eo=new yy().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Eo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${ji})`,ji).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){Eo.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Ci(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=_g(o.config),s=$a(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await vy(o.notify,s),r=o.id||Xa(t.matched,o.agent),a=Za({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Qa(o.onError),enabled:!o.disabled}),c=a.onError,l=await se(d=>je(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});Eo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=_g(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=oc(ec(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])Eo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await sc(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});Eo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await se(t=>{if(!Ot(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Ga(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",tc,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",nc,"reject an agent's pending create/delete request (drops the request)"]])Eo.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});Eo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ci(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as xy}from"commander";import be from"chalk";import Ao from"chalk";function Dg(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var Pg=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Mg(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(o,t)=>{if(process.platform!=="darwin"){console.error(Ao.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?Dg():n?_c(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(Ao.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={...Rt().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await Lc(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(Ao.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(Ao.dim(` not answered${r.why?` (${r.why})`:""}; the card is still waiting`));return}let a=await us({root:process.cwd()},`card:${s.id}`,r.action,{by:"operator (popup)",...r.action==="yes"?{choice:r.choice,text:r.text}:{}});if(!a.ok){console.error(Ao.red(` ${a.error}`)),process.exitCode=1;return}console.log(Ao.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async o=>{let t={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(t.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${Pg()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(Ao.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(Ao.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(Ao.red(` couldn't reach the daemon at ${Pg()}: ${n?.message??n}`)),process.exitCode=1}})}var To=new xy("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Sy={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function Lg(){return{root:process.cwd()}}function Or(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Ey(e){console.log(` ${be.cyan(e.key)} ${be.dim(`[${Sy[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?be.dim(` (later: until ${Or(e.snoozed_until)})`):""}`),console.log(` ${be.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${be.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,t)=>console.log(` ${be.magenta(`${t+1}.`)} ${o}`)),e.expires&&console.log(be.yellow(` Expires ${Or(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(be.dim(` ${e.detail}`)),e.source&&console.log(be.dim(` ${e.source}`)),console.log(be.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}To.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let o=Mc(Lg(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(be.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(be.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Ey(t),console.log();console.log(be.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Cr(e,o,t){let n=Rt(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(be.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await us(Lg(),e,o,{force:t.force,note:t.note,laterHours:s,choice:t.choice,text:t.text});if(!i.ok){console.error(be.red(` ${i.error}`)),process.exitCode=1;return}console.log(be.green(` \u2713 ${i.message}`))}To.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message: the message as you want it sent").action((e,o)=>Cr(e,"yes",o));To.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,o)=>Cr(e,"no",o));To.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,o)=>Cr(e,"later",o));To.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").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,o=[])=>[...o,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(e=>{let o=Rt(),t=Dc(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},{settings:o});if(!t.ok){console.error(be.red(` ${t.error}`)),process.exitCode=1;return}console.log(be.green(` \u2713 card:${t.card.id} raised; expires ${Or(t.card.expires)}, then: ${t.card.if_silent}`))});Mg(To);To.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let o={},t=(l,g)=>{if(g===void 0)return;let d=Number(g);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,g)=>{if(g!==void 0){if(g==="on")return!0;if(g==="off")return!1;throw new Error(`${l} takes on or off`)}};try{o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),o.popupEnabled=n("--popup",e.popup),o.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(o.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(o.popupSound=e.popupSound==="none"?"":e.popupSound),o.popupTimeoutSeconds=t("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(o.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(o.popupTheme=e.popupTheme),o.checkinEnabled=n("--checkin",e.checkin);let l=g=>g?.split(",").map(d=>d.trim()).filter(Boolean);if(o.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(o.checkinDailyAt=e.checkinDaily),o.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(o.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let g=Tl(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=g}}catch(l){console.error(be.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(o).some(l=>l!==void 0)){let l=await Ol(o);if(!l.success){console.error(be.red(` ${l.error}`)),process.exitCode=1;return}console.log(be.green(" \u2713 saved")+(l.reloaded?be.dim(" (daemon reloaded)"):""))}let i=Rt(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`);let a=i.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=i.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as Ay}from"commander";import Me from"chalk";ee();ns();fp();ya();function qg(e,o,t=20){return e.prepare(`SELECT task_id, agent_id, channel, chat_id, status, started_at, message_preview
411
+ FROM task_traces
412
+ WHERE person = ? AND (channel IS NULL OR channel != 'a2a')
413
+ ORDER BY started_at DESC LIMIT ?`).all(o,Math.max(1,Math.min(t,500))).map(s=>({taskId:s.task_id,agentId:s.agent_id,channel:s.channel,chatId:s.chat_id,status:s.status,startedAt:s.started_at,messagePreview:s.message_preview}))}function Ug(e,o){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()?e.prepare("PRAGMA table_info(requests)").all().some(i=>i.name==="person")?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
414
+ WHERE person = ? AND state IN (${ki.map(()=>"?").join(",")})
415
+ ORDER BY created_at`).all(o,...ki).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]:[]}var Yo=new Ay("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),Ty=["owner","member","guest"],Oy=(e,o=[])=>[...o,e];async function Vs(e){let o="",t=await se(n=>{n.people=Array.isArray(n.people)?n.people:[],o=e(n.people)});t.success||(console.error(Me.red(`\u2717 ${(t.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(Me.green(`\u2713 ${o}`)),t.reloaded&&console.log(Me.dim(" daemon hot-reloaded"))}function jr(e,o){let t=e.find(n=>n?.id===o);if(!t)throw new Error(`No person "${o}". See \`agentx people list\`.`);return t.identities=Array.isArray(t.identities)?t.identities:[],t}function Bg(e,o){let t=xi(e),n=xi(o);return!!t&&!!n&&t.channel===n.channel&&t.value===n.value}function Jg(e){console.log(` ${Me.bold(e.id)} ${e.name} ${Me.dim(`\xB7 ${e.role}`)}`),console.log(Me.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}Yo.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let o=O().people;if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(),o.length===0&&(console.log(Me.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${vi}"; senders on other channels are unknown.`)),console.log(Me.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let t of o)Jg(t);console.log()});Yo.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${Ty.join(" | ")}`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",Oy,[]).action(async(e,o)=>{await Vs(t=>{if(t.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);return t.push({id:e,name:o.name,role:o.role,identities:o.identity}),`added ${e} (${o.role})`})});Yo.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,o)=>{await Vs(t=>{let n=jr(t,e);return n.identities.some(s=>Bg(s,o))?`${e} already has ${o}`:(n.identities.push(o),`${o} is now ${e}`)})});Yo.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,o)=>{await Vs(t=>{let n=jr(t,e),s=n.identities.length;if(n.identities=n.identities.filter(i=>!Bg(i,o)),n.identities.length===s)throw new Error(`"${e}" has no identity ${o}.`);return`${o} is no longer ${e}`})});Yo.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown").action(async e=>{await Vs(o=>(jr(o,e),o.splice(o.findIndex(t=>t?.id===e),1),`removed ${e}`))});var Fg=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC",Wg=(e,o=100)=>(e??"").replace(/\s+/g," ").trim().slice(0,o);Yo.command("show <id>").description("one person and what they asked for, on every channel").option("--limit <n>","how many runs to list","20").option("--json","machine-readable output").action((e,o)=>{let t=O().people.find(r=>r.id===e),n=No({quiet:!0}),s=n?qg(n,e,Number(o.limit)||20):[],i=n?Ug(n,e):[];if(o.json){console.log(JSON.stringify({person:t??null,openRequests:i,runs:s},null,2));return}if(console.log(),t?Jg(t):console.log(Me.dim(` "${e}" is not in the list${e===vi?" (it is the built-in owner of this machine)":""}; showing what is recorded under that id`)),!n){console.log(Me.yellow(`
416
+ couldn't open .agentx/db.sqlite: run this from the folder that holds agentx.json
417
+ `));return}if(i.length){console.log(`
418
+ Open requests (${i.length})`);for(let r of i)console.log(` ${Me.cyan(r.id)} ${Me.dim(`${Fg(r.createdAt)} \xB7 ${r.channel} \xB7 ${r.agentId} \xB7 ${r.state.replace(/_/g," ")}`)}
419
+ ${Wg(r.text,200)}`)}console.log(`
420
+ Latest runs (${s.length})`),s.length===0&&console.log(Me.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?Me.green("ok"):r.status==="in-flight"?Me.yellow("running"):Me.red(r.status);console.log(` ${Me.dim(Fg(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${Wg(r.messagePreview)}`)}console.log()});ns();ya();import{Command as Cy}from"commander";import{existsSync as jy}from"fs";import fe from"chalk";var Kt=new Cy("requests").description("what you asked agents for that is not finished, oldest first"),Hg={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function Ir(){if(!jy(Ha()))return console.error(fe.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=No();return e?new ha(e):(process.exitCode=1,null)}var Ks=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function Gg(e){let o=e.state==="needs_attention"?fe.red:e.state==="waiting_owner"?fe.yellow:fe.dim;console.log(` ${fe.cyan(e.id)} ${o(`[${Hg[e.state]??e.state}]`)} ${fe.dim(`${Ks(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(fe.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(fe.red(` ${e.attentionReason}`)),e.evidence&&console.log(fe.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(fe.dim(` Reason: ${e.closeReason}`))}Kt.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Ir();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Ni().enabled||console.log(fe.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(fe.dim(" no open requests"));return}for(let n of t)Gg(n);console.log(fe.dim(`
421
+ ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});Kt.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Ir();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(fe.red(` no request "${e}"`)),process.exitCode=1;return}Gg(t),console.log(fe.dim(` Last activity ${Ks(t.updatedAt)}${t.closedAt?` \xB7 closed ${Ks(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(fe.dim(` ${n.kind} ${n.ref} (${Ks(n.at)})`))});function zg(e,o,t,n){Kt.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=Ir();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(fe.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(fe.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(fe.red(` ${s} is already closed (${Hg[c.state]??c.state})`)),process.exitCode=1;return}console.log(fe.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}zg("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");zg("drop","drop a request you no longer want","--reason <text>","");Kt.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(fe.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await Pc(o);if(!n.success){console.error(fe.red(` ${n.error}`)),process.exitCode=1;return}console.log(fe.green(" \u2713 saved")+(n.reloaded?fe.dim(" (daemon reloaded)"):""))}let t=Ni();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as Iy}from"commander";import Xt from"chalk";ee();var Yg=new Iy("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Ji.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(Xt.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await se(i=>{n=Cl(i,e,o==="on")});s.success||(console.error(Xt.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Xt.green(`\u2713 ${n}`)),s.reloaded&&console.log(Xt.dim(" daemon hot-reloaded"))}let t=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Ji)console.log(` ${n.padEnd(8)} ${t.includes(n)?Xt.green("on"):Xt.dim("off")}`)});import{Command as ew}from"commander";import Qt from"chalk";import re from"chalk";import Wn from"prompts";import{readFileSync as Ny,writeFileSync as Ry,existsSync as _y}from"fs";import{resolve as Vg}from"path";var Dy=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Py(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Nr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Kg(e=".env"){let o=Vg(e);if(!_y(o))return[];let t=Ny(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(Dy);i?n.push({kind:"kv",key:i[1],value:Py(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function My(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Nr(o.value)}`:o.raw).join(`
412
422
  `)+`
413
- `}function Mn(e,o,t=".env"){let n=Ng(t),s=Rg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${kr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${kr(o)}`})),ry(n,dy(s))}function vr(e,o=".env"){return Rg(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var _g="https://t.me/BotFather";async function gy(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function my(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Dg(e={}){console.log(),console.log(ie.bold(" Connect Telegram")),console.log(),console.log(ie.dim(` 1. Open ${_g}`)),console.log(ie.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ie.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Ln({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b($,[_g],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Ln({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ie.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await gy(t.trim());n||(console.log(ie.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ie.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ie.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Ln({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ie.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Ln({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ie.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Mn(f,t.trim()),process.env[f]=t.trim();let p=await pe(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=At(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),je(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ie.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ie.dim(` Token stored in .env as ${f}`)),console.log(ie.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ie.dim(" Daemon hot-reloaded.")):console.log(ie.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Ln({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 my(t.trim(),9e4);if(!w){console.log(ie.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ie.dim(" agentx config set notifications.destination.channel telegram")),console.log(ie.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ie.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await pe(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ie.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ie.green(" \u2713 Default --notify target set")),console.log(ie.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ie.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ie.dim(" Daemon hot-reloaded."))}import ke from"chalk";import xr from"prompts";import{existsSync as Er,mkdirSync as py,readdirSync as uy,readFileSync as Pg}from"fs";import{resolve as Sr}from"path";var fy=".agentx/whatsapp-sessions";function hy(){let e=Sr(process.cwd(),".agentx/daemon.pid");if(!Er(e))return!1;try{let o=parseInt(Pg(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function yy(e){if(!Er(e))return!1;try{return uy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function wy(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ke.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ke.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;py(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ke.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ke.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ke.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ke.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Mg(e={}){if(console.log(),console.log(ke.bold(" Connect WhatsApp")),console.log(),hy()){console.log(ke.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ke.dim(" agentx daemon stop")),console.log();let{cont:l}=await xr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ke.red(" Aborted")),process.exit(1))}let o=e.configPath||Sr(process.cwd(),"agentx.json");Er(o)||(console.log(ke.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Pg(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||fy,s=Sr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ke.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await xr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ke.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yy(s)&&a){let{keep:l}=await xr({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(ke.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await wy(s,g=>console.log(g))||(console.log(ke.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ke.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ke.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ke.dim(` Session: ${n}`)),console.log(ke.dim(" Start the daemon to begin receiving:")),console.log(ke.dim(" agentx daemon start")),console.log(ke.dim(" Add routes later with:")),console.log(ke.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as $y}from"crypto";import Te from"chalk";import Lg from"prompts";var Hs="agentx-mesh:",Gs="//join/";function by(e){return Buffer.from(e,"utf-8").toString("base64url")}function ky(e){return Buffer.from(e,"base64url").toString("utf-8")}function vy(e){return`${Hs}${Gs}${by(JSON.stringify(e))}`}function xy(e){if(!e.startsWith(`${Hs}${Gs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Hs}${Gs}\u2026`);let o=e.slice(Hs.length+Gs.length),t=JSON.parse(ky(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Sy(){return $y(32).toString("hex")}function Ey(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Ay(e){return e?.node?.name||e?.node?.id||"node"}async function qg(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(Te.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=vr("MESH_TOKEN");r||(r=Sy(),Mn("MESH_TOKEN",r),console.log(Te.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ey(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Lg({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(Te.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Te.red(` \u2717 ${l.error}`)),process.exit(1));let g=vy({url:a,token:r,name:Ay(i),version:1});console.log(),console.log(Te.bold(" Mesh invite")),console.log(),console.log(` ${Te.cyan(g)}`),console.log(),console.log(Te.dim(" Run on the other node:")),console.log(Te.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Te.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Ug(e,o={}){let t;try{t=xy(e)}catch(i){console.log(Te.red(` \u2717 ${i.message}`)),process.exit(1)}let n=vr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Lg({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Te.red(" Aborted (keeping existing .env)")),process.exit(1))}Mn("MESH_TOKEN",t.token);let s=await pe(i=>{je(i,"mesh.enabled",!0);let r=At(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),je(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Te.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Te.green(" \u2713 Joined mesh")),console.log(Te.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Te.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Te.dim(" Daemon hot-reloaded.")):console.log(Te.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Te.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Te.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Te.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Kt=new Ty().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Kt.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 Dg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Kt.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 Mg({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Fg=Kt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Fg.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 qg({url:e.url,configPath:e.config})});Fg.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await Ug(e,{configPath:o.config})});Kt.action(()=>{console.log(),console.log(Yt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Yt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Yt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Yt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Yt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Yt.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as Oy}from"commander";import he from"chalk";var qn=new Oy().name("usage").description("token usage analysis and reporting");qn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=j(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(he.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(he.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${he.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: ${he.red(String(s.totalErrors))}`),console.log(),console.log(he.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(` ${he.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${he.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(he.red(" Daemon not running. Start with: agentx daemon start")):console.log(he.red(` ${e.message}`))}});qn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(he.red(` Script not found: ${s}`)),console.log(he.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(he.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(he.red(" Analysis failed. Is Python 3 installed?"))}});qn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-HVVP22SA.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-KMQNX6YK.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(he.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${he.dim("\xB7")} ${d}`);console.log(),console.log(he.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(he.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(he.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(he.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(he.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(he.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=he.dim(`${i.days}d`);console.log(` ${he.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(he.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Cy}from"commander";import ve from"chalk";import{readFileSync as jy}from"fs";import{resolve as Iy}from"path";ne();var Go=new Cy().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Go.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{ya(Iy(process.cwd(),".env"))}catch{}let o=Ny(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-OS5J3F73.js");t(o)}catch(o){console.log(ve.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ve.dim(o.stack)),process.exit(1)}});function Ny(e,o){try{let t=j();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ve.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ve.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
414
- `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Go.command("list").description("list configured boards").action(()=>{try{let e=j();if(!e.boards?.length){console.log(ve.dim(`
423
+ `}function Fn(e,o,t=".env"){let n=Vg(t),s=Kg(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Nr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Nr(o)}`})),Ry(n,My(s))}function Rr(e,o=".env"){return Kg(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xg="https://t.me/BotFather";async function Ly(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function qy(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Qg(e={}){console.log(),console.log(re.bold(" Connect Telegram")),console.log(),console.log(re.dim(` 1. Open ${Xg}`)),console.log(re.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(re.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Wn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&nt(Xg);let{token:t}=await Wn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(re.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Ly(t.trim());n||(console.log(re.red("\u2717 invalid or revoked")),process.exit(1)),console.log(re.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(re.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(re.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Wn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(re.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Wn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(re.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Fn(f,t.trim()),process.env[f]=t.trim();let p=await se(b=>{je(b,"channels.telegram.enabled",!0),je(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Ot(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),je(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(re.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(re.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(re.dim(` Token stored in .env as ${f}`)),console.log(re.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(re.dim(" Daemon hot-reloaded.")):console.log(re.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Wn({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(re.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(re.dim(" Waiting up to 90s..."));let w=await qy(t.trim(),9e4);if(!w){console.log(re.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(re.dim(" agentx config set notifications.destination.channel telegram")),console.log(re.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(re.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await se(b=>{je(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(re.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(re.green(" \u2713 Default --notify target set")),console.log(re.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(re.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(re.dim(" Daemon hot-reloaded."))}import ke from"chalk";import _r from"prompts";import{existsSync as Pr,mkdirSync as Uy,readdirSync as Fy,readFileSync as Zg}from"fs";import{resolve as Dr}from"path";var Wy=".agentx/whatsapp-sessions";function By(){let e=Dr(process.cwd(),".agentx/daemon.pid");if(!Pr(e))return!1;try{let o=parseInt(Zg(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Jy(e){if(!Pr(e))return!1;try{return Fy(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Hy(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ke.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ke.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Uy(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ke.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ke.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ke.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ke.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function em(e={}){if(console.log(),console.log(ke.bold(" Connect WhatsApp")),console.log(),By()){console.log(ke.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ke.dim(" agentx daemon stop")),console.log();let{cont:l}=await _r({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ke.red(" Aborted")),process.exit(1))}let o=e.configPath||Dr(process.cwd(),"agentx.json");Pr(o)||(console.log(ke.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Zg(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Wy,s=Dr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ke.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await _r({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ke.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Jy(s)&&a){let{keep:l}=await _r({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(ke.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Hy(s,g=>console.log(g))||(console.log(ke.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await se(l=>{je(l,"channels.whatsapp.enabled",!0),je(l,"channels.whatsapp.sessionDir",n),je(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ke.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ke.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ke.dim(` Session: ${n}`)),console.log(ke.dim(" Start the daemon to begin receiving:")),console.log(ke.dim(" agentx daemon start")),console.log(ke.dim(" Add routes later with:")),console.log(ke.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Gy}from"crypto";import Te from"chalk";import om from"prompts";var Xs="agentx-mesh:",Qs="//join/";function zy(e){return Buffer.from(e,"utf-8").toString("base64url")}function Yy(e){return Buffer.from(e,"base64url").toString("utf-8")}function Vy(e){return`${Xs}${Qs}${zy(JSON.stringify(e))}`}function Ky(e){if(!e.startsWith(`${Xs}${Qs}`))throw new Error(`Not a mesh invite link \u2014 expected ${Xs}${Qs}\u2026`);let o=e.slice(Xs.length+Qs.length),t=JSON.parse(Yy(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Xy(){return Gy(32).toString("hex")}function Qy(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Zy(e){return e?.node?.name||e?.node?.id||"node"}async function tm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(Te.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Rr("MESH_TOKEN");r||(r=Xy(),Fn("MESH_TOKEN",r),console.log(Te.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Qy(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await om({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(Te.red(" Aborted")),process.exit(1)),a=d}let l=await se(d=>{je(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Te.red(` \u2717 ${l.error}`)),process.exit(1));let g=Vy({url:a,token:r,name:Zy(i),version:1});console.log(),console.log(Te.bold(" Mesh invite")),console.log(),console.log(` ${Te.cyan(g)}`),console.log(),console.log(Te.dim(" Run on the other node:")),console.log(Te.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Te.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function nm(e,o={}){let t;try{t=Ky(e)}catch(i){console.log(Te.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Rr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await om({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Te.red(" Aborted (keeping existing .env)")),process.exit(1))}Fn("MESH_TOKEN",t.token);let s=await se(i=>{je(i,"mesh.enabled",!0);let r=Ot(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),je(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Te.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Te.green(" \u2713 Joined mesh")),console.log(Te.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Te.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Te.dim(" Daemon hot-reloaded.")):console.log(Te.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Te.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Te.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Te.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Zt=new ew().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Zt.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Qg({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Zt.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await em({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var sm=Zt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sm.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 tm({url:e.url,configPath:e.config})});sm.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await nm(e,{configPath:o.config})});Zt.action(()=>{console.log(),console.log(Qt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Qt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Qt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Qt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Qt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Qt.dim(" GitLab connect is the next slice.")),console.log()});ee();import{Command as ow}from"commander";import he from"chalk";var Bn=new ow().name("usage").description("token usage analysis and reporting");Bn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(he.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(he.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${he.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: ${he.red(String(s.totalErrors))}`),console.log(),console.log(he.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(` ${he.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${he.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(he.red(" Daemon not running. Start with: agentx daemon start")):console.log(he.red(` ${e.message}`))}});Bn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(he.red(` Script not found: ${s}`)),console.log(he.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(he.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(he.red(" Analysis failed. Is Python 3 installed?"))}});Bn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-O5L4KLGS.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-FUYHN2F7.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(he.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${he.dim("\xB7")} ${d}`);console.log(),console.log(he.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(he.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(he.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(he.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(he.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(he.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=he.dim(`${i.days}d`);console.log(` ${he.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(he.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as tw}from"commander";import ve from"chalk";import{readFileSync as nw}from"fs";import{resolve as sw}from"path";ee();var Vo=new tw().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Vo.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{Ca(sw(process.cwd(),".env"))}catch{}let o=iw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-TWEF5XVE.js");t(o)}catch(o){console.log(ve.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(ve.dim(o.stack)),process.exit(1)}});function iw(e,o){try{let t=O();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(ve.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(ve.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
424
+ `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Vo.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(ve.dim(`
415
425
  No boards configured.
416
- `));return}console.log();for(let o of e.boards){console.log(` ${ve.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(ve.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(ve.dim(` primary label: ${o.primaryToolLabel}`)),console.log(ve.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(ve.red(` ${e.message}`)),process.exit(1)}});Go.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{Un(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(ve.red(` ${t.message}`)),process.exit(1)}});Go.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{Un(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(ve.red(` ${t.message}`)),process.exit(1)}});var Ar=Go.command("column").description("manage a board's columns (add / remove / edit / list)");Ar.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(jy("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(ve.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(` ${ve.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${ve.dim(i)}`)}}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});Ar.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{Un(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(ve.red(` ${n.message}`)),process.exit(1)}});Ar.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Un(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(ve.red(` ${t.message}`)),process.exit(1)}});Go.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Un(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});function Un(e){let{summary:o,backupPath:t}=Ze(n=>e(n));console.log(ve.green(`
426
+ `));return}console.log();for(let o of e.boards){console.log(` ${ve.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(ve.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(ve.dim(` primary label: ${o.primaryToolLabel}`)),console.log(ve.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(ve.red(` ${e.message}`)),process.exit(1)}});Vo.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{Jn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(ve.red(` ${t.message}`)),process.exit(1)}});Vo.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{Jn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(ve.red(` ${t.message}`)),process.exit(1)}});var Mr=Vo.command("column").description("manage a board's columns (add / remove / edit / list)");Mr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(nw("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(ve.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(` ${ve.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${ve.dim(i)}`)}}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});Mr.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{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===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(ve.red(` ${n.message}`)),process.exit(1)}});Mr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Jn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(ve.red(` ${t.message}`)),process.exit(1)}});Vo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Jn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});function Jn(e){let{summary:o,backupPath:t}=eo(n=>e(n));console.log(ve.green(`
417
427
  \u2713 ${o}
418
428
  `)),t&&console.log(ve.dim(` Backup: ${t}`)),console.log(ve.dim(` Restart the dashboard to pick up the change if not auto-reloading.
419
- `))}import{Command as Dy}from"commander";import m from"chalk";import Ee from"chalk";import{resolve as Ry}from"path";var _y=e=>e||Ry(process.cwd(),".agentx/wiki");async function Xt(e){let{FactLedger:o}=await import("./ledger-CH7R756S.js");return new o(_y(e))}function Qt(e){return async(...o)=>{try{await e(...o)}catch(t){t?.name!=="LedgerCorruptError"&&console.error(Ee.red(` ${t?.message??t}`)),process.exitCode=1}}}function Wg(e){let o=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");o.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(Qt(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await Xt(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(Ee.dim(" no facts recorded"));return}for(let r of i){let a=r.undated?Ee.yellow(" UNCHECKED"):s(r)?Ee.yellow(" STALE"):"";console.log(` ${Ee.cyan(r.id)} ${Ee.bold(r.subject)} \xB7 ${r.attribute}: ${r.value}${a}`),console.log(Ee.dim(` ${r.volatility} \xB7 ${r.source} \xB7 checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy}`))}})),o.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(Qt(async(n,s)=>{let i=(await Xt(s.dir)).get(n);if(!i){console.error(Ee.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(i,null,2))})),o.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${hi.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(Qt(async n=>{if(n.class&&!ka(n.class)){console.error(Ee.red(` --class must be one of ${hi.join(", ")}`)),process.exitCode=1;return}let i=(await Xt(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(Ee.yellow(` not replaced: the wiki says "${i.fact.value}" (checked ${i.fact.verifiedAt.slice(0,10)}), ${r}.`)),console.log(i.questionId?Ee.dim(` Queued question ${i.questionId}: agentx wiki questions \xB7 agentx wiki answer ${i.questionId} "<true value>"`):i.questionClosed?Ee.dim(` A person already ${i.questionClosed} this same claim, so it is not asked again.`):Ee.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Ee.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))}));let t=o.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");t.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(Qt(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await Xt(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Ee.dim(" no fact proposals waiting"));return}for(let r of i)console.log(` ${Ee.cyan(r.id)} ${r.status==="pending"?"":Ee.dim(`[${r.status}] `)}${r.claim}`),console.log(Ee.dim(` ${r.agentId} \xB7 ${r.origin} \xB7 ${r.source} \xB7 ${r.verifiedAt.slice(0,10)}`));console.log(Ee.dim(`
420
- Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),t.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(Qt(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await Xt(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Ee.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))})),t.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(Qt(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await Xt(s.dir),n,s.by,s.reason);console.log(Ee.dim(` rejected: ${r.claim}`))}))}import{resolve as q,relative as Bg,dirname as Jg}from"path";import{execSync as mt}from"child_process";import{writeFileSync as pt,mkdirSync as To,readFileSync as Fn,readdirSync as Py,renameSync as zs,rmSync as My,existsSync as Qe}from"fs";function Oe(e,o){return new fi(ut(e),void 0,o||"graph")}function ut(e){return e||q(process.cwd(),".agentx/wiki")}function Or(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var ee=new Dy().name("wiki").description("wiki knowledge base management");Wg(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 o=e.mode,t=Oe(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Or(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});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 o=Oe(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let r of t){let c=o.getAgentWiki(r).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(r)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(r)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-CH7R756S.js"),i=s(ut(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 o=e.mode,t=Oe(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=q(process.cwd(),".agentx/graph");return Qe(u)?new Io({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 b=c(k);if(!b?.length)continue;let $=b.join("/"),E=p.get($);E?E.n++:p.set($,{path:b,n:1})}if(p.size===0)return;let 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=t.getUnabsorbedEntries(u).filter(v=>!f||(v.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let v of p.slice(0,3))console.log(m.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let h=t.getAgentWiki(u),w=h.rebuildIndex(),k=h.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
429
+ `))}import{Command as cw}from"commander";import m from"chalk";import Ee from"chalk";import{resolve as rw}from"path";var aw=e=>e||rw(process.cwd(),".agentx/wiki");async function en(e){let{FactLedger:o}=await import("./ledger-CH7R756S.js");return new o(aw(e))}function on(e){return async(...o)=>{try{await e(...o)}catch(t){t?.name!=="LedgerCorruptError"&&console.error(Ee.red(` ${t?.message??t}`)),process.exitCode=1}}}function im(e){let o=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");o.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(on(async n=>{let{isStaleFact:s}=await import("./ledger-CH7R756S.js"),i=(await en(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(Ee.dim(" no facts recorded"));return}for(let r of i){let a=r.undated?Ee.yellow(" UNCHECKED"):s(r)?Ee.yellow(" STALE"):"";console.log(` ${Ee.cyan(r.id)} ${Ee.bold(r.subject)} \xB7 ${r.attribute}: ${r.value}${a}`),console.log(Ee.dim(` ${r.volatility} \xB7 ${r.source} \xB7 checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy}`))}})),o.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(on(async(n,s)=>{let i=(await en(s.dir)).get(n);if(!i){console.error(Ee.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(i,null,2))})),o.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${Ei.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(on(async n=>{if(n.class&&!Ra(n.class)){console.error(Ee.red(` --class must be one of ${Ei.join(", ")}`)),process.exitCode=1;return}let i=(await en(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(Ee.yellow(` not replaced: the wiki says "${i.fact.value}" (checked ${i.fact.verifiedAt.slice(0,10)}), ${r}.`)),console.log(i.questionId?Ee.dim(` Queued question ${i.questionId}: agentx wiki questions \xB7 agentx wiki answer ${i.questionId} "<true value>"`):i.questionClosed?Ee.dim(` A person already ${i.questionClosed} this same claim, so it is not asked again.`):Ee.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Ee.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))}));let t=o.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");t.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(on(async n=>{let{listFactProposals:s}=await import("./fact-proposals-LZWS5KFO.js"),i=s(await en(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(Ee.dim(" no fact proposals waiting"));return}for(let r of i)console.log(` ${Ee.cyan(r.id)} ${r.status==="pending"?"":Ee.dim(`[${r.status}] `)}${r.claim}`),console.log(Ee.dim(` ${r.agentId} \xB7 ${r.origin} \xB7 ${r.source} \xB7 ${r.verifiedAt.slice(0,10)}`));console.log(Ee.dim(`
430
+ Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),t.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(on(async(n,s)=>{let{approveFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),{write:r}=i(await en(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Ee.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))})),t.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(on(async(n,s)=>{let{rejectFactProposal:i}=await import("./fact-proposals-LZWS5KFO.js"),r=i(await en(s.dir),n,s.by,s.reason);console.log(Ee.dim(` rejected: ${r.claim}`))}))}import{resolve as q,relative as rm,dirname as am}from"path";import{execSync as ft}from"child_process";import{writeFileSync as ht,mkdirSync as Oo,readFileSync as Hn,readdirSync as lw,renameSync as Zs,rmSync as dw,existsSync as Ze}from"fs";function Oe(e,o){return new Si(yt(e),void 0,o||"graph")}function yt(e){return e||q(process.cwd(),".agentx/wiki")}function qr(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var oe=new cw().name("wiki").description("wiki knowledge base management");im(oe);oe.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=Oe(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${qr(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});oe.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let o=Oe(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let r of t){let c=o.getAgentWiki(r).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(r)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(r)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-CH7R756S.js"),i=s(yt(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()});oe.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=Oe(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=q(process.cwd(),".agentx/graph");return Ze(u)?new Ro({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 b=c(k);if(!b?.length)continue;let $=b.join("/"),E=p.get($);E?E.n++:p.set($,{path:b,n:1})}if(p.size===0)return;let 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=t.getUnabsorbedEntries(u).filter(v=>!f||(v.date??"")>=f).slice(0,s);if(p.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${p.length} entries to absorb`));for(let v of p.slice(0,3))console.log(m.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(p.length>3&&console.log(m.dim(` ... and ${p.length-3} more`)),e.dryRun)continue;let h=t.getAgentWiki(u),w=h.rebuildIndex(),k=h.getWorldview()||t.getSharedStore().getWorldview()||"",b=p.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
421
431
  ${v.content}
422
432
  --- END ENTRY ---`).join(`
423
433
 
424
- `),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-U7BUYRXN.js");if(!a){let J=new Set;for(let Ce of t.listAgents())for(let xe of t.getAgentWiki(Ce).listArticles(Ce))xe.meta.type==="person"&&J.add(xe.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:Ce,results:xe}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=I([...me,...Ce]);$=C(M);let Xe=[...me.length>0?[`entries:${me.length}`]:[],...xe.filter(Se=>Se.records.length>0).map(Se=>`${Se.source}:${Se.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Xe.length?` (${Xe.join(" ")})`:""}`));for(let Se of P(xe,J))console.log(m.yellow(` ! ${Se.source} ${Se.kind} \u2014 would supply ${Se.provides.join(", ")}`)),console.log(m.dim(` ${Se.hint}`))}}let E=ec(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${Or(o)}`));let S=q(h.baseDir,"_tmp");To(S,{recursive:!0});let x=q(S,"absorb-prompt.txt");pt(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=mt(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:$t({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let I,C=[],P=R.indexOf("{"),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,Ce=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){Ce=M+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let xe=R.slice(L,Ce);try{let M=JSON.parse(xe);Array.isArray(M)?I=M:(I=M.articles||[],C=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${xe.slice(0,300)}`));continue}for(let M of I){let Xe=new Date().toISOString().slice(0,10),Se=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:Xe,lastUpdated:Xe,sources:M.sources||[],graphPath:Se},M.content,u);let Xo=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("+")} ${Xo}${M.path}: ${M.title}${m.dim(_)}`);let we=(M.tags||[]).slice(0,4).join(", ");we&&console.log(m.dim(` tags: ${we}`)),Se?.length&&(console.log(m.dim(` graphPath: ${Se.join(" \u203A ")}`)),d++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let M of C)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Xe=new M(ut(e.dir)).add(C.map(Se=>({kind:"article",agentId:u,path:"",subject:String(Se).slice(0,120),question:`No article yet for: ${String(Se).slice(0,160)}`})));Xe.added>0&&console.log(m.dim(` queued ${Xe.added} for follow-up (agentx wiki questions)`))}catch{}}h.rebuildIndex()}catch(v){console.log(m.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(m.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(m.dim("stdout: "+String(v.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ee.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=Ly(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-IPJWEXR2.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!Qe(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Qe(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let h=p[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await oc({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var Vs=ee.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Ys(e){return e?q(e):q(process.cwd(),".agentx","wiki")}Vs.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(Ys(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});Vs.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(Ys(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
434
+ `),$="";if(e.facts!==!1){let{extractHints:v,resolveFacts:R,mergeRecords:I,renderFactsBlock:j,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-5T5GRUTG.js");if(!a){let J=new Set;for(let Ce of t.listAgents())for(let xe of t.getAgentWiki(Ce).listArticles(Ce))xe.meta.type==="person"&&J.add(xe.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}),pe=L(p);if(G.length>0||pe.length>0){let J=B(),{records:Ce,results:xe}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=I([...pe,...Ce]);$=j(M);let Qe=[...pe.length>0?[`entries:${pe.length}`]:[],...xe.filter(Se=>Se.records.length>0).map(Se=>`${Se.source}:${Se.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Qe.length?` (${Qe.join(" ")})`:""}`));for(let Se of P(xe,J))console.log(m.yellow(` ! ${Se.source} ${Se.kind} \u2014 would supply ${Se.provides.join(", ")}`)),console.log(m.dim(` ${Se.hint}`))}}let E=gc(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${qr(o)}`));let S=q(h.baseDir,"_tmp");Oo(S,{recursive:!0});let x=q(S,"absorb-prompt.txt");ht(x,E),console.log(m.dim(" Compiling with Claude..."));try{let v;try{v=ft(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:vt({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(v=M.stdout||"",!v)throw M}let R=v;try{let M=JSON.parse(v);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let I,j=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],pe=G==="{"?"}":"]",J=0,Ce=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===pe&&(J--,J===0)){Ce=M+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let xe=R.slice(L,Ce);try{let M=JSON.parse(xe);Array.isArray(M)?I=M:(I=M.articles||[],j=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${xe.slice(0,300)}`));continue}for(let M of I){let Qe=new Date().toISOString().slice(0,10),Se=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:Qe,lastUpdated:Qe,sources:M.sources||[],graphPath:Se},M.content,u);let et=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("+")} ${et}${M.path}: ${M.title}${m.dim(_)}`);let we=(M.tags||[]).slice(0,4).join(", ");we&&console.log(m.dim(` tags: ${we}`)),Se?.length&&(console.log(m.dim(` graphPath: ${Se.join(" \u203A ")}`)),d++),g++}if(j.length>0){console.log(),console.log(m.yellow(` Gaps detected (${j.length} missing pieces):`));for(let M of j)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Qe=new M(yt(e.dir)).add(j.map(Se=>({kind:"article",agentId:u,path:"",subject:String(Se).slice(0,120),question:`No article yet for: ${String(Se).slice(0,160)}`})));Qe.added>0&&console.log(m.dim(` queued ${Qe.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()});oe.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let o=gw(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-FBDLPU6H.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!Ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-PBPF45GN.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!Ze(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let 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 mc({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var ei=oe.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function oi(e){return e?q(e):q(process.cwd(),".agentx","wiki")}ei.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:o}=await import("./proposals-O4B5LD5T.js"),t=o(oi(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});ei.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(oi(o.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
425
435
  `).map(s=>` ${s}`).join(`
426
- `)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Vs.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-NDC3X54P.js"),n=t(Ys(o.dir),e,{force:o.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});Vs.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{rejectProposal:t}=await import("./promote-NDC3X54P.js"),n=t(Ys(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Ly(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ee.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-F7BD3JPE.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Oe(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let w of f){let k=r(d,w),b=[];try{b=t(k).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of b){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
436
+ `)),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>)`))}});ei.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{approveProposal:t}=await import("./promote-ZZWMGVO2.js"),n=t(oi(o.dir),e,{force:o.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});ei.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,o)=>{let{rejectProposal:t}=await import("./promote-ZZWMGVO2.js"),n=t(oi(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function gw(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}oe.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",q(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-OQBB7EFS.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Oe(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let w of f){let k=r(d,w),b=[];try{b=t(k).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of b){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
427
437
  `)||"_(none returned)_",E;try{let S=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")E=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map(v=>`\`${v.title}\` [${v.type||"?"}]`).join(", ");E=`**Answer:**
428
438
 
429
439
  ${S.answer}
430
440
 
431
441
  **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)","",$,"","### NEW \u2014 agentic query","",E,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let h=p.join(`
432
- `);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 o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-NZOBHQGS.js"),s=e.answers?Fn(e.answers,"utf-8").split(/\r?\n/).filter(_=>_.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=Oe(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(_){console.log(m.red(` can't open wiki for agent "${e.agent}": ${_.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async _=>{if(s){let we=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${we.slice(0,80)}${we.length>80?"\u2026":""}`)+`
433
- `),we.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 we=p[_],eo=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${we}
434
- ${m.green(">")} `);if(eo==="/abort"){w=!0;break}if(eo==="/done")break;eo!=="/skip"&&eo&&h.push({q:we,a:eo})}if(!w){let _=await l(`
442
+ `);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))});oe.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-NZOBHQGS.js"),s=e.answers?Hn(e.answers,"utf-8").split(/\r?\n/).filter(_=>_.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=Oe(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(_){console.log(m.red(` can't open wiki for agent "${e.agent}": ${_.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async _=>{if(s){let we=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${we.slice(0,80)}${we.length>80?"\u2026":""}`)+`
443
+ `),we.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 we=p[_],oo=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${we}
444
+ ${m.green(">")} `);if(oo==="/abort"){w=!0;break}if(oo==="/done")break;oo!=="/skip"&&oo&&h.push({q:we,a:oo})}if(!w){let _=await l(`
435
445
  ${m.dim("Anything else worth capturing?")}
436
446
  ${m.green(">")} `);_&&_!=="/abort"&&_!=="/done"&&h.push({q:"Anything else worth capturing?",a:_})}if(w||h.length===0){console.log(m.yellow(`
437
447
  Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(_=>`- ${_.meta.title} [${_.meta.type||"?"}]`).join(`
438
448
  `),$=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${g}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...h.map(_=>`
439
449
  Q: ${_.q}
440
450
  A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
441
- `),E=q(a.baseDir,"_tmp");To(E,{recursive:!0});let S=q(E,`interview-${t().slice(0,8)}.txt`);pt(S,$),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,we=mt(_,{env:$t({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let eo=JSON.parse(we);x=String(eo.result||eo.content||"")}catch{x=we}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let v=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(x=v[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let I=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!I){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let C={};for(let _ of I[1].split(`
442
- `)){let we=_.match(/^(\w+):\s*(.+)$/);we&&(C[we[1]]=we[2].trim().replace(/^"(.*)"$/,"$1"))}let P=I[2],B=C.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 Ce=P,xe={title:B,type:C.type||d,related:C.related?C.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:C.tags?C.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:C.access||"public",created:C.created||new Date().toISOString().slice(0,10),lastUpdated:C.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",we=q(E,`draft-${t().slice(0,8)}.md`);pt(we,x);try{mt(`${_} '${we}'`,{stdio:"inherit"});let mi=Fn(we,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(mi){let jo={};for(let pn of mi[1].split(`
443
- `)){let pi=pn.match(/^(\w+):\s*(.+)$/);pi&&(jo[pi[1]]=pi[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=mi[2],xe={...xe,title:jo.title||xe.title,type:jo.type||xe.type,access:jo.access||xe.access,related:jo.related?jo.related.replace(/^\[|\]$/g,"").split(",").map(pn=>pn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):xe.related,tags:jo.tags?jo.tags.replace(/^\[|\]$/g,"").split(",").map(pn=>pn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):xe.tags}}}catch(eo){console.log(m.red(` editor failed: ${eo.message}`));return}}if(!a.writeArticle(me,xe,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Xe=a.extractWikilinks(Ce),Se=new Map;for(let _ of a.listArticles(e.agent))Se.set(_.meta.title.toLowerCase(),!0);let Xo=Xe.filter(_=>!Se.has(_.toLowerCase()));if(Xo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Xo.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ee.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-F7BD3JPE.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Oe(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=Fn(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);r=[];for(let h of p){let w=h.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),b=w.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,h;if(r){let G=r[f];if(!G)break;p=G.q,h=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let G=w.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
444
- `)),console.log(m.dim(" citations: "+G))}r||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let k={q:p,answer:w.answer,citations:w.citations,verdict:h},b=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let $=b[1].toLowerCase(),E=(b[2]||"").trim();if(d.push(k),$==="/ok"||$==="/skip")continue;if(!E){console.log(m.yellow(` ${$} without note \u2014 skipping.`));continue}let S=w.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let v=Uy(x.content,$,E,x.meta.title,x.meta.type),R=q(i.baseDir,"_tmp");To(R,{recursive:!0});let I=q(R,`quiz-patch-${t().slice(0,8)}.txt`);pt(I,v);let C="";try{let G=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=mt(G,{env:$t({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(me);C=String(Ce.result||Ce.content||"")}catch{C=me}let J=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(C=J[1].trim()),C=C.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
445
- `).length,B=C.split(`
446
- `).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)},C,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let 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}\``:""),"")}pt(e.out,f.join(`
447
- `)),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,o,t)=>{let n=Oe(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=zg(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{mt(`${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,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=Oe(n.dir),a;try{a=r.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=zg(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=qy(l.content,l.meta.title,l.meta.type,t),d=q(a.baseDir,"_tmp");To(d,{recursive:!0});let u=q(d,`patch-${i().slice(0,8)}.txt`);pt(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=mt(S,{env:$t({...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(`
451
+ `),E=q(a.baseDir,"_tmp");Oo(E,{recursive:!0});let S=q(E,`interview-${t().slice(0,8)}.txt`);ht(S,$),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,we=ft(_,{env:vt({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let oo=JSON.parse(we);x=String(oo.result||oo.content||"")}catch{x=we}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let v=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);v&&(x=v[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let I=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!I){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let j={};for(let _ of I[1].split(`
452
+ `)){let we=_.match(/^(\w+):\s*(.+)$/);we&&(j[we[1]]=we[2].trim().replace(/^"(.*)"$/,"$1"))}let P=I[2],B=j.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),pe=`${{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: ${pe}`)),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 Ce=P,xe={title:B,type:j.type||d,related:j.related?j.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:j.tags?j.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:j.access||"public",created:j.created||new Date().toISOString().slice(0,10),lastUpdated:j.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",we=q(E,`draft-${t().slice(0,8)}.md`);ht(we,x);try{ft(`${_} '${we}'`,{stdio:"inherit"});let wi=Hn(we,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(wi){let Io={};for(let hn of wi[1].split(`
453
+ `)){let $i=hn.match(/^(\w+):\s*(.+)$/);$i&&(Io[$i[1]]=$i[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=wi[2],xe={...xe,title:Io.title||xe.title,type:Io.type||xe.type,access:Io.access||xe.access,related:Io.related?Io.related.replace(/^\[|\]$/g,"").split(",").map(hn=>hn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):xe.related,tags:Io.tags?Io.tags.replace(/^\[|\]$/g,"").split(",").map(hn=>hn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):xe.tags}}}catch(oo){console.log(m.red(` editor failed: ${oo.message}`));return}}if(!a.writeArticle(pe,xe,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${pe} saved.`));let Qe=a.extractWikilinks(Ce),Se=new Map;for(let _ of a.listArticles(e.agent))Se.set(_.meta.title.toLowerCase(),!0);let et=Qe.filter(_=>!Se.has(_.toLowerCase()));if(et.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of et.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});oe.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-OQBB7EFS.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Oe(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=Hn(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);r=[];for(let h of p){let w=h.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),b=w.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,h;if(r){let G=r[f];if(!G)break;p=G.q,h=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let G=w.citations.map(pe=>`${pe.title} [${pe.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
454
+ `)),console.log(m.dim(" citations: "+G))}r||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let k={q:p,answer:w.answer,citations:w.citations,verdict:h},b=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let $=b[1].toLowerCase(),E=(b[2]||"").trim();if(d.push(k),$==="/ok"||$==="/skip")continue;if(!E){console.log(m.yellow(` ${$} without note \u2014 skipping.`));continue}let S=w.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let v=pw(x.content,$,E,x.meta.title,x.meta.type),R=q(i.baseDir,"_tmp");Oo(R,{recursive:!0});let I=q(R,`quiz-patch-${t().slice(0,8)}.txt`);ht(I,v);let j="";try{let G=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,pe=ft(G,{env:vt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(pe);j=String(Ce.result||Ce.content||"")}catch{j=pe}let J=j.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(j=J[1].trim()),j=j.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!j||j.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
455
+ `).length,B=j.split(`
456
+ `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},j,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let h=d[p];f.push(`## ${p+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}ht(e.out,f.join(`
457
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});oe.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=Oe(t.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=dm(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=q(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{ft(`${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)}`))}});oe.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=Oe(n.dir),a;try{a=r.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=dm(a,o,e);if(!c){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let g=mw(l.content,l.meta.title,l.meta.type,t),d=q(a.baseDir,"_tmp");Oo(d,{recursive:!0});let u=q(d,`patch-${i().slice(0,8)}.txt`);ht(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=ft(S,{env:vt({...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(`
448
458
  `).length,h=f.split(`
449
- `).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,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let E=(l.meta.related||[]).filter(S=>!b.includes(S));E.length&&console.log(m.dim(` (pruned stale related: ${E.slice(0,3).join(", ")}${E.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function zg(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function qy(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
450
- `)}function Uy(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
459
+ `).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,b=a.extractWikilinks(f).filter(S=>k.has(S)?!1:(k.add(S),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let E=(l.meta.related||[]).filter(S=>!b.includes(S));E.length&&console.log(m.dim(` (pruned stale related: ${E.slice(0,3).join(", ")}${E.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function dm(e,o,t){let n=o.trim(),s=e.listArticles(t),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function mw(e,o,t,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${o}" (type: ${t||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
460
+ `)}function pw(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
451
461
 
452
462
  ${t}
453
463
 
@@ -460,8 +470,8 @@ Incorporate it into the most relevant existing section, or create a short new se
460
470
  ${t}
461
471
 
462
472
  Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${t}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${n}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",i[o]||`Make a minimal edit per: ${t}`,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
463
- `)}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 o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,g=0;for(let d of t){let u=q(s,"agents",d);if(!Qe(u))continue;let f=q(u,i),p=r.map(b=>({mode:b,dir:q(u,b)})).filter(b=>Qe(b.dir));if(p.length===0)continue;let h=new Map;Tr(f,b=>{let $=Bg(f,b);if($.startsWith("_")||$.startsWith("raw/")||$.includes("_tmp/"))return;let E=Hg(Fn(b,"utf-8"));E?.meta.title&&h.set(E.meta.title.trim().toLowerCase(),{relPath:$,type:E.meta.type,lastUpdated:E.meta.lastUpdated||""})});let w=[];for(let b of p)Tr(b.dir,$=>{let E=Bg(b.dir,$);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=Hg(Fn($,"utf-8"));S?.meta.title&&w.push({mode:b.mode,relPath:E,absPath:$,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${k}`));for(let b of w){let $=b.title.toLowerCase(),E=h.get($),S;E?!E.type&&b.type||!!E.type==!!b.type&&b.lastUpdated&&E.lastUpdated&&b.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),v=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${v} ${x} ${m.dim(b.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${E.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let I=q(f,b.relPath);Qe(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Gg(u,b),g++):(To(Jg(I),{recursive:!0}),zs(b.absPath,I),h.set($,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let I=q(f,E.relPath);if(Qe(I)){let C=q(u,"_versions",E.relPath.replace(/\.md$/,""));To(C,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");zs(I,q(C,`${P}.md`))}To(Jg(I),{recursive:!0}),zs(b.absPath,I),h.set($,{relPath:E.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else Gg(u,b),g++}catch(I){console.log(m.red(` ! ${S} failed: ${I.message?.slice(0,120)}`))}}if(n){for(let b of p)try{My(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Tr(e,o){if(Qe(e))for(let t of Py(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?Tr(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Hg(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
464
- `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function Gg(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));To(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");zs(o.absPath,q(t,`${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 o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let h=g.baseDir,w=q(h,"_tmp");To(w,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),$=Wy(b),E=q(w,"migrate-prompt.txt");pt(E,$);let S;try{let x=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=mt(x,{env:$t({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(v),C=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!C)throw new Error("no JSON array in classifier response");S=JSON.parse(C[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let v=S.find(L=>L.path===x.path),R=Fy(v?.type);if(!v||!R){console.log(m.yellow(` ? ${x.path}: unclassified${v?` (got "${v.type}")`:""}`));continue}let I=g.extractWikilinks(x.content),C={...x.meta,type:R.type,related:I.length?I:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=I.length?m.dim(` \u2192 ${I.slice(0,3).join(", ")}${I.length>3?", \u2026":""}`):"",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,C,x.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Fy(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function Wy(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
473
+ `)}oe.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?q(e.dir):q(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,g=0;for(let d of t){let u=q(s,"agents",d);if(!Ze(u))continue;let f=q(u,i),p=r.map(b=>({mode:b,dir:q(u,b)})).filter(b=>Ze(b.dir));if(p.length===0)continue;let h=new Map;Lr(f,b=>{let $=rm(f,b);if($.startsWith("_")||$.startsWith("raw/")||$.includes("_tmp/"))return;let E=cm(Hn(b,"utf-8"));E?.meta.title&&h.set(E.meta.title.trim().toLowerCase(),{relPath:$,type:E.meta.type,lastUpdated:E.meta.lastUpdated||""})});let w=[];for(let b of p)Lr(b.dir,$=>{let E=rm(b.dir,$);if(E.startsWith("_")||E.startsWith("raw/")||E.includes("_tmp/"))return;let S=cm(Hn($,"utf-8"));S?.meta.title&&w.push({mode:b.mode,relPath:E,absPath:$,title:S.meta.title.trim(),type:S.meta.type,lastUpdated:S.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let k=p.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(d)}: ${w.length} legacy article(s) across ${k}`));for(let b of w){let $=b.title.toLowerCase(),E=h.get($),S;E?!E.type&&b.type||!!E.type==!!b.type&&b.lastUpdated&&E.lastUpdated&&b.lastUpdated>E.lastUpdated?S="upgrade":S="archive":S="promote";let x=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),v=S==="promote"?m.green("\u2192 promote "):S==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),R=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${v} ${x} ${m.dim(b.mode+"/")}${R}`),S==="upgrade"&&console.log(m.dim(` (replaces ${E.relPath}, old version kept under _versions/)`)),!n){S==="promote"?c++:S==="upgrade"?l++:g++;continue}try{if(S==="promote"){let I=q(f,b.relPath);Ze(I)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),lm(u,b),g++):(Oo(am(I),{recursive:!0}),Zs(b.absPath,I),h.set($,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(S==="upgrade"){let I=q(f,E.relPath);if(Ze(I)){let j=q(u,"_versions",E.relPath.replace(/\.md$/,""));Oo(j,{recursive:!0});let P=new Date().toISOString().replace(/[:.]/g,"-");Zs(I,q(j,`${P}.md`))}Oo(am(I),{recursive:!0}),Zs(b.absPath,I),h.set($,{relPath:E.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else lm(u,b),g++}catch(I){console.log(m.red(` ! ${S} failed: ${I.message?.slice(0,120)}`))}}if(n){for(let b of p)try{dw(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(d).rebuildIndex()}catch(b){console.log(m.dim(` (catalog rebuild skipped: ${b.message?.slice(0,80)})`))}}}console.log(),console.log(m.dim(` Legacy scanned: ${a}`)),n?(console.log(m.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${g}`)),console.log(m.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(m.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${g}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Lr(e,o){if(Ze(e))for(let t of lw(e,{withFileTypes:!0})){let n=q(e,t.name);t.isDirectory()?Lr(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function cm(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
474
+ `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];t[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:t}}function lm(e,o){let t=q(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));Oo(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Zs(o.absPath,q(t,`${n}.md`))}oe.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(m.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(m.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of t){let g=o.getAgentWiki(l),d=g.listArticles(l),u=d.filter(k=>!k.meta.type);if(r+=d.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${d.length} articles)`);continue}let f=Math.max(0,s-c),p=Math.min(u.length,f);if(p===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${p}/${u.length} untyped articles`));let h=g.baseDir,w=q(h,"_tmp");Oo(w,{recursive:!0});for(let k=0;k<p;k+=n){let b=u.slice(k,Math.min(k+n,p)),$=fw(b),E=q(w,"migrate-prompt.txt");ht(E,$);let S;try{let x=`cat '${E}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,v=ft(x,{env:vt({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),R=JSON.parse(v),j=String(R.result||R.content||"").match(/\[[\s\S]*\]/);if(!j)throw new Error("no JSON array in classifier response");S=JSON.parse(j[0])}catch(x){console.log(m.red(` LLM classify failed: ${x.message?.slice(0,150)}`));continue}for(let x of b){let v=S.find(L=>L.path===x.path),R=uw(v?.type);if(!v||!R){console.log(m.yellow(` ? ${x.path}: unclassified${v?` (got "${v.type}")`:""}`));continue}let I=g.extractWikilinks(x.content),j={...x.meta,type:R.type,related:I.length?I:void 0,lastUpdated:new Date().toISOString().slice(0,10)},P=I.length?m.dim(` \u2192 ${I.slice(0,3).join(", ")}${I.length>3?", \u2026":""}`):"",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,j,x.content,l),c++)}}i&&g.rebuildIndex()}console.log(),console.log(m.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?m.green(` Applied ${c} patches.`):m.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function uw(e){if(!e)return null;let o=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!o)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[o];return n?n===o?{type:n}:{type:n,alias:o}:null}function fw(e){let o=e.map((t,n)=>{let s=t.content.replace(/\s+/g," ").slice(0,400),i=(t.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${t.path}"
465
475
  title: "${t.meta.title}"
466
476
  tags: [${i}]
467
477
  body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
@@ -501,51 +511,51 @@ Output (JSON array, one entry per input article, same order):
501
511
  [
502
512
  {"path": "path/to/article.md", "type": "project"},
503
513
  ...
504
- ]`}ee.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});ee.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-4WZ7Y34V.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),vl(o,t,e.agent,n,e.mode)});ee.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-TOM2WHQR.js"),c=Oe(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let b of k.listArticles(w)){if(u.length>=g)break e;let $=k.readArticle(b.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...o($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,t({path:b.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:b.path}],features:{agent:w,type:$.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),v=e.fields?r($.meta.type,S.answers):null;x.completeness>=d&&!(v&&!v.fit)||u.push({agent:w,type:$.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...v?{missing:v.missingCritical.join(",")||"-",cov:`${Math.round(v.coverage*100)}%`}:{},title:$.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),h=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(h(f)));for(let w of u)console.log(h(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
514
+ ]`}oe.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});oe.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-JCETBKWT.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),_l(o,t,e.agent,n,e.mode)});oe.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-2HJG3UNW.js"),c=Oe(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let b of k.listArticles(w)){if(u.length>=g)break e;let $=k.readArticle(b.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...o($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,t({path:b.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:b.path}],features:{agent:w,type:$.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),v=e.fields?r($.meta.type,S.answers):null;x.completeness>=d&&!(v&&!v.fit)||u.push({agent:w,type:$.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...v?{missing:v.missingCritical.join(",")||"-",cov:`${Math.round(v.coverage*100)}%`}:{},title:$.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),h=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(h(f)));for(let w of u)console.log(h(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
505
515
  ${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(`
506
- ${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});ee.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-F7BD3JPE.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=q(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ee.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Oe(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});ee.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Qe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Io({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),h=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of $.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),I=s.fingerprint({text:v.content,channel:v.source,sender:R}),C=r.get(I);if(!C?.length)continue;let P=C.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:C,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ee.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-4WZ7Y34V.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ee.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new fi(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,h=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);h+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Or(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ee.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Qe(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Qe(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${By(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ee.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-TOM2WHQR.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let I=v.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let C=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:I.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,C.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:I.meta.title,field:B.field,tier:B.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:I.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(ut(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),$=(x,v)=>String(x)+" ".repeat(Math.max(0,b[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>$(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>$(x[v],R)).join(" "));let E=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(I=>(x[I.tier??"furniture"]??9)<=v);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-4WZ7Y34V.js"),C=I(),P=C?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
516
+ ${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."))});oe.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-OQBB7EFS.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=q(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});oe.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=Oe(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});oe.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!Ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Ro({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),h=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let x of $.meta.sources){let v=h.get(x);if(!v)continue;let R=String(v.meta?.sender??""),I=s.fingerprint({text:v.content,channel:v.source,sender:R}),j=r.get(I);if(!j?.length)continue;let P=j.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:j,n:1})}if(E.size===0)continue;k++,l++;let S;for(let x of E.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});oe.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-JCETBKWT.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});oe.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Si(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,h=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);h+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:qr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});oe.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Ze(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${hw(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});oe.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-2HJG3UNW.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let v=l.getAgentWiki(x);for(let R of v.listArticles(x)){if(f>=u)break e;let I=v.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let j=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:I.meta.type??"?"}});if(!j){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,j.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:I.meta.title,field:B.field,tier:B.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:I.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(yt(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(x=>Math.max(x.length,...p.map(v=>k(v[x]).length))),$=(x,v)=>String(x)+" ".repeat(Math.max(0,b[v]-k(x).length));console.log(),console.log(m.bold(w.map((x,v)=>$(x,v)).join(" ")));for(let x of p)console.log(w.map((v,R)=>$(x[v],R)).join(" "));let E=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),v=x[e.notifyTier]??x.pillar,R=g.filter(I=>(x[I.tier??"furniture"]??9)<=v);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-JCETBKWT.js"),j=I(),P=j?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
507
517
  `),L=R.length>10?`
508
518
  \u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
509
519
  ${B}${L}
510
520
 
511
- agentx wiki questions`,me=C?.daemon?.port??C?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ee.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-TOM2WHQR.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-U7BUYRXN.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],x=!1;e:for(let C of p){let P=f.getAgentWiki(C);for(let B of P.listArticles(C)){if($>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:C,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Ce,results:xe}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(xe,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Xe=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,we])=>[_,we.value]))}]:[],...Ce]);if(Xe.length===0)continue;let{content:Se,edits:Xo}=u(L.content,Xe[0],J);if(Xo.length!==0){for(let _ of Xo)S.push({agent:C,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,Se,C)?E++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(C=>Math.max(C.length,...S.map(P=>String(P[C]).length))),I=C=>C.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(I(v)));for(let C of S)console.log(I(v.map(P=>C[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ee.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(ut(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});ee.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ut(t.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(ut(t.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Oe(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ee.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-TOM2WHQR.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:me.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),C=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:I,failures:S,elapsed:C},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),v.lostPositives>0){let L=v.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let 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(` ${C}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points: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((Ce,xe)=>xe.recall-Ce.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ee.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);Qe(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Qe(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function By(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"}ep();import{Command as Jy}from"commander";import D from"chalk";import{resolve as Ks}from"path";import{existsSync as Hy}from"fs";ne();var Zt=new Jy().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Zt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=j();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new Io({baseDir:Ks(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let h=r[p],w=es(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=Gy(h,a,c),b=null;try{b=await zy(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{Vy(i,h,a,c,t),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Zt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=j();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Ks(process.cwd(),o.graph.baseDir);if(!Hy(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Io({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Zt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=j();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new Io({baseDir:Ks(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let v=await fetch(`${t}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);d=(await C.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let v of k){if(c.has(v.id)){$++;continue}if(e.dryRun){b++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${t}`}),c.add(v.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function Gy(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
521
+ agentx wiki questions`,pe=j?.daemon?.port??j?.port??18800;try{let J=await fetch(`http://127.0.0.1:${pe}/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.`))}}}}});oe.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-2HJG3UNW.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-5T5GRUTG.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(j=>[j.name.toLowerCase().trim(),j])),$=0,E=0,S=[],x=!1;e:for(let j of p){let P=f.getAgentWiki(j);for(let B of P.listArticles(j)){if($>=h)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:j,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=t(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Ce,results:xe}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(xe,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Qe=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,we])=>[_,we.value]))}]:[],...Ce]);if(Qe.length===0)continue;let{content:Se,edits:et}=u(L.content,Qe[0],J);if(et.length!==0){for(let _ of et)S.push({agent:j,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,Se,j)?E++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let v=["agent","article","field","action","got"],R=v.map(j=>Math.max(j.length,...S.map(P=>String(P[j]).length))),I=j=>j.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(I(v)));for(let j of S)console.log(I(v.map(P=>j[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});oe.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(yt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});oe.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(yt(t.dir)),a=r.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!r.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let h=r.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-CH7R756S.js"),w=new h(yt(t.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Oe(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});oe.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-2HJG3UNW.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,h),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let pe=G.answers;E.push({entry:L,verdict:s(G.answers,$),citeWorthy:pe.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let v=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),j=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:v,calibration:I,failures:S,elapsed:j},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${v.n} (${v.positives} kept by absorb, ${v.negatives} passed over)`),console.log(` recall ${P(v.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(v.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(v.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${v.lostPositives>0?m.yellow(`lost ${v.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),v.lostPositives>0){let L=v.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=v.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${j}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:pe}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${pe.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=pe.slice().sort((Ce,xe)=>xe.recall-Ce.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."))}}});oe.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=q(process.cwd(),e);Ze(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");Ze(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function hw(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"}$p();import{Command as yw}from"commander";import D from"chalk";import{resolve as ti}from"path";import{existsSync as ww}from"fs";ee();var tn=new yw().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");tn.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=O();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new Ro({baseDir:ti(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let h=r[p],w=is(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=$w(h,a,c),b=null;try{b=await bw(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{kw(i,h,a,c,t),i.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});tn.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=O();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=ti(process.cwd(),o.graph.baseDir);if(!ww(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Ro({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});tn.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=O();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new Ro({baseDir:ti(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(v=>v.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let v=await fetch(`${t}/graph/schema`,{headers:s});if(!v.ok)throw new Error(`schema HTTP ${v.status}`);l=(await v.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let j=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!j.ok)throw new Error(`classifications HTTP ${j.status}`);d=(await j.json()).classifications||[]}catch(v){console.log(D.red(` fetch failed: ${v.message}`));return}let u=r.levels.map(v=>v.id).join(","),f=l?.levels?.map(v=>v.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let h=p?r:l,w=new Map;h.levels.forEach((v,R)=>w.set(v.id,R));let k=[...g].sort((v,R)=>(w.get(v.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let v of k){if(c.has(v.id)){$++;continue}if(e.dryRun){b++,c.add(v.id);continue}try{i.addNode({...v,createdBy:v.createdBy?`${v.createdBy} (sync)`:`sync:${t}`}),c.add(v.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${v.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,x=0;for(let v of d)if(!(!v.msgHash||!Array.isArray(v.path))){if(i.getFingerprint(v.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(v.msgHash,{path:v.path,leaf:v.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function $w(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
512
522
  `),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(`
513
- `)}async function zy(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return pa((c?.content||"").toString())}finally{clearTimeout(r)}}function Vy(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Cr(){let e=j();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=Ks(process.cwd(),e.graph.baseDir);return{store:new Io({baseDir:o}),baseDir:o}}var jr=Zt.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");jr.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let o=Cr();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(D.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(es(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]"))});jr.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=Cr();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${o}: ${es(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});jr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Cr();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?D.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as ew}from"commander";import Y from"chalk";import{Command as Yg}from"commander";import de from"chalk";import{existsSync as Yy}from"fs";import{resolve as Ky}from"path";import Xy from"better-sqlite3";function Qy(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(de.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Zy(e){let o=Ky(process.cwd(),e);return Yy(o)||(console.log(de.red(` No db at ${o}`)),process.exit(1)),new Xy(o,{readonly:!0})}var Kg=new Yg().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(wn)).option("--max <n>","max clusters distilled per run",String(ss)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(de.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Zy(e.path),t=await tc(o,{since:Qy(e.since),agentId:e.agent,sessions:new ba(process.cwd()),minOccurrences:Number(e.minOccurrences)||wn,max:Number(e.max)||ss,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(de.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${de.cyan(n.key)} ${de.bold(`\xD7${n.count}`)} ${de.dim(n.status)}`),n.sampleMessage&&console.log(de.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(de.dim(`
514
- near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(de.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(de.green(` \u2713 draft written: ${n.id}`)+de.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(de.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(de.yellow(` \u26A0 ${n}`));t.dryRun?console.log(de.dim(`
515
- dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(de.dim(`
516
- review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Vg={hourly:"0 * * * *",daily:"0 3 * * *"},Xg=new Yg().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(wn)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?Vg.hourly:e.daily?Vg.daily:void 0);!e.off&&!o&&!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 t=Number(e.minOccurrences)||wn,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${ss} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
517
- `),i=await pe(a=>{je(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&je(a,"crons.procedure-extract.enabled",!1):o&&je(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(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`)),o&&console.log(de.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(de.dim(" on-task counting: enabled")),console.log(de.dim(` threshold: ${t} occurrences`))),console.log(de.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var mo=new ew().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");mo.addCommand(Kg);mo.addCommand(Xg);mo.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new No,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(Y.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?Y.green(n.meta.status):n.meta.status==="draft"?Y.yellow(n.meta.status):Y.dim(n.meta.status);console.log(` ${Y.cyan(n.meta.id)} ${Y.bold(n.meta.title)} ${s}`),console.log(` ${Y.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${Y.dim("source:")} ${Y.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${Y.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(Y.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});mo.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new No,t=e.steps?String(e.steps):`## Steps
523
+ `)}async function bw(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Ea((c?.content||"").toString())}finally{clearTimeout(r)}}function kw(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Ur(){let e=O();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=ti(process.cwd(),e.graph.baseDir);return{store:new Ro({baseDir:o}),baseDir:o}}var Fr=tn.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 o=Ur();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(D.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(is(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,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){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:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${o}: ${is(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});Fr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Ur();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?D.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as Tw}from"commander";import V from"chalk";import{Command as mm}from"commander";import ge from"chalk";import{existsSync as vw}from"fs";import{resolve as xw}from"path";import Sw from"better-sqlite3";function Ew(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(ge.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Aw(e){let o=xw(process.cwd(),e);return vw(o)||(console.log(ge.red(` No db at ${o}`)),process.exit(1)),new Sw(o,{readonly:!0})}var pm=new mm().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(kn)).option("--max <n>","max clusters distilled per run",String(ls)).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(ge.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Aw(e.path),t=await pc(o,{since:Ew(e.since),agentId:e.agent,sessions:new Na(process.cwd()),minOccurrences:Number(e.minOccurrences)||kn,max:Number(e.max)||ls,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ge.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${ge.cyan(n.key)} ${ge.bold(`\xD7${n.count}`)} ${ge.dim(n.status)}`),n.sampleMessage&&console.log(ge.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ge.dim(`
524
+ near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ge.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ge.green(` \u2713 draft written: ${n.id}`)+ge.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ge.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ge.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ge.dim(`
525
+ dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(ge.dim(`
526
+ review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),gm={hourly:"0 * * * *",daily:"0 3 * * *"},um=new mm().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(kn)).option("--timezone <tz>","IANA timezone (default: this machine's)",Intl.DateTimeFormat().resolvedOptions().timeZone).option("-c, --config <path>","path to agentx.json").option("--dry-run","print what would be written without writing").action(async e=>{let o=e.off?void 0:e.cron??(e.hourly?gm.hourly:e.daily?gm.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(ge.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(ge.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||kn,n={enabled:!e.off,onTaskCompletion:!e.off&&!!e.onTask,minOccurrences:t,via:e.off?void 0:e.via},s=["Run this shell command EXACTLY as written. Do NOT substitute, rewrite, shorten, or fall back to alternative commands. If it exits non-zero, report the verbatim exit code and stderr and STOP.","",`1) cd ${process.cwd()} && node dist/cli.js procedure extract --since 7d --max ${ls} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
527
+ `),i=await se(a=>{je(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&je(a,"crons.procedure-extract.enabled",!1):o&&je(a,"crons.procedure-extract",{enabled:!0,schedule:o,timezone:e.timezone,agent:e.via,prompt:s,timeout:900,onError:"log"})},{configPath:e.config,dryRun:!!e.dryRun});i.success||(console.log(ge.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(ge.green(` \u2713 ${r} procedure extraction: off`)):(console.log(ge.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(ge.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(ge.dim(" on-task counting: enabled")),console.log(ge.dim(` threshold: ${t} occurrences`))),console.log(ge.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var po=new Tw().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");po.addCommand(pm);po.addCommand(um);po.command("list").description("list procedures with their trigger line").option("--drafts","list unreviewed drafts instead",!1).option("--all","list active procedures and drafts",!1).action(e=>{let o=new _o,t=[...e.drafts?[]:o.list(),...e.drafts||e.all?o.listDrafts():[]];if(!t.length){console.log(V.dim(e.drafts?" no procedure drafts. Mine some with: agentx procedure extract":" no procedures yet. Try: agentx procedure extract \xB7 or: agentx procedure add"));return}console.log();for(let n of t){let s=n.meta.status==="active"?V.green(n.meta.status):n.meta.status==="draft"?V.yellow(n.meta.status):V.dim(n.meta.status);console.log(` ${V.cyan(n.meta.id)} ${V.bold(n.meta.title)} ${s}`),console.log(` ${V.dim("trigger:")} ${n.meta.trigger}`),n.meta.source&&console.log(` ${V.dim("source:")} ${V.dim(n.meta.source)}`),n.meta.kpis?.length&&console.log(` ${V.dim("kpis:")} ${n.meta.kpis.join(", ")}`)}console.log(),console.log(V.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});po.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-peer)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,o=[])=>[...o,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,o=[])=>[...o,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,o=[])=>[...o,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,o=[])=>[...o,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let o=new _o,t=e.steps?String(e.steps):`## Steps
518
528
 
519
529
  1. (fill in)
520
530
 
521
531
  ## Notes
522
532
 
523
- `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(Y.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(Y.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(Y.red(` add failed: ${n.message}`)),process.exit(1)}});mo.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new No,t=o.get(e)??o.getDraft(e);t||(console.log(Y.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(Y.bold(` ${t.meta.title}`)+Y.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(Y.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(Y.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(Y.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(Y.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(Y.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(Y.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(Y.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});mo.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new No;try{let t=o.promoteDraft(e);console.log(Y.green(` \u2713 promoted: ${t.meta.id}`)),console.log(Y.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});mo.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new No;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});mo.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new No;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});mo.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new No,n=Da(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(Y.dim(" no matching procedures"));return}for(let s of n)console.log(` ${Y.cyan(s.procedure.meta.id)} ${Y.bold(s.score.toFixed(2))} ${Y.dim(s.reasons.join(", "))}`),console.log(Y.dim(` ${s.procedure.meta.trigger}`))});import{Command as nw}from"commander";import A from"chalk";import{resolve as on,basename as sw}from"path";import{existsSync as Ir,readFileSync as Nr,writeFileSync as Xs}from"fs";import VA from"better-sqlite3";import{readFileSync as ow}from"fs";import{resolve as en,dirname as Qg}from"path";import{fileURLToPath as tw}from"url";var Wn=[{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 Zg(e){let o=Qg(tw(import.meta.url)),t=process.argv[1]?Qg(process.argv[1]):"",n=[en(o,`${e}.yaml`),en(o,"workflows/templates",`${e}.yaml`),en(o,"..","workflows/templates",`${e}.yaml`),en(o,"../..","workflows/templates",`${e}.yaml`),t?en(t,"workflows/templates",`${e}.yaml`):"",t?en(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return ow(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
533
+ `;try{let n=o.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},t);console.log(V.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(V.dim(` ${o.baseDir}/${n.path}`))}catch(n){console.log(V.red(` add failed: ${n.message}`)),process.exit(1)}});po.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new _o,t=o.get(e)??o.getDraft(e);t||(console.log(V.yellow(` no procedure matches "${e}". Try: agentx procedure list --all`)),process.exit(1)),console.log(),console.log(V.bold(` ${t.meta.title}`)+V.dim(` (${t.meta.id}, ${t.meta.status})`)),console.log(V.dim(` trigger: ${t.meta.trigger}`)),t.meta.inputs?.length&&console.log(V.dim(` inputs: ${t.meta.inputs.join(", ")}`)),t.meta.expected&&console.log(V.dim(` expected: ${t.meta.expected}`)),t.meta.kpis?.length&&console.log(V.dim(` kpis: ${t.meta.kpis.join(", ")}`)),t.meta.owner&&console.log(V.dim(` owner: ${t.meta.owner}`)),t.meta.source&&console.log(V.dim(` source: ${t.meta.source}`)),t.meta.related?.length&&console.log(V.dim(` related: ${t.meta.related.join(", ")}`)),console.log(),console.log(t.body),console.log()});po.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new _o;try{let t=o.promoteDraft(e);console.log(V.green(` \u2713 promoted: ${t.meta.id}`)),console.log(V.dim(` agents will now follow it when a task matches: "${t.meta.trigger}"`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});po.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new _o;try{o.rejectDraft(e),console.log(V.green(` \u2713 rejected: ${e}`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});po.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new _o;try{o.deprecate(e),console.log(V.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});po.command("match <text>").description("find active procedures matching a task description").option("--limit <n>","max matches","3").option("--min-score <s>","minimum score 0..1","0.2").action((e,o)=>{let t=new _o,n=za(e,t.list(),{limit:Number(o.limit)||3,minScore:Number(o.minScore)||.2});if(!n.length){console.log(V.dim(" no matching procedures"));return}for(let s of n)console.log(` ${V.cyan(s.procedure.meta.id)} ${V.bold(s.score.toFixed(2))} ${V.dim(s.reasons.join(", "))}`),console.log(V.dim(` ${s.procedure.meta.trigger}`))});import{Command as jw}from"commander";import A from"chalk";import{resolve as sn,basename as Iw}from"path";import{existsSync as Wr,readFileSync as Br,writeFileSync as ni}from"fs";import WT from"better-sqlite3";import{readFileSync as Ow}from"fs";import{resolve as nn,dirname as fm}from"path";import{fileURLToPath as Cw}from"url";var Gn=[{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 hm(e){let o=fm(Cw(import.meta.url)),t=process.argv[1]?fm(process.argv[1]):"",n=[nn(o,`${e}.yaml`),nn(o,"workflows/templates",`${e}.yaml`),nn(o,"..","workflows/templates",`${e}.yaml`),nn(o,"../..","workflows/templates",`${e}.yaml`),t?nn(t,"workflows/templates",`${e}.yaml`):"",t?nn(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Ow(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
524
534
  ${n.join(`
525
- `)}`)}var Ye=new nw().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ye.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Qo().list();if(!o.length){console.log(A.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?A.green("dispatch: active"):A.yellow(`dispatch: ${t.state}`);console.log(` ${A.cyan(t.id)} ${A.bold(t.title)} ${A.dim(`v${t.version} \xB7`)} ${r} ${A.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${A.dim("trigger:")} ${s.source??"?"}${i?` ${A.dim(i)}`:""}`),console.log(` ${A.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(A.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Ye.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new Qo().get(e);n||(console.log(A.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Ea(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(A.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Ye.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=on(process.cwd(),e);Ir(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=Nr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?St(r,{filePath:e}):JSON.parse(r),l=xt.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=os(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 ts?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let t=new Qo().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(A.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(A.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(A.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ye.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Wn.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");Wn.some(a=>a.name===t)||(console.log(A.red(` unknown template "${o.template}"`)),console.log(A.dim(` available: ${Wn.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 Qo;!o.force&&n.get(e)&&(console.log(A.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Zg(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=St(s,{filePath:`${e}.yaml`}),c=xt.safeParse(a);if(!c.success){console.log(A.red(` template "${t}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(A.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=on(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=St(s,{filePath:`${e}.yaml`}),c=xt.parse(a);Xs(r,JSON.stringify(c,null,2)+`
526
- `)}else Xs(r,s);console.log(),console.log(A.green(` \u2713 scaffolded ${r}`)),console.log(A.dim(` template: ${t}`)),console.log(),console.log(A.dim(" Next:")),console.log(A.dim(` 1. edit ${r}`)),console.log(A.dim(` 2. agentx workflow validate ${r}`)),console.log(A.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Ye.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Wn)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()});Ye.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=on(process.cwd(),e);Ir(t)||(console.log(A.red(` file not found: ${t}`)),process.exit(1));let n=Nr(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?St(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof ts?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=xt.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=os(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 Qo,l=s?sw(e).match(/\.yml$/i)?"yml":"yaml":"json",g=on(c.baseDir,`${r.data.id}.${l}`);if(Xs(g,s?n:JSON.stringify(r.data,null,2)+`
527
- `),console.log(A.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(A.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(A.dim(" \u2713 daemon reloaded")):console.log(A.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(A.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ye.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new hn({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(A.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?A.cyan:s.status==="failed"?A.red:A.green;console.log(` ${A.dim(s.id.slice(0,8))} ${A.bold(s.workflowId)} ${a(r)} ${A.dim(s.status)}`),console.log(` ${A.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${A.dim("home: ")} ${s.homeNode}`),console.log(` ${A.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${A.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(A.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ye.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(A.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=on(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Ir(s)){let c=Nr(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?St(c,{filePath:e}):JSON.parse(c)}catch(b){let $=b instanceof ts?b.message:`parse error: ${b?.message??b}`;console.log(A.red(` ${$}`)),process.exit(1)}let d=xt.safeParse(g);if(!d.success){console.log(A.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=os(d.data);if(u.length){console.log(A.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new Qo,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,h=l?"yaml":"json",w=on(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)+`
528
- `;Xs(w,k),n=p,console.log(A.dim(` ad-hoc registered as "${p}" \u2192 ${w}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(A.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&g.includes('"hint"')&&console.log(A.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(A.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?A.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(A.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await iw({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function iw(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?A.green:a==="error"?A.red:A.cyan,l=r.totalTokens!=null?A.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?A.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${A.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${A.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${A.dim("run finished:")} ${c.status}`),console.log(A.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(A.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Ye.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}em(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(A.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(A.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(A.yellow(` no traces for "${e}"`)),console.log(A.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(A.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)em(i)});function em(e){let o=e.status||"ok",t=o==="ok"?A.green:o==="error"?A.red:A.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${A.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${A.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${A.dim("model:")} ${i}`),console.log(` ${A.dim("tokens:")} ${n} ${A.dim("duration:")} ${s}`),e.error&&console.log(` ${A.dim("error:")} ${A.red(String(e.error).slice(0,300))}`),console.log()}Ye.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new hn({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Ye.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new hn({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Ye.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new hn({nodeId:t}).setStatus(e,"canceled")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 canceled ${e}`))});import{Command as om}from"commander";import re from"chalk";import ft from"prompts";import{readFileSync as rw,existsSync as aw}from"fs";import{resolve as cw}from"path";var Bn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Rr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),tm={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 nm(){let e=cw(process.cwd(),"agentx.json");if(!aw(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(rw(e,"utf-8"))}function lw(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?re.yellow("\u26A0 no signing secret"):re.green("\u2713 active"):re.dim("disabled")}function dw(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Rr.has(e.source)?re.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${re.cyan(e.id)} ${lw(e)}`),console.log(` ${re.dim(e.source)} \u2192 ${re.bold(e.agentId)}${n}`),console.log(` POST ${re.dim(t)}`),e.secretEnv&&console.log(` secret: ${re.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${re.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${re.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${re.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var Oo=new om().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");Oo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=nm(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(re.dim(`
535
+ `)}`)}var Ke=new jw().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ke.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new ot().list();if(!o.length){console.log(A.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let t of o){let s=t.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),r=t.state==="active"?A.green("dispatch: active"):A.yellow(`dispatch: ${t.state}`);console.log(` ${A.cyan(t.id)} ${A.bold(t.title)} ${A.dim(`v${t.version} \xB7`)} ${r} ${A.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${A.dim("trigger:")} ${s.source??"?"}${i?` ${A.dim(i)}`:""}`),console.log(` ${A.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(A.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});Ke.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,o)=>{let n=new ot().get(e);n||(console.log(A.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Ma(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(A.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});Ke.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=sn(process.cwd(),e);Wr(i)||(console.log(A.red(` file not found: ${i}`)),process.exit(1));try{let r=Br(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?At(r,{filePath:e}):JSON.parse(r),l=Et.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=rs(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 as?r.message:`parse error: ${r?.message??r}`;console.log(A.red(` ${a}`)),process.exit(1)}return}let t=new ot().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(A.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(A.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(A.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ke.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Gn.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,o)=>{let t=String(o.template||"linear");Gn.some(a=>a.name===t)||(console.log(A.red(` unknown template "${o.template}"`)),console.log(A.dim(` available: ${Gn.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 ot;!o.force&&n.get(e)&&(console.log(A.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=hm(t);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,o.title?String(o.title):`${t} workflow ${e}`).replace(/__AGENT__/g,String(o.agent)).replace(/__REVIEWER__/g,String(o.reviewer));try{let a=At(s,{filePath:`${e}.yaml`}),c=Et.safeParse(a);if(!c.success){console.log(A.red(` template "${t}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(A.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=sn(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=At(s,{filePath:`${e}.yaml`}),c=Et.parse(a);ni(r,JSON.stringify(c,null,2)+`
536
+ `)}else ni(r,s);console.log(),console.log(A.green(` \u2713 scaffolded ${r}`)),console.log(A.dim(` template: ${t}`)),console.log(),console.log(A.dim(" Next:")),console.log(A.dim(` 1. edit ${r}`)),console.log(A.dim(` 2. agentx workflow validate ${r}`)),console.log(A.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Ke.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Gn)console.log(` ${A.cyan(e.name.padEnd(20))} ${A.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${A.dim(e.description)}`);console.log(),console.log(A.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Ke.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,o)=>{let t=sn(process.cwd(),e);Wr(t)||(console.log(A.red(` file not found: ${t}`)),process.exit(1));let n=Br(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?At(n,{filePath:e}):JSON.parse(n)}catch(u){let f=u instanceof as?u.message:`parse error: ${u?.message??u}`;console.log(A.red(` ${f}`)),process.exit(1)}let r=Et.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=rs(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 ot,l=s?Iw(e).match(/\.yml$/i)?"yml":"yaml":"json",g=sn(c.baseDir,`${r.data.id}.${l}`);if(ni(g,s?n:JSON.stringify(r.data,null,2)+`
537
+ `),console.log(A.green(` \u2713 ${r.data.id} \u2192 ${g}`)),o.reload===!1){console.log(A.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(d,{method:"POST"});u.ok?console.log(A.dim(" \u2713 daemon reloaded")):console.log(A.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(A.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ke.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local",n=new $n({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(A.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?A.cyan:s.status==="failed"?A.red:A.green;console.log(` ${A.dim(s.id.slice(0,8))} ${A.bold(s.workflowId)} ${a(r)} ${A.dim(s.status)}`),console.log(` ${A.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${A.dim("home: ")} ${s.homeNode}`),console.log(` ${A.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${A.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(A.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ke.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,o)=>{let t={};if(o.input)try{t=JSON.parse(o.input)}catch{console.log(A.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=sn(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Wr(s)){let c=Br(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?At(c,{filePath:e}):JSON.parse(c)}catch(b){let $=b instanceof as?b.message:`parse error: ${b?.message??b}`;console.log(A.red(` ${$}`)),process.exit(1)}let d=Et.safeParse(g);if(!d.success){console.log(A.red(" \u2717 schema:"));for(let b of d.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=rs(d.data);if(u.length){console.log(A.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let f=new ot,p=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,h=l?"yaml":"json",w=sn(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)+`
538
+ `;ni(w,k),n=p,console.log(A.dim(` ad-hoc registered as "${p}" \u2192 ${w}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let g=await c.text();console.log(A.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&g.includes('"hint"')&&console.log(A.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(A.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?A.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(A.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await Nw({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Nw(e){let o=new Set,t=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let i=[];try{let r=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);r.ok&&(i=(await r.json()).traces||[])}catch{}for(let r of i){if(!r.taskId||o.has(r.taskId)||(o.add(r.taskId),t.set(r.taskId,r),e.quiet))continue;let a=r.status||"running",c=a==="ok"?A.green:a==="error"?A.red:A.cyan,l=r.totalTokens!=null?A.dim(`${r.totalTokens}t`):"",g=r.durationMs!=null?A.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${A.bold(r.nodeId||r.label||"(node)")} ${l} ${g}`),r.error&&console.log(` ${A.red(String(r.error).slice(0,200))}`)}try{let r=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(r.ok){let c=(await r.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${A.dim("run finished:")} ${c.status}`),console.log(A.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(t.values())}}catch{}await new Promise(r=>setTimeout(r,500))}return e.quiet||console.log(A.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}Ke.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,o)=>{let t=String(o.daemon).replace(/\/$/,"");try{let i=await fetch(`${t}/traces/${encodeURIComponent(e)}`);if(i.ok){let r=await i.json();if(o.json){console.log(JSON.stringify(r,null,2));return}ym(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(A.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(A.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(A.yellow(` no traces for "${e}"`)),console.log(A.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(o.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(A.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)ym(i)});function ym(e){let o=e.status||"ok",t=o==="ok"?A.green:o==="error"?A.red:A.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",i=e.model||"\u2014";console.log(` ${t(o.padEnd(5))} ${A.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${A.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${A.dim("model:")} ${i}`),console.log(` ${A.dim("tokens:")} ${n} ${A.dim("duration:")} ${s}`),e.error&&console.log(` ${A.dim("error:")} ${A.red(String(e.error).slice(0,300))}`),console.log()}Ke.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new $n({nodeId:t}).setStatus(e,"paused")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 paused ${e}`))});Ke.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new $n({nodeId:t}).setStatus(e,"running")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 resumed ${e}`))});Ke.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,o)=>{let t=o.node||process.env.WF_NODE_ID||"local";new $n({nodeId:t}).setStatus(e,"canceled")||(console.log(A.yellow(` no such run: ${e}`)),process.exit(1)),console.log(A.green(` \u2713 canceled ${e}`))});import{Command as wm}from"commander";import ae from"chalk";import wt from"prompts";import{readFileSync as Rw,existsSync as _w}from"fs";import{resolve as Dw}from"path";var zn=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Jr=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),$m={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 bm(){let e=Dw(process.cwd(),"agentx.json");if(!_w(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Rw(e,"utf-8"))}function Pw(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ae.yellow("\u26A0 no signing secret"):ae.green("\u2713 active"):ae.dim("disabled")}function Mw(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Jr.has(e.source)?ae.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ae.cyan(e.id)} ${Pw(e)}`),console.log(` ${ae.dim(e.source)} \u2192 ${ae.bold(e.agentId)}${n}`),console.log(` POST ${ae.dim(t)}`),e.secretEnv&&console.log(` secret: ${ae.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${ae.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${ae.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${ae.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var Co=new wm().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");Co.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=bm(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ae.dim(`
529
539
  No webhooks registered. Add one with: agentx webhook add
530
- `));return}console.log();for(let n of t)dw(n)});Oo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Bn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=nm(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),l=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),d=o.prompt!==!1;if(!r&&d&&(r=((await ft({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 ft({type:"select",name:"source",message:"Source",choices:Bn.map(p=>({title:`${p}${Rr.has(p)?" \u2713 wired":""}`,value:p,description:tm[p]}))})).source),!Bn.includes(a))throw new Error(`Source must be one of: ${Bn.join(", ")}`);if(!c&&d&&(i?c=((await ft({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await ft({type:"select",name:"agentId",message:"Agent",choices:n.map(p=>({title:p,value:p}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!l&&d&&a!=="custom"&&(l=((await ft({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await ft({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"))});Oo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await ft({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await pe(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(re.green(`\u2713 removed webhook "${e}"`))});function sm(e){return async o=>{let t=await pe(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(re.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}Oo.command("enable <id>").description("enable a webhook entry").action(sm(!0));Oo.command("disable <id>").description("disable a webhook entry").action(sm(!1));var Qs=new om().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Qs.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await pe(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});Qs.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await pe(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(re.green(`\u2713 removed trigger ${o} from "${e}"`))});Qs.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await pe(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(re.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});Oo.addCommand(Qs);Oo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Bn.map(t=>({source:t,wired:Rr.has(t),hint:tm[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?re.green("\u2713 wired"):re.dim("inbound-only");console.log(` ${re.cyan(t.source.padEnd(8))} ${n} ${re.dim(t.hint)}`)}console.log(),console.log(re.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(re.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as gw}from"commander";import ae from"chalk";ne();function tn(e){let{summary:o,backupPath:t}=Ze(n=>e(n));console.log(ae.green(`
531
- \u2713 ${o}`)),t&&console.log(ae.dim(` Backup: ${t}`)),console.log(ae.dim(` Restart the daemon (or POST /reload) for the change to take effect.
532
- `))}function Zs(){try{return j().business||{}}catch{return{}}}var nn=new gw().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");nn.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=Zs();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.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 t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(ae.bold(" Org chart"));let i=Object.entries(t);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 _r=nn.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");_r.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=Zs(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(ae.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${ae.cyan(n)} ${s.role}${s.reportsTo?ae.dim(` \u2192 ${s.reportsTo}`):""}`)});_r.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);tn(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});_r.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{tn(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var Dr=nn.command("project").description("manage business.projects \u2014 id, pm, client");Dr.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=Zs().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ae.dim(" no projects"));return}for(let n of t)console.log(` ${ae.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Dr.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{tn(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Dr.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{tn(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var Pr=nn.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Pr.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=Zs().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ae.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${ae.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Pr.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)),tn(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});Pr.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=>{tn(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as mw}from"commander";import Ue from"chalk";ne();var pw={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Mr(e){let o=pw[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function ei(){let o=j().business?.standup?.plansDir||".agentx/plans";return new rl(o)}var sn=new mw().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");sn.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=Mr(e),n=ei(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
533
- `):(console.error(Ue.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Ue.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Ri(s);if(r.length){console.log(Ue.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Ue.dim(` \u2022 ${a}`))}});sn.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=ei();if(e){let n=Mr(e),s=o.read(n);if(!s){console.log(Ue.dim(` No ${n} plan set.`));return}im(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Ue.yellow(" No plan set at any tier.")),console.log(Ue.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Ue.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}im(t.tier,t.date,t.content)});sn.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=ei().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Ue.dim(" No plans yet."));return}for(let n of t)console.log(` ${Ue.cyan(n.tier.padEnd(5))} ${Ue.bold(n.date.padEnd(11))} ${Ue.dim(n.path)}`)});sn.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Mr(e),n=ei().read(o);if(!n){console.log(Ue.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Ue.green(` \u2713 ${o} plan cleared (${n.path})`))});function im(e,o,t){console.log(Ue.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
534
- `))console.log(` ${s}`);console.log();let n=Ri(t);n.length&&console.log(Ue.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as uw}from"commander";import V from"chalk";ne();function fw(){try{return j().notifications||{}}catch{return{}}}function hw(){try{return j().channels?.ntfy}catch{return}}function yw(){try{return j().channels?.push}catch{return}}function rn(e){let{summary:o,backupPath:t}=Ze(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(V.green(`
535
- \u2713 ${o}`)),t&&console.log(V.dim(` Backup: ${t}`)),console.log(V.dim(` Restart the daemon (or POST /reload) for the change to take effect.
536
- `))}var $o=new uw().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");$o.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=fw();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let c=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${V.cyan(o.destination.channel+":"+o.destination.chatId)}${V.dim(c)}`)}else console.log(` destination ${V.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${V.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?V.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?V.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":V.dim("off")}`);let n=as(o.local);if(console.log(` local.banner ${n.banner?"on":V.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:V.dim("off")}`),console.log(` local.icon ${n.icon??V.dim("AgentX logo")}`),n.banner){let c=await ul();c.state!=="unsupported"&&(console.log(` local.helper ${c.state==="ready"?c.message:V.yellow(c.message)}`),c.fix&&console.log(` ${V.dim("Fix: "+c.fix)}`))}let s;try{s=j()}catch{s=void 0}console.log(` channel ${cs(s)} ${V.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=vi(yw()),r=i.role==="relay"?`relays to ${i.relayTo}`:`this node sends \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing (agentx app push-keys)"}`;console.log(` push ${i.enabled?"on":V.dim("off")} ${V.dim(r)}`);let a=Di(hw());console.log(` ntfy ${a.enabled?"on":V.dim("off")} ${V.dim(`${a.server} \xB7 topic ${a.topicSet?"set":"unset"} \xB7 token ${a.tokenSet?"set":"unset"}`)}`),console.log()});$o.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){rn(o=>(delete o.destination,"notifications destination cleared"));return}rn(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});$o.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(V.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(V.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";rn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});$o.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(V.red(" threshold must be a non-negative integer")),process.exit(1)),rn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});$o.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(V.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(V.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{rn(n=>(n.local=uc(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(V.dim(` Run agentx desktop install to put the new icon on the helper.
537
- `))}catch(n){console.log(V.red(` ${n?.message??n}`)),process.exit(1)}});$o.command("channel <name>").description("channel agentx notify uses when --channel is not given: push, ntfy, telegram\u2026 (unset: push when it is on, else ntfy)").action(e=>{let o=e.trim();/^[\w-]+$/.test(o)||(console.log(V.red(` not a channel name: ${e}`)),process.exit(1)),rn(t=>(t.channel=o,`notifications.channel = ${o}`))});$o.command("push").description("set up notifications on the phone app: on/off, contact, or relay to the node that hosts the app").option("--subject <contact>","contact for the push services: mailto:you@example.com or an https:// URL").option("--relay-to <peer>",'mesh peer that hosts the phone app (on every other node); "" makes this node the host').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.subject!==void 0&&(o.subject=e.subject),e.relayTo!==void 0&&(o.relayTo=e.relayTo),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(V.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=Ze(s=>{s.channels=s.channels||{},s.channels.push=kc(s.channels.push,o);let i=vi(s.channels.push);return`channels.push ${i.enabled?"on":"off"} \xB7 ${i.role==="relay"?`relays to ${i.relayTo}`:`host \xB7 subject ${i.subjectSet?"set":"unset"} \xB7 keys ${i.keysSet?"set":"missing"}`}`});console.log(V.green(`
538
- \u2713 ${t}`)),n&&console.log(V.dim(` Backup: ${n}`)),console.log(V.dim(` Restart the daemon for a channel change to take effect.
539
- `))}catch(t){console.log(V.red(` ${t?.message??t}`)),process.exit(1)}});$o.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(V.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=Ze(s=>{s.channels=s.channels||{},s.channels.ntfy=kl(s.channels.ntfy,o);let i=Di(s.channels.ntfy);return`channels.ntfy ${i.enabled?"on":"off"} \xB7 ${i.server} \xB7 topic ${i.topicSet?"set":"unset"} \xB7 token ${i.tokenSet?"set":"unset"}`});console.log(V.green(`
540
- \u2713 ${t}`)),n&&console.log(V.dim(` Backup: ${n}`)),console.log(V.dim(` Restart the daemon for a channel change to take effect.
541
- `))}catch(t){console.log(V.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as ww}from"commander";import zo from"chalk";import{readdirSync as Lr,statSync as rm,unlinkSync as $w,rmSync as bw,existsSync as am}from"fs";import{resolve as cm,join as lm}from"path";var dm=[{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 qr(e,o){if(!am(e))return[];let t=[];for(let n of Lr(e,{withFileTypes:!0})){let s=lm(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...qr(s,!0))}return t}var ti=new ww().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");ti.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of dm){let t=cm(process.cwd(),o.dir),n=qr(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=rm(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(` ${zo.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${oi(s).padStart(10)} oldest=${r}`)}console.log(zo.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${oi(e).padStart(10)} total`)),console.log(),console.log(zo.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});ti.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(zo.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(zo.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?zo.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of dm){if(n&&r.dir!==n)continue;let a=cm(process.cwd(),r.dir),c=qr(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=rm(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{$w(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{gm(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${zo.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${oi(g)})`),s+=l,i+=g}console.log(),console.log(zo.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${oi(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function gm(e){if(am(e))for(let o of Lr(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=lm(e,o.name);gm(t);try{Lr(t).length===0&&bw(t,{recursive:!1})}catch{}}}function oi(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 kw}from"commander";import U from"chalk";var Vo=new kw().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Vo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new Et().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});Vo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new Et().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});Vo.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=vw(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=Aa.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 Et().save(s.data);console.log(U.green(`
540
+ `));return}console.log();for(let n of t)Mw(n)});Co.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${zn.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=bm(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(f=>f.name).filter(Boolean),i=String(o.node||"").trim();if(!n.length&&!i)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let r=(e||"").trim(),a=String(o.source||"").trim(),c=String(o.agent||"").trim(),l=String(o.secretEnv||"").trim(),g=String(o.description||"").trim(),d=o.prompt!==!1;if(!r&&d&&(r=((await wt({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 wt({type:"select",name:"source",message:"Source",choices:zn.map(p=>({title:`${p}${Jr.has(p)?" \u2713 wired":""}`,value:p,description:$m[p]}))})).source),!zn.includes(a))throw new Error(`Source must be one of: ${zn.join(", ")}`);if(!c&&d&&(i?c=((await wt({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await wt({type:"select",name:"agentId",message:"Agent",choices:n.map(p=>({title:p,value:p}))})).agentId),!c)throw new Error("Agent is required.");if(i){if(!s.includes(i))throw new Error(`Mesh peer "${i}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!t.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!l&&d&&a!=="custom"&&(l=((await wt({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await wt({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await se(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(ae.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(ae.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(ae.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});Co.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await wt({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await se(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(i=>i.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!t.success)throw new Error(t.error);console.log(ae.green(`\u2713 removed webhook "${e}"`))});function km(e){return async o=>{let t=await se(n=>{let s=(n.webhooks||[]).find(i=>i.id===o);if(!s)throw new Error(`Webhook "${o}" not found.`);s.enabled=e});if(!t.success)throw new Error(t.error);console.log(ae.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}Co.command("enable <id>").description("enable a webhook entry").action(km(!0));Co.command("disable <id>").description("disable a webhook entry").action(km(!1));var si=new wm().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");si.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await se(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);i.triggers=i.triggers&&typeof i.triggers=="object"?i.triggers:{},i.triggers[o]=t});if(!n.success)throw new Error(n.error);console.log(ae.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});si.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await se(n=>{let s=(n.webhooks||[]).find(i=>i.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[o]});if(!t.success)throw new Error(t.error);console.log(ae.green(`\u2713 removed trigger ${o} from "${e}"`))});si.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,o)=>{let t=o==="-"||o==="",n=await se(s=>{let i=(s.webhooks||[]).find(r=>r.id===e);if(!i)throw new Error(`Webhook "${e}" not found.`);t?delete i.defaultWorkflow:i.defaultWorkflow=o});if(!n.success)throw new Error(n.error);console.log(ae.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});Co.addCommand(si);Co.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=zn.map(t=>({source:t,wired:Jr.has(t),hint:$m[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?ae.green("\u2713 wired"):ae.dim("inbound-only");console.log(` ${ae.cyan(t.source.padEnd(8))} ${n} ${ae.dim(t.hint)}`)}console.log(),console.log(ae.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(ae.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as Lw}from"commander";import ce from"chalk";ee();function rn(e){let{summary:o,backupPath:t}=eo(n=>e(n));console.log(ce.green(`
541
+ \u2713 ${o}`)),t&&console.log(ce.dim(` Backup: ${t}`)),console.log(ce.dim(` Restart the daemon (or POST /reload) for the change to take effect.
542
+ `))}function ii(){try{return O().business||{}}catch{return{}}}var an=new Lw().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");an.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=ii();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(ce.yellow(" business block not enabled (or missing).")),console.log(ce.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let t=o.orgChart||{},n=o.projects||[],s=o.contactMap||[];console.log(),console.log(ce.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(ce.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?ce.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?ce.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${ce.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(ce.bold(` Projects (${n.length})`)),n.length===0)console.log(ce.dim(" (empty)"));else for(let r of n){let a=r.pm?ce.dim(` \xB7 pm=${r.pm}`):"",c=r.client?ce.dim(` \xB7 client=${r.client}`):"";console.log(` ${ce.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(ce.bold(` Contact map (${s.length})`)),s.length===0)console.log(ce.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(` ${ce.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?ce.dim(` (${r.displayName})`):""}`)}console.log()});var Hr=an.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Hr.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=ii(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(ce.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${ce.cyan(n)} ${s.role}${s.reportsTo?ce.dim(` \u2192 ${s.reportsTo}`):""}`)});Hr.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,o)=>{let t=String(o.days).split(",").map(n=>n.trim()).filter(Boolean);rn(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:o.role,...o.reportsTo?{reportsTo:o.reportsTo}:{},schedule:{days:t,start:o.start,end:o.end},utilizationTarget:parseFloat(o.utilization)||.8},`orgChart entry "${e}" upserted (role=${o.role}${o.reportsTo?`, reports to ${o.reportsTo}`:""})`))});Hr.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{rn(o=>{if(!o.business?.orgChart||!(e in o.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete o.business.orgChart[e],`orgChart entry "${e}" removed`})});var Gr=an.command("project").description("manage business.projects \u2014 id, pm, client");Gr.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=ii().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ce.dim(" no projects"));return}for(let n of t)console.log(` ${ce.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Gr.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,o)=>{rn(t=>{t.business=t.business||{},t.business.projects=t.business.projects||[];let n=t.business.projects.findIndex(i=>i.id===e),s={id:e,...o.pm?{pm:o.pm}:{},...o.client?{client:o.client}:{}};return n>=0?t.business.projects[n]={...t.business.projects[n],...s}:t.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Gr.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{rn(o=>{let t=o.business?.projects||[],n=t.length;if(o.business.projects=t.filter(s=>s.id!==e),o.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var zr=an.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");zr.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=ii().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(ce.dim(" no entries"));return}for(let n of t){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${ce.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});zr.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(ce.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),rn(o=>{o.business=o.business||{},o.business.contactMap=o.business.contactMap||[];let t={client:e.client};e.channel&&(t.channel=e.channel),e.chatId&&(t.chatId=e.chatId),e.username&&(t.username=e.username),e.senderId&&(t.senderId=e.senderId),e.project&&(t.project=e.project),e.displayName&&(t.displayName=e.displayName),o.business.contactMap.push(t);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});zr.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=>{rn(o=>{let t=o.business?.contactMap||[],n=t.length;if(o.business.contactMap=t.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),o.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-o.business.contactMap.length} contact entry/entries removed`})});import{Command as qw}from"commander";import Fe from"chalk";ee();var Uw={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Yr(e){let o=Uw[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function ri(){let o=O().business?.standup?.plansDir||".agentx/plans";return new yl(o)}var cn=new qw().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");cn.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,o)=>{let t=Yr(e),n=ri(),s;if(o.file){let{readFileSync:a}=await import("fs");s=a(o.file,"utf-8")}else o.markdown?s=o.markdown:o.priority?.length?s=o.priority.map(a=>`- ${a}`).join(`
543
+ `):(console.error(Fe.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Fe.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Wi(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}`))}});cn.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=ri();if(e){let n=Yr(e),s=o.read(n);if(!s){console.log(Fe.dim(` No ${n} plan set.`));return}vm(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Fe.yellow(" No plan set at any tier.")),console.log(Fe.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Fe.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}vm(t.tier,t.date,t.content)});cn.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=ri().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Fe.dim(" No plans yet."));return}for(let n of t)console.log(` ${Fe.cyan(n.tier.padEnd(5))} ${Fe.bold(n.date.padEnd(11))} ${Fe.dim(n.path)}`)});cn.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Yr(e),n=ri().read(o);if(!n){console.log(Fe.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Fe.green(` \u2713 ${o} plan cleared (${n.path})`))});function vm(e,o,t){console.log(Fe.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
544
+ `))console.log(` ${s}`);console.log();let n=Wi(t);n.length&&console.log(Fe.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Fw}from"commander";import Y from"chalk";ee();function Ww(){try{return O().notifications||{}}catch{return{}}}function Bw(){try{return O().channels?.ntfy}catch{return}}function Jw(){try{return O().channels?.push}catch{return}}function ln(e){let{summary:o,backupPath:t}=eo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Y.green(`
545
+ \u2713 ${o}`)),t&&console.log(Y.dim(` Backup: ${t}`)),console.log(Y.dim(` Restart the daemon (or POST /reload) for the change to take effect.
546
+ `))}var bo=new Fw().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");bo.command("show").description("print current notifications config").option("--json","JSON output").action(async e=>{let o=Ww();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let c=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Y.cyan(o.destination.channel+":"+o.destination.chatId)}${Y.dim(c)}`)}else console.log(` destination ${Y.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Y.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Y.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Y.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Y.dim("off")}`);let n=ms(o.local);if(console.log(` local.banner ${n.banner?"on":Y.dim("off")}`),console.log(` local.sound ${n.sound?`${n.soundName} at ${n.volume}`:Y.dim("off")}`),console.log(` local.icon ${n.icon??Y.dim("AgentX logo")}`),n.banner){let c=await 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=O()}catch{s=void 0}console.log(` channel ${ps(s)} ${Y.dim(o.channel?"(where agentx notify sends)":"(where agentx notify sends; not set, so push when it is on, else ntfy)")}`);let i=Ii(Jw()),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=Hi(Bw());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()});bo.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){ln(o=>(delete o.destination,"notifications destination cleared"));return}ln(o=>(o.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});bo.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,o)=>{let t=["taskComplete","taskError","taskQueued"];t.includes(e)||(console.log(Y.red(` unknown event "${e}". Pick from: ${t.join(", ")}`)),process.exit(1));let n=o.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(Y.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";ln(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});bo.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let o=parseInt(e,10);(!Number.isFinite(o)||o<0)&&(console.log(Y.red(" threshold must be a non-negative integer")),process.exit(1)),ln(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});bo.command("local").description("set what `agentx notify` does on this Mac: banner, sound, sound name, volume, banner icon").option("--banner <state>","on | off").option("--sound <state>","on | off").option("--sound-name <name>","a macOS system sound, e.g. Glass, Ping, Tink").option("--volume <n>","0 to 1").option("--icon <path>",'image for the banner icon (.png, .jpg, .icns); "" for the AgentX logo').action(e=>{let o=(n,s)=>{let i=s.toLowerCase();if(["on","true","1"].includes(i))return!0;if(["off","false","0"].includes(i))return!1;console.log(Y.red(` ${n} must be on|off`)),process.exit(1)},t={};e.banner!==void 0&&(t.banner=o("--banner",e.banner)),e.sound!==void 0&&(t.sound=o("--sound",e.sound)),e.soundName!==void 0&&(t.soundName=e.soundName),e.volume!==void 0&&(t.volume=e.volume),e.icon!==void 0&&(t.icon=e.icon),Object.keys(t).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --banner, --sound, --sound-name, --volume or --icon")),process.exit(1));try{ln(n=>(n.local=Ec(n.local,t),`notifications.local = ${JSON.stringify(n.local)}`)),e.icon!==void 0&&console.log(Y.dim(` Run agentx desktop install to put the new icon on the helper.
547
+ `))}catch(n){console.log(Y.red(` ${n?.message??n}`)),process.exit(1)}});bo.command("channel <name>").description("channel agentx notify uses when --channel is not given: push, ntfy, telegram\u2026 (unset: push when it is on, else ntfy)").action(e=>{let o=e.trim();/^[\w-]+$/.test(o)||(console.log(Y.red(` not a channel name: ${e}`)),process.exit(1)),ln(t=>(t.channel=o,`notifications.channel = ${o}`))});bo.command("push").description("set up notifications on the phone app: on/off, contact, or relay to the node that hosts the app").option("--subject <contact>","contact for the push services: mailto:you@example.com or an https:// URL").option("--relay-to <peer>",'mesh peer that hosts the phone app (on every other node); "" makes this node the host').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.subject!==void 0&&(o.subject=e.subject),e.relayTo!==void 0&&(o.relayTo=e.relayTo),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --subject, --relay-to, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=eo(s=>{s.channels=s.channels||{},s.channels.push=Nc(s.channels.push,o);let i=Ii(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(`
548
+ \u2713 ${t}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
549
+ `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});bo.command("ntfy").description("set up phone push through ntfy: server, topic, token, on/off").option("--server <url>","ntfy server (default https://ntfy.sh)").option("--topic <topic>",'topic to publish to; a secret on ntfy.sh \u2014 "${NTFY_TOPIC}" reads it from .env').option("--token <token>",'access token for a protected topic; "${NTFY_TOKEN}" reads it from .env; "" removes it').option("--enable","turn the channel on").option("--disable","turn the channel off").action(e=>{let o={};e.server!==void 0&&(o.server=e.server),e.topic!==void 0&&(o.topic=e.topic),e.token!==void 0&&(o.token=e.token),e.enable&&(o.enabled=!0),e.disable&&(o.enabled=!1),Object.keys(o).length===0&&(console.log(Y.red(" nothing to change \u2014 pass --server, --topic, --token, --enable or --disable")),process.exit(1));try{let{summary:t,backupPath:n}=eo(s=>{s.channels=s.channels||{},s.channels.ntfy=Rl(s.channels.ntfy,o);let i=Hi(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(`
550
+ \u2713 ${t}`)),n&&console.log(Y.dim(` Backup: ${n}`)),console.log(Y.dim(` Restart the daemon for a channel change to take effect.
551
+ `))}catch(t){console.log(Y.red(` ${t?.message??t}`)),process.exit(1)}});import{Command as Hw}from"commander";import Ko from"chalk";import{readdirSync as Vr,statSync as xm,unlinkSync as Gw,rmSync as zw,existsSync as Sm}from"fs";import{resolve as Em,join as Am}from"path";var Tm=[{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 Kr(e,o){if(!Sm(e))return[];let t=[];for(let n of Vr(e,{withFileTypes:!0})){let s=Am(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Kr(s,!0))}return t}var ci=new Hw().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");ci.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Tm){let t=Em(process.cwd(),o.dir),n=Kr(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=xm(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(` ${Ko.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ai(s).padStart(10)} oldest=${r}`)}console.log(Ko.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ai(e).padStart(10)} total`)),console.log(),console.log(Ko.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});ci.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(Ko.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(Ko.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?Ko.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Tm){if(n&&r.dir!==n)continue;let a=Em(process.cwd(),r.dir),c=Kr(a,!!r.recursive),l=0,g=0;for(let u of c)try{let f=xm(u);if(f.mtimeMs<t&&(g+=f.size,l++,!e.dryRun))try{Gw(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Om(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Ko.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${ai(g)})`),s+=l,i+=g}console.log(),console.log(Ko.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${ai(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Om(e){if(Sm(e))for(let o of Vr(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Am(e,o.name);Om(t);try{Vr(t).length===0&&zw(t,{recursive:!1})}catch{}}}function ai(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 Yw}from"commander";import U from"chalk";var Xo=new Yw().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");Xo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new Tt().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(U.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of t){let s=n.inputs?.length?U.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${U.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${U.dim(i)}`)}console.log()});Xo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new Tt().get(e);if(n||(console.log(U.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(U.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?U.red("*"):" ",r=s.defaultValue!==void 0?U.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?U.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${U.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});Xo.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=Vw(o.inputs),n={id:e,title:o.title,description:o.description,inputs:t,timeoutMs:parseInt(o.timeout,10)||3e4,kind:o.kind};if(o.kind==="shell")o.command||(console.log(U.red(" --command required for kind=shell")),process.exit(1)),n.command=o.command,o.cwd&&(n.cwd=o.cwd);else if(o.kind==="http"){if(o.url||(console.log(U.red(" --url required for kind=http")),process.exit(1)),n.url=o.url,n.method=o.method,o.headers)try{n.headers=JSON.parse(o.headers)}catch{console.log(U.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(U.red(" --kind must be shell|http")),process.exit(1);let s=La.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 Tt().save(s.data);console.log(U.green(`
542
552
  \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(U.dim(` Test: agentx actions run ${r.id}
543
- `))});Vo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Et().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Vo.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new Et().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Ta(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});Vo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function vw(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}ne();import{Command as xw}from"commander";import te from"chalk";var mm=new xw().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=j(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(te.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(te.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(te.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(`
553
+ `))});Xo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Tt().delete(e)||(console.log(U.red(` no action "${e}"`)),process.exit(1)),console.log(U.green(` \u2713 action "${e}" removed`))});Xo.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new Tt().get(e);n||(console.log(U.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(U.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await qa(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?U.green("\u2713 ok"):U.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(U.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(U.dim(" --- errors ---")),console.log(U.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(U.red(` ${i.message}`)),process.exit(1)}});Xo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(U.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(U.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(U.bold(" Built-in typed actions")),console.log(U.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?U.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${U.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(U.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(U.bold(` ${r.name}`)),r.description&&console.log(U.dim(` ${r.description}`)),console.log(),console.log(U.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(U.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(U.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(U.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(U.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(U.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Vw(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}ee();import{Command as Kw}from"commander";import ne from"chalk";var Cm=new Kw().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=O(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(ne.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(ne.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(ne.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(`
544
554
 
545
- `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),Sw(f)}}}catch(r){console.error(te.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Sw(e){let o="message",t="";for(let i of e.split(`
546
- `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?te.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=te.cyan(n.phase?.padEnd(9)??"run"),r=te.bold(n.workflowId??""),a=te.dim((n.runId??"").slice(0,8)),c=n.nodeId?te.yellow(n.nodeId):"",l=n.note?te.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=te.magenta(`task.${n.phase}`.padEnd(14)),r=te.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?te.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${te.cyan(a)} ${c}`);break}case"signal":{let i=te.green("signal".padEnd(9)),r=te.bold(n.name),a=te.dim(`(${n.scope})`),c=n.workflowId?te.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=te.blue("mesh".padEnd(9)),r=te.bold(n.peer),a=n.healthy?te.green("\u2713 healthy"):te.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${te.dim(n.delta??"")}`);break}case"channel":{let i=te.yellow("channel".padEnd(9)),r=n.direction==="in"?te.cyan("\u2190"):te.magenta("\u2192"),a=te.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?te.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(te.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}ne();import{Command as Ew}from"commander";import an from"chalk";function Aw(e,o){let t=e.replace(/\/+$/,""),n=new URLSearchParams;if(o.since&&n.set("since",o.since),o.limit&&n.set("limit",o.limit),o.agent){let s=n.toString();return`${t}/agents/${encodeURIComponent(o.agent)}/events${s?`?${s}`:""}`}return o.kind&&n.set("kind",o.kind),o.limit||n.set("limit","50"),`${t}/events/recent?${n}`}var pm=new Ew().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let a=j(e.config);o||(o=a.dashboard?.daemonUrl||""),t||(t=a.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n={};t&&(n.Authorization=`Bearer ${t}`);let s;try{let a=await fetch(Aw(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(an.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(an.red(` daemon unreachable at ${o}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let i=s.events??[];if(e.agent&&!s.subscriptions){console.log(an.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(an.dim(" no events"));return}for(let a of i)console.log(` ${xa(a)} ${an.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(an.dim(`
547
- ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as Ow}from"commander";import Jn from"chalk";import{spawn as Cw}from"node:child_process";import{execFileSync as Tw}from"node:child_process";function um(e=()=>Tw("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var fm=new Ow().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(Jn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-TJ5YZOEE.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:um();if(n?.ok){let{fetchAgents:l}=await import("./client-TJ5YZOEE.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Jn.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:Cw,log:k=>console.error(Jn.dim(k))});return}n&&!n.ok&&(console.error(Jn.yellow(n.reason)),console.error(Jn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-KVH5POXZ.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as jw}from"commander";import K from"chalk";import{randomUUID as wm}from"crypto";import{createInterface as Iw}from"node:readline/promises";import Nw from"ora";import ni from"chalk";function hm(e){console.error(),console.error(ni.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(ni.dim(` ${e.why}`)),console.error(),console.error(` Use ${ni.cyan(e.instead)} instead.`),e.note&&console.error(ni.dim(` ${e.note}`)),console.error()}var ym={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 $m=new jw().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{hm({what:"agentx chat",...ym});let t=xl({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${wm().slice(0,12)}`,r=[];try{r=await hs(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-LD4TXJWP.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}_w(t.baseUrl,n,i,s);let a=Iw({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
548
- 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:${wm().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await hs(t);for(let h of p){let w=h.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${w} @${h.id} ${K.dim(h.tier)} ${h.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await hs(t)).find(w=>w.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(h){console.error(K.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=Nw({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=Rw(n);try{let p=await Sl(t,n,g,{channel:s,chatId:i,onText:w=>{d.stop(),f.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),f.tool(w)}});d.stop();let h=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(h,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function Rw(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
555
+ `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),Xw(f)}}}catch(r){console.error(ne.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Xw(e){let o="message",t="";for(let i of e.split(`
556
+ `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ne.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ne.cyan(n.phase?.padEnd(9)??"run"),r=ne.bold(n.workflowId??""),a=ne.dim((n.runId??"").slice(0,8)),c=n.nodeId?ne.yellow(n.nodeId):"",l=n.note?ne.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ne.magenta(`task.${n.phase}`.padEnd(14)),r=ne.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ne.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ne.cyan(a)} ${c}`);break}case"signal":{let i=ne.green("signal".padEnd(9)),r=ne.bold(n.name),a=ne.dim(`(${n.scope})`),c=n.workflowId?ne.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ne.blue("mesh".padEnd(9)),r=ne.bold(n.peer),a=n.healthy?ne.green("\u2713 healthy"):ne.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ne.dim(n.delta??"")}`);break}case"channel":{let i=ne.yellow("channel".padEnd(9)),r=n.direction==="in"?ne.cyan("\u2190"):ne.magenta("\u2192"),a=ne.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ne.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ne.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}ee();import{Command as Qw}from"commander";import dn from"chalk";function Zw(e,o){let t=e.replace(/\/+$/,""),n=new URLSearchParams;if(o.since&&n.set("since",o.since),o.limit&&n.set("limit",o.limit),o.agent){let s=n.toString();return`${t}/agents/${encodeURIComponent(o.agent)}/events${s?`?${s}`:""}`}return o.kind&&n.set("kind",o.kind),o.limit||n.set("limit","50"),`${t}/events/recent?${n}`}var jm=new Qw().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let a=O(e.config);o||(o=a.dashboard?.daemonUrl||""),t||(t=a.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n={};t&&(n.Authorization=`Bearer ${t}`);let s;try{let a=await fetch(Zw(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(dn.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(dn.red(` daemon unreachable at ${o}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let i=s.events??[];if(e.agent&&!s.subscriptions){console.log(dn.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(dn.dim(" no events"));return}for(let a of i)console.log(` ${Da(a)} ${dn.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(dn.dim(`
557
+ ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as o$}from"commander";import Yn from"chalk";import{spawn as t$}from"node:child_process";import{execFileSync as e$}from"node:child_process";function Im(e=()=>e$("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var Nm=new o$().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(Yn.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-JDY2FZUF.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Im();if(n?.ok){let{fetchAgents:l}=await import("./client-JDY2FZUF.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(Yn.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:t$,log:k=>console.error(Yn.dim(k))});return}n&&!n.ok&&(console.error(Yn.yellow(n.reason)),console.error(Yn.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-HF6W6CV2.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as n$}from"commander";import K from"chalk";import{randomUUID as Dm}from"crypto";import{createInterface as s$}from"node:readline/promises";import i$ from"ora";import li from"chalk";function Rm(e){console.error(),console.error(li.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(li.dim(` ${e.why}`)),console.error(),console.error(` Use ${li.cyan(e.instead)} instead.`),e.note&&console.error(li.dim(` ${e.note}`)),console.error()}var _m={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 Pm=new n$().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{Rm({what:"agentx chat",..._m});let t=Dl({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Dm().slice(0,12)}`,r=[];try{r=await ks(t)}catch(g){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(K.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(K.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(K.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-74VBWP7R.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}a$(t.baseUrl,n,i,s);let a=s$({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
558
+ 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:${Dm().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await ks(t);for(let h of p){let w=h.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${w} @${h.id} ${K.dim(h.tier)} ${h.model??""}`)}}catch(p){console.error(K.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await ks(t)).find(w=>w.id===p)){console.log(K.red(` unknown agent: @${p}`));continue}n=p,console.log(K.dim(` now talking to @${n}`))}catch(h){console.error(K.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(K.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=i$({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=r$(n);try{let p=await Pl(t,n,g,{channel:s,chatId:i,onText:w=>{d.stop(),f.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),f.tool(w)}});d.stop();let h=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(h,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function r$(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
549
559
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
550
560
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
551
561
  `&&(t=!0)}},tool(r){if(i(),r.status==="start"&&r.name){let a=r.id||`${r.name}:${s.size}`;if(s.has(a))return;s.add(a),t||(process.stdout.write(`
@@ -560,17 +570,17 @@ agentx wiki questions`,me=C?.daemon?.port??C?.port??18800;try{let J=await fetch(
560
570
  `))},finishError(r){o&&!t&&process.stdout.write(`
561
571
  `),process.stdout.write(K.red(` \u2717 ${r}
562
572
 
563
- `))}}}function _w(e,o,t,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(K.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as Dw}from"commander";import Z from"chalk";import{readFileSync as Pw}from"fs";import{existsSync as Mw,readdirSync as Lw}from"fs";import{resolve as qw}from"path";var si=["user","feedback","project","reference"],Yo=new Dw().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Yo.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(!si.includes(e.type)){console.error(Z.red(` --type must be one of: ${si.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Uw();else try{o=Pw(e.file,"utf-8")}catch(s){console.error(Z.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Z.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new vt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Z.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Yo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new vt().list(e.agent);if(e.type){if(!si.includes(e.type)){console.error(Z.red(` --type must be one of: ${si.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.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 t)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(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Yo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new vt().get(o.agent,e);if(!n){console.error(Z.red(` no memory "${e}" for agent "${o.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)});Yo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new vt().remove(o.agent,e)){console.error(Z.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 memory "${e}" removed`))});Yo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new vt().indexMarkdown(e.agent);if(!t){console.log(Z.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var Hn=Yo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function ii(e){if(e)return[e];let o=qw(process.cwd(),".agentx/memory");return Mw(o)?Lw(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}Hn.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let o=new kt;for(let t of ii(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${Z.bold(t)} ${n||Z.dim("(none)")}`)}});Hn.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new kt,t=0;for(let n of ii(e.agent))for(let s of o.held(n))t++,console.log(` ${Z.bold(n)} ${Z.cyan(s.id)} ${Z.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(Z.dim(" nothing held"))});for(let e of["approve","reject"])Hn.command(e).description(e==="approve"?"let a held fact be used in prompts":"keep a held fact out of prompts for good").requiredOption("--agent <id>","agent id").argument("<id>","fact id (from `agentx memory facts held`)").action((o,t)=>{if(!new kt().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(Z.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});Hn.command("scrub").description("find stored facts that contain credentials; --apply deletes them").option("--agent <id>","one agent (default: all)").option("--apply","delete them (default: count only)").action(e=>{let o=new kt,t=0;for(let n of ii(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${Z.bold(n)} ${s}`),t+=s}console.log(e.apply?Z.green(` \u2713 deleted ${t} fact(s) containing credentials`):Z.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});Hn.command("flag-unsourced").description("mark facts about billing, accounts, outages or deploys that name no source as unverified; --apply writes (with a backup)").option("--agent <id>","one agent (default: all)").option("--apply","flag them (default: list only)").action(async e=>{let{flagUnsourced:o}=await import("./memory-migrate-ED37IBEL.js"),t=new kt,n=0;for(let s of ii(e.agent)){let i=o(t,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 Uw(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Vm();import Ur from"chalk";import{Command as Fw}from"commander";import{resolve as Ww}from"path";var bm=new Fw().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(Ww(e.cwd)),e.stdio!==!1?await Va():(bo.error("Only stdio transport is currently supported."),bo.info(`Usage: ${Ur.green("agentx serve --stdio")} or configure in your MCP client.`),bo.break(),bo.info("Add to Claude Code:"),bo.info(Ur.dim(" claude mcp add agentx -- npx agentx serve --stdio")),bo.break(),bo.info("Add to Cursor/MCP config:"),bo.info(Ur.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){ll(o)}});import{Command as Xw}from"commander";import ce from"chalk";import{spawn as Fr}from"child_process";import{mkdirSync as Qw,writeFileSync as ci,readFileSync as Zw,readdirSync as e$,rmSync as Am,openSync as Tm,existsSync as ri}from"fs";import{resolve as o$,join as Fe}from"path";import{randomBytes as t$}from"crypto";var km={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 Bw,readFileSync as Jw}from"fs";import{cpus as Hw,loadavg as Gw}from"os";import{resolve as zw}from"path";var vm="AGENTX_DEMO_STARTUP_TIMEOUT",Vw=60,Yw=300;function Kw(e,o){let t=Math.max(1,e/Math.max(1,o));return Math.min(Yw,Math.ceil(Vw*t))}function xm(e,o){if(e===void 0||e.trim()==="")return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error(`${o} must be a positive number of seconds, got "${e}"`);return t}function Sm(e){let o=zw(e,"agentx.json");if(!Bw(o))return;let t;try{t=JSON.parse(Jw(o,"utf8"))}catch{return}let n=ra.shape.demo.safeParse(t?.demo);if(!n.success)throw new Error(`${o}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function Em(e){let o=xm(e.flag,"--startup-timeout");if(o!==void 0)return{seconds:o,source:"--startup-timeout"};let t=xm(e.env,vm);if(t!==void 0)return{seconds:t,source:vm};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??Gw()[0],s=e.cpuCount??Hw().length;return{seconds:Kw(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var Om="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",n$="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function s$(e,o){return[{dir:Fe(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(km,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:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:Fe(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function i$(e,o,t){let n=Fe(e.dir,"workspaces",e.agentId);Qw(n,{recursive:!0}),ci(Fe(n,"CLAUDE.md"),`# ${e.agentName}
573
+ `))}}}function a$(e,o,t,n){console.log(),console.log(K.bold(" agentx chat")),console.log(K.dim(` daemon: ${e} \xB7 channel: ${n} \xB7 chatId: ${t}`)),console.log(K.dim(` agent: @${o} \xB7 /exit to quit \xB7 /agent <id> to switch`)),console.log()}import{Command as c$}from"commander";import Z from"chalk";import{readFileSync as l$}from"fs";import{existsSync as d$,readdirSync as g$}from"fs";import{resolve as m$}from"path";var di=["user","feedback","project","reference"],Qo=new c$().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Qo.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!di.includes(e.type)){console.error(Z.red(` --type must be one of: ${di.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await p$();else try{o=l$(e.file,"utf-8")}catch(s){console.error(Z.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Z.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new St().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Z.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Qo.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let t=new St().list(e.agent);if(e.type){if(!di.includes(e.type)){console.error(Z.red(` --type must be one of: ${di.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.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 t)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(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Qo.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{let n=new St().get(o.agent,e);if(!n){console.error(Z.red(` no memory "${e}" for agent "${o.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)});Qo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new St().remove(o.agent,e)){console.error(Z.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 memory "${e}" removed`))});Qo.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let t=new St().indexMarkdown(e.agent);if(!t){console.log(Z.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});var Vn=Qo.command("facts").description("review facts extracted from conversations (held, approve, reject, scrub)");function gi(e){if(e)return[e];let o=m$(process.cwd(),".agentx/memory");return d$(o)?g$(o).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}Vn.command("summary").description("count facts per agent by source trust and review state").option("--agent <id>","one agent (default: all)").action(e=>{let o=new xt;for(let t of gi(e.agent)){let n=Object.entries(o.trustSummary(t)).map(([s,i])=>`${s}: ${i}`).join(", ");console.log(` ${Z.bold(t)} ${n||Z.dim("(none)")}`)}});Vn.command("held").description("list facts waiting for review before they are used").option("--agent <id>","one agent (default: all)").action(e=>{let o=new xt,t=0;for(let n of gi(e.agent))for(let s of o.held(n))t++,console.log(` ${Z.bold(n)} ${Z.cyan(s.id)} ${Z.dim(`${s.source.channel} \xB7 ${s.source.date}`)}`),console.log(` ${s.content}`);t===0&&console.log(Z.dim(" nothing held"))});for(let e of["approve","reject"])Vn.command(e).description(e==="approve"?"let a held fact be used in prompts":"keep a held fact out of prompts for good").requiredOption("--agent <id>","agent id").argument("<id>","fact id (from `agentx memory facts held`)").action((o,t)=>{if(!new xt().review(t.agent,o,e==="approve"?"approved":"rejected")){console.error(Z.red(` no fact "${o}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(Z.green(` \u2713 ${o} ${e==="approve"?"approved":"rejected"}`))});Vn.command("scrub").description("find stored facts that contain credentials; --apply deletes them").option("--agent <id>","one agent (default: all)").option("--apply","delete them (default: count only)").action(e=>{let o=new xt,t=0;for(let n of gi(e.agent)){let s=o.scrubSecrets(n,!!e.apply);s&&console.log(` ${Z.bold(n)} ${s}`),t+=s}console.log(e.apply?Z.green(` \u2713 deleted ${t} fact(s) containing credentials`):Z.dim(` ${t} fact(s) contain credentials (never injected). Run with --apply to delete them.`))});Vn.command("flag-unsourced").description("mark facts about billing, accounts, outages or deploys that name no source as unverified; --apply writes (with a backup)").option("--agent <id>","one agent (default: all)").option("--apply","flag them (default: list only)").action(async e=>{let{flagUnsourced:o}=await import("./memory-migrate-ED37IBEL.js"),t=new xt,n=0;for(let s of gi(e.agent)){let i=o(t,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 p$(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}mp();import Xr from"chalk";import{Command as u$}from"commander";import{resolve as f$}from"path";var Mm=new u$().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(f$(e.cwd)),e.stdio!==!1?await ic():(ko.error("Only stdio transport is currently supported."),ko.info(`Usage: ${Xr.green("agentx serve --stdio")} or configure in your MCP client.`),ko.break(),ko.info("Add to Claude Code:"),ko.info(Xr.dim(" claude mcp add agentx -- npx agentx serve --stdio")),ko.break(),ko.info("Add to Cursor/MCP config:"),ko.info(Xr.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){bl(o)}});import{Command as S$}from"commander";import le from"chalk";import{spawn as Bm}from"child_process";import{mkdirSync as E$,writeFileSync as ui,readFileSync as A$,readdirSync as T$,rmSync as Jm,openSync as Hm,existsSync as mi}from"fs";import{resolve as O$,join as We}from"path";import{randomBytes as C$}from"crypto";var Lm={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"}]};ee();import{existsSync as h$,readFileSync as y$}from"fs";import{cpus as w$,loadavg as $$}from"os";import{resolve as b$}from"path";var qm="AGENTX_DEMO_STARTUP_TIMEOUT",k$=60,v$=300;function x$(e,o){let t=Math.max(1,e/Math.max(1,o));return Math.min(v$,Math.ceil(k$*t))}function Um(e,o){if(e===void 0||e.trim()==="")return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error(`${o} must be a positive number of seconds, got "${e}"`);return t}function Fm(e){let o=b$(e,"agentx.json");if(!h$(o))return;let t;try{t=JSON.parse(y$(o,"utf8"))}catch{return}let n=wa.shape.demo.safeParse(t?.demo);if(!n.success)throw new Error(`${o}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function Wm(e){let o=Um(e.flag,"--startup-timeout");if(o!==void 0)return{seconds:o,source:"--startup-timeout"};let t=Um(e.env,qm);if(t!==void 0)return{seconds:t,source:qm};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??$$()[0],s=e.cpuCount??w$().length;return{seconds:x$(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}var Gm="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",j$="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function I$(e,o){return[{dir:We(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(Lm,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:We(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:We(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function N$(e,o,t){let n=We(e.dir,"workspaces",e.agentId);E$(n,{recursive:!0}),ui(We(n,"CLAUDE.md"),`# ${e.agentName}
564
574
 
565
575
  ${e.persona}
566
- `),ci(Fe(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};ci(Fe(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Wr(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,250))}throw new Error(`Timed out waiting for ${e} (${t/1e3}s) \u2014 raise it with --startup-timeout <seconds>`)}function Br(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function Jr(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function ai(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
576
+ `),ui(We(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};ui(We(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Qr(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,250))}throw new Error(`Timed out waiting for ${e} (${t/1e3}s) \u2014 raise it with --startup-timeout <seconds>`)}function Zr(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function ea(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function pi(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
567
577
  `).join(`
568
- `)}`)}var Cm=new Xw().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").option("--startup-timeout <seconds>","seconds each startup step may take (default: 60, longer when the machine is loaded)").action(async e=>{let o=parseInt(e.basePort,10),t=o$(process.cwd(),".agentx-demo"),n;try{n=Em({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:Sm(process.cwd())})}catch(h){console.error(ce.red(h.message)),process.exit(1)}let s=n.seconds*1e3,i=s$(t,o),r=Fe(t,"mesh-token"),a=!!e.reuse&&ri(r)&&ri(Fe(i[0].dir,"agentx.json")),c=a?Zw(r,"utf8").trim():t$(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!ri(d))&&(console.error(ce.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if(ri(t))for(let h of e$(t))Am(Fe(t,h),{recursive:!0,force:!0});for(let h of i)i$(h,i,c);ci(r,c+`
569
- `,{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{Am(t,{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 $ of i){let E=Tm(Fe($.dir,"daemon.log"),"a"),S=Fr(process.execPath,[d,"daemon","start","-c",Fe($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:Fe($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(ce.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${Fe($.dir,"daemon.log")})`))}let h=$=>Wr(`${$.name} /health`,async()=>(await Br(`http://127.0.0.1:${$.port}/health`)).ok,s);await h(i[0]);let w=i[0].port+10;{let $=Tm(Fe(i[0].dir,"board.log"),"a"),E=Fr(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",$,$]});g.push(E)}for(let $ of i.slice(1))await h($);console.log(ce.green(" \u2713 three daemons up")),await Wr("dashboard /live",async()=>(await Br(`http://127.0.0.1:${w}/live`)).ok,s),console.log(ce.green(" \u2713 dashboard up")),await Wr("mesh discovery (laptop sees both peers)",async()=>((await(await Br(`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($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1){let $=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Fr($,[k],{stdio:"ignore",detached:!0}).unref()}catch{}}let b=async()=>{console.log(),console.log(ce.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),ai("You \u2192 @cx (laptop-paris)",Om,ce.cyan);let $=await Jr(i[0].port,"/task",{agent:"cx",message:Om});ai("@cx (laptop-paris)",$.content||"(no content)",ce.green),console.log(),console.log(ce.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await Jr(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:n$}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";ai("@builder (vps-nyc)",S,ce.yellow);let x=await Jr(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});ai("@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 b(),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",()=>{b().catch($=>console.error(ce.red(` Replay failed: ${$.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 r$}from"commander";import{randomUUID as a$}from"crypto";import{readFileSync as c$}from"fs";import{resolve as l$}from"path";ne();var Im=new r$().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??c$(0,"utf8")).trim();t||jm("no task given (pass it as an argument or on stdin)");let n=j(o.config?l$(o.config):void 0),s=n.agents[o.agent];s||jm(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";wa(o.agent,s,l,i)}let r=new Ma(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${a$()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
578
+ `)}`)}var zm=new S$().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").option("--startup-timeout <seconds>","seconds each startup step may take (default: 60, longer when the machine is loaded)").action(async e=>{let o=parseInt(e.basePort,10),t=O$(process.cwd(),".agentx-demo"),n;try{n=Wm({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:Fm(process.cwd())})}catch(h){console.error(le.red(h.message)),process.exit(1)}let s=n.seconds*1e3,i=I$(t,o),r=We(t,"mesh-token"),a=!!e.reuse&&mi(r)&&mi(We(i[0].dir,"agentx.json")),c=a?A$(r,"utf8").trim():C$(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!mi(d))&&(console.error(le.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if(mi(t))for(let h of T$(t))Jm(We(t,h),{recursive:!0,force:!0});for(let h of i)N$(h,i,c);ui(r,c+`
579
+ `,{mode:384})}console.log(),console.log(le.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(le.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(le.dim(" Run `agentx setup` to wire real agents.\n")),console.log(le.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{Jm(t,{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 $ of i){let E=Hm(We($.dir,"daemon.log"),"a"),S=Bm(process.execPath,[d,"daemon","start","-c",We($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:We($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(le.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${We($.dir,"daemon.log")})`))}let h=$=>Qr(`${$.name} /health`,async()=>(await Zr(`http://127.0.0.1:${$.port}/health`)).ok,s);await h(i[0]);let w=i[0].port+10;{let $=Hm(We(i[0].dir,"board.log"),"a"),E=Bm(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",$,$]});g.push(E)}for(let $ of i.slice(1))await h($);console.log(le.green(" \u2713 three daemons up")),await Qr("dashboard /live",async()=>(await Zr(`http://127.0.0.1:${w}/live`)).ok,s),console.log(le.green(" \u2713 dashboard up")),await Qr("mesh discovery (laptop sees both peers)",async()=>((await(await Zr(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(x=>x.healthy&&x.skills?.length).length>=2,s),console.log(le.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let k=`http://127.0.0.1:${w}/live`;console.log(),console.log(` Dashboard: ${le.cyan(k)} (all three nodes via the mesh)`),console.log(le.dim(` Daemon APIs: ${i.map($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1&&nt(k);let b=async()=>{console.log(),console.log(le.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),pi("You \u2192 @cx (laptop-paris)",Gm,le.cyan);let $=await ea(i[0].port,"/task",{agent:"cx",message:Gm});pi("@cx (laptop-paris)",$.content||"(no content)",le.green),console.log(),console.log(le.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await ea(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:j$}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";pi("@builder (vps-nyc)",S,le.yellow);let x=await ea(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});pi("@cx (laptop-paris)",x.content||"(no content)",le.green),console.log(),console.log(le.dim(` Inspect the run: ${k} \xB7 ledger rows on each node record every dispatch`)),console.log(le.dim(` Worth your time? A star helps others find it: ${le.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(le.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await b(),e.once){console.log(),console.log(le.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(le.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{b().catch($=>console.error(le.red(` Replay failed: ${$.message}`)))}),process.stdin.resume()}catch(h){console.error(),console.error(le.red(` Demo failed: ${h.message}`)),console.error(le.dim(` Node logs: ${i.map(w=>We(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as R$}from"commander";import{randomUUID as _$}from"crypto";import{readFileSync as D$}from"fs";import{resolve as P$}from"path";ee();var Vm=new R$().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??D$(0,"utf8")).trim();t||Ym("no task given (pass it as an argument or on stdin)");let n=O(o.config?P$(o.config):void 0),s=n.agents[o.agent];s||Ym(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";ja(o.agent,s,l,i)}let r=new Ya(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${_$()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
570
580
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
571
- `),process.exit(c.error?1:0)});function jm(e){console.error(`agentx exec: ${e}`),process.exit(1)}ne();import{Command as g$}from"commander";import Re from"chalk";import{Command as d$}from"commander";import Ne from"chalk";ne();var ht=new d$("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function Gn(e){let o="",t=await pe(n=>{n.whatsappTriage=n.whatsappTriage&&typeof n.whatsappTriage=="object"?n.whatsappTriage:{},n.whatsappTriage.rules=Array.isArray(n.whatsappTriage.rules)?n.whatsappTriage.rules:[],o=e(n.whatsappTriage,n)});t.success||(console.error(Ne.red(`\u2717 ${t.error}`)),process.exit(1)),console.log(Ne.green(`\u2713 ${o}`)),t.reloaded&&console.log(Ne.dim(" daemon hot-reloaded"))}function Rm(e,o){let t=e.rules.find(n=>n.id===o);if(!t)throw new Error(`No watch rule "${o}". See \`agentx whatsapp triage status\`.`);return t}var Nm=(e,o=[])=>[...o,e];ht.command("status").description("show triage settings and watch rules").action(()=>{let e=j().whatsappTriage,o=!!process.env[e.secretEnv];console.log(),console.log(` WhatsApp triage: ${e.enabled?Ne.green("on"):Ne.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${o?Ne.green("set in this shell"):Ne.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(Ne.dim(" no watch rules yet: agentx whatsapp triage rule add <id> --agent <agent> --chat <number or JID>"));for(let t of e.rules){let n=t.quietHours?` \xB7 quiet ${t.quietHours.start}\u2013${t.quietHours.end}`:"";console.log(` ${t.enabled?Ne.green("\u25CF"):Ne.dim("\u25CB")} ${Ne.bold(t.id)} \u2192 ${t.agent}${n}${t.autoAck?" \xB7 autoAck":""}`),t.chats.length&&console.log(Ne.dim(` chats: ${t.chats.join(", ")}`)),t.senders.length&&console.log(Ne.dim(` senders: ${t.senders.join(", ")}`))}console.log()});ht.command("on").description("turn triage on").action(()=>Gn(e=>(e.enabled=!0,"WhatsApp triage is on")));ht.command("off").description("turn triage off").action(()=>Gn(e=>(e.enabled=!1,"WhatsApp triage is off")));ht.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let o=bt();o||(console.error(Ne.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let t=new Vc(o).recent(Math.max(1,Number(e.limit)||20));if(t.length===0){console.log(Ne.dim(" nothing triaged yet"));return}for(let n of t){let s=new Date(n.at).toISOString().slice(0,16).replace("T"," "),i=n.error?Ne.red(n.error):`${Ne.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${Ne.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?Ne.dim(` draft whatsapp:${n.draftId}`):""}`)}});var Hr=ht.command("rule").description("add, remove, enable or disable a watch rule");Hr.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)",Nm).option("--sender <jid>","only messages from this person (repeatable)",Nm).option("--prompt <text>","extra instructions for the agent").option("--quiet <range>","no notifications in this window, e.g. 22:00-07:00").option("--auto-ack","send short acknowledgements without asking (also needs allowAutoAck)").action((e,o)=>Gn((t,n)=>{if(!n.agents?.[o.agent])throw new Error(`No agent "${o.agent}" on this computer.`);if(t.rules.some(i=>i.id===e))throw new Error(`Watch rule "${e}" already exists.`);let s={id:e,agent:o.agent,chats:o.chat??[],senders:o.sender??[]};if(o.prompt&&(s.prompt=o.prompt),o.quiet){let i=String(o.quiet).match(/^(\d{2}:\d{2})-(\d{2}:\d{2})$/);if(!i)throw new Error("--quiet looks like 22:00-07:00");s.quietHours={start:i[1],end:i[2]}}return o.autoAck&&(s.autoAck=!0),t.rules.push(s),`added watch rule "${e}" \u2192 ${o.agent}`}));Hr.command("remove <id>").description("delete a watch rule").action(e=>Gn(o=>(Rm(o,e),o.rules=o.rules.filter(t=>t.id!==e),`removed watch rule "${e}"`)));for(let[e,o]of[["enable",!0],["disable",!1]])Hr.command(`${e} <id>`).description(`${e} a watch rule`).action(t=>Gn(n=>(Rm(n,t).enabled=o,`watch rule "${t}" ${o?"enabled":"disabled"}`)));var Co=new g$().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Co.addCommand(ht);Co.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await zn("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Re.dim(" no chats cached yet"));return}console.log(),console.log(Re.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Re.cyan("group"):Re.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Re.dim(n.jid.padEnd(40))} ${Re.dim(i)}`)}console.log()}catch(o){cn(o)}});Co.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await zn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Re.dim(" no contacts cached yet"));return}console.log(),console.log(Re.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Re.dim(i)} ${Re.dim(n.jid)}`)}console.log()}catch(o){cn(o)}});Co.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await zr("/whatsapp/ingest",o);Gr(t,!!e.dryRun)}catch(o){cn(o)}});Co.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await zr("/whatsapp/ingest",t);Gr(n,!!o.dryRun)}catch(t){cn(t)}});Co.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await zr("/whatsapp/ingest",t);Gr(n,!!o.dryRun)}catch(t){cn(t)}});Co.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await zn("/whatsapp/state"),o=await zn("/whatsapp/chats"),t=await zn("/whatsapp/contacts");console.log(),console.log(Re.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){cn(e)}});function Gr(e,o){if(console.log(),console.log(Re.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Re.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Re.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Re.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Re.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Re.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function _m(){try{let e=j(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function zn(e){let o=await fetch(`${_m()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function zr(e,o){let t=await fetch(`${_m()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function cn(e){console.error(Re.red(` ${e.message||e}`)),process.exit(1)}ne();import{Command as m$}from"commander";import ge from"chalk";import{existsSync as p$,mkdirSync as Dm,writeFileSync as Vn}from"fs";import{join as ln,resolve as u$}from"path";var Yn=new m$().name("plugin").description("manage agentx plugins (Move B)");Yn.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=j().plugins??[];if(console.log(),o.length===0){console.log(ge.dim(" No plugins configured.")),console.log(ge.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ge.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ge.cyan(t)}`);console.log(),console.log(ge.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});Yn.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(ge.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=u$(o.cwd,t);p$(n)&&!o.force&&(console.log(ge.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Dm(n,{recursive:!0}),Dm(ln(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Vn(ln(n,"package.json"),w$(e,s)),Vn(ln(n,"tsconfig.json"),$$()),Vn(ln(n,"src/index.ts"),b$(e)),Vn(ln(n,"README.md"),k$(e,s)),Vn(ln(n,".gitignore"),v$()),console.log(),console.log(ge.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ge.bold(" Next steps:")),console.log(ge.dim(` cd ${t}`)),console.log(ge.dim(" pnpm install")),console.log(ge.dim(" pnpm build")),console.log(ge.dim(" pnpm link --global # for local testing")),console.log(ge.dim(" # then in your agentx project:")),console.log(ge.dim(` pnpm link --global ${e}`)),console.log(ge.dim(` agentx config set plugins[0] "${e}"`)),console.log(ge.dim(" agentx plugin doctor")),console.log()});Yn.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=j().plugins??[];if(console.log(),o.length===0){console.log(ge.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await f$(n);s.kind==="ok"?console.log(` ${ge.green("\u2713")} ${ge.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ge.red("\u2717")} ${ge.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ge.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ge.red(` ${e.message}`)),process.exitCode=1}});async function f$(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=h$(o);if(!y$(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Oc.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function h$(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function y$(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function w$(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
572
- `}function $$(){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)+`
573
- `}function b$(e){return`// ${e} \u2014 AgentX plugin
581
+ `),process.exit(c.error?1:0)});function Ym(e){console.error(`agentx exec: ${e}`),process.exit(1)}ee();import{Command as L$}from"commander";import Re from"chalk";import{Command as M$}from"commander";import Ne from"chalk";ee();ns();var $t=new M$("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function Kn(e){let o="",t=await se(n=>{n.whatsappTriage=n.whatsappTriage&&typeof n.whatsappTriage=="object"?n.whatsappTriage:{},n.whatsappTriage.rules=Array.isArray(n.whatsappTriage.rules)?n.whatsappTriage.rules:[],o=e(n.whatsappTriage,n)});t.success||(console.error(Ne.red(`\u2717 ${t.error}`)),process.exit(1)),console.log(Ne.green(`\u2713 ${o}`)),t.reloaded&&console.log(Ne.dim(" daemon hot-reloaded"))}function Xm(e,o){let t=e.rules.find(n=>n.id===o);if(!t)throw new Error(`No watch rule "${o}". See \`agentx whatsapp triage status\`.`);return t}var Km=(e,o=[])=>[...o,e];$t.command("status").description("show triage settings and watch rules").action(()=>{let e=O().whatsappTriage,o=!!process.env[e.secretEnv];console.log(),console.log(` WhatsApp triage: ${e.enabled?Ne.green("on"):Ne.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${o?Ne.green("set in this shell"):Ne.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(Ne.dim(" no watch rules yet: agentx whatsapp triage rule add <id> --agent <agent> --chat <number or JID>"));for(let t of e.rules){let n=t.quietHours?` \xB7 quiet ${t.quietHours.start}\u2013${t.quietHours.end}`:"";console.log(` ${t.enabled?Ne.green("\u25CF"):Ne.dim("\u25CB")} ${Ne.bold(t.id)} \u2192 ${t.agent}${n}${t.autoAck?" \xB7 autoAck":""}`),t.chats.length&&console.log(Ne.dim(` chats: ${t.chats.join(", ")}`)),t.senders.length&&console.log(Ne.dim(` senders: ${t.senders.join(", ")}`))}console.log()});$t.command("on").description("turn triage on").action(()=>Kn(e=>(e.enabled=!0,"WhatsApp triage is on")));$t.command("off").description("turn triage off").action(()=>Kn(e=>(e.enabled=!1,"WhatsApp triage is off")));$t.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let o=No();o||(console.error(Ne.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let t=new il(o).recent(Math.max(1,Number(e.limit)||20));if(t.length===0){console.log(Ne.dim(" nothing triaged yet"));return}for(let n of t){let s=new Date(n.at).toISOString().slice(0,16).replace("T"," "),i=n.error?Ne.red(n.error):`${Ne.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${Ne.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?Ne.dim(` draft whatsapp:${n.draftId}`):""}`)}});var oa=$t.command("rule").description("add, remove, enable or disable a watch rule");oa.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)",Km).option("--sender <jid>","only messages from this person (repeatable)",Km).option("--prompt <text>","extra instructions for the agent").option("--quiet <range>","no notifications in this window, e.g. 22:00-07:00").option("--auto-ack","send short acknowledgements without asking (also needs allowAutoAck)").action((e,o)=>Kn((t,n)=>{if(!n.agents?.[o.agent])throw new Error(`No agent "${o.agent}" on this computer.`);if(t.rules.some(i=>i.id===e))throw new Error(`Watch rule "${e}" already exists.`);let s={id:e,agent:o.agent,chats:o.chat??[],senders:o.sender??[]};if(o.prompt&&(s.prompt=o.prompt),o.quiet){let i=String(o.quiet).match(/^(\d{2}:\d{2})-(\d{2}:\d{2})$/);if(!i)throw new Error("--quiet looks like 22:00-07:00");s.quietHours={start:i[1],end:i[2]}}return o.autoAck&&(s.autoAck=!0),t.rules.push(s),`added watch rule "${e}" \u2192 ${o.agent}`}));oa.command("remove <id>").description("delete a watch rule").action(e=>Kn(o=>(Xm(o,e),o.rules=o.rules.filter(t=>t.id!==e),`removed watch rule "${e}"`)));for(let[e,o]of[["enable",!0],["disable",!1]])oa.command(`${e} <id>`).description(`${e} a watch rule`).action(t=>Kn(n=>(Xm(n,t).enabled=o,`watch rule "${t}" ${o?"enabled":"disabled"}`)));var jo=new L$().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");jo.addCommand($t);jo.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await Xn("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Re.dim(" no chats cached yet"));return}console.log(),console.log(Re.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Re.cyan("group"):Re.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Re.dim(n.jid.padEnd(40))} ${Re.dim(i)}`)}console.log()}catch(o){gn(o)}});jo.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await Xn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Re.dim(" no contacts cached yet"));return}console.log(),console.log(Re.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Re.dim(i)} ${Re.dim(n.jid)}`)}console.log()}catch(o){gn(o)}});jo.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await na("/whatsapp/ingest",o);ta(t,!!e.dryRun)}catch(o){gn(o)}});jo.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await na("/whatsapp/ingest",t);ta(n,!!o.dryRun)}catch(t){gn(t)}});jo.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await na("/whatsapp/ingest",t);ta(n,!!o.dryRun)}catch(t){gn(t)}});jo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Xn("/whatsapp/state"),o=await Xn("/whatsapp/chats"),t=await Xn("/whatsapp/contacts");console.log(),console.log(Re.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){gn(e)}});function ta(e,o){if(console.log(),console.log(Re.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Re.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Re.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Re.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Re.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Re.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Qm(){try{let e=O(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function Xn(e){let o=await fetch(`${Qm()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function na(e,o){let t=await fetch(`${Qm()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function gn(e){console.error(Re.red(` ${e.message||e}`)),process.exit(1)}ee();import{Command as q$}from"commander";import me from"chalk";import{existsSync as U$,mkdirSync as Zm,writeFileSync as Qn}from"fs";import{join as mn,resolve as F$}from"path";var Zn=new q$().name("plugin").description("manage agentx plugins (Move B)");Zn.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=O().plugins??[];if(console.log(),o.length===0){console.log(me.dim(" No plugins configured.")),console.log(me.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(me.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${me.cyan(t)}`);console.log(),console.log(me.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(me.red(` ${e.message}`)),process.exitCode=1}});Zn.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(me.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=F$(o.cwd,t);U$(n)&&!o.force&&(console.log(me.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Zm(n,{recursive:!0}),Zm(mn(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Qn(mn(n,"package.json"),H$(e,s)),Qn(mn(n,"tsconfig.json"),G$()),Qn(mn(n,"src/index.ts"),z$(e)),Qn(mn(n,"README.md"),Y$(e,s)),Qn(mn(n,".gitignore"),V$()),console.log(),console.log(me.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(me.bold(" Next steps:")),console.log(me.dim(` cd ${t}`)),console.log(me.dim(" pnpm install")),console.log(me.dim(" pnpm build")),console.log(me.dim(" pnpm link --global # for local testing")),console.log(me.dim(" # then in your agentx project:")),console.log(me.dim(` pnpm link --global ${e}`)),console.log(me.dim(` agentx config set plugins[0] "${e}"`)),console.log(me.dim(" agentx plugin doctor")),console.log()});Zn.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=O().plugins??[];if(console.log(),o.length===0){console.log(me.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await W$(n);s.kind==="ok"?console.log(` ${me.green("\u2713")} ${me.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${me.red("\u2717")} ${me.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(me.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(me.red(` ${e.message}`)),process.exitCode=1}});async function W$(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=B$(o);if(!J$(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=qc.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function B$(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function J$(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function H$(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
582
+ `}function G$(){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)+`
583
+ `}function z$(e){return`// ${e} \u2014 AgentX plugin
574
584
  //
575
585
  // A plugin's default export is { manifest, setup }. The daemon calls
576
586
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -606,7 +616,7 @@ const plugin = {
606
616
  }
607
617
 
608
618
  export default plugin
609
- `}function k$(e,o){return`# ${e}
619
+ `}function Y$(e,o){return`# ${e}
610
620
 
611
621
  ${o}
612
622
 
@@ -633,24 +643,24 @@ agentx plugin doctor
633
643
  \`\`\`
634
644
 
635
645
  Restart the daemon to activate.
636
- `}function v$(){return`node_modules/
646
+ `}function V$(){return`node_modules/
637
647
  dist/
638
648
  *.log
639
649
  .env
640
- `}import{Command as x$}from"commander";import _e from"chalk";import{writeFileSync as S$,mkdirSync as E$,existsSync as li,readFileSync as Pm,appendFileSync as Mm}from"fs";import{resolve as dn,dirname as Um}from"path";import{homedir as Yr}from"os";var Fm=new x$().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-KMQNX6YK.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=O$(t);break;case"bash":s=R$(t);break;case"fish":s=_$(t);break;default:console.error(_e.red(`unsupported shell: ${n}`)),console.error(_e.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?dn(String(e.output)):A$(n);E$(Um(i),{recursive:!0}),S$(i,s),console.log(_e.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),T$(n,i,!!e.yes)});function A$(e){let o=Yr();switch(e){case"zsh":return dn(o,".zsh","completions","_agentx");case"bash":return dn(o,".bash_completion.d","agentx.bash");case"fish":return dn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function T$(e,o,t){if(e==="zsh"){let n=dn(Yr(),".zshrc"),s=Um(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=li(n)?Pm(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(_e.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&li(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Mm(n,g.join(`
650
+ `}import{Command as K$}from"commander";import _e from"chalk";import{writeFileSync as X$,mkdirSync as Q$,existsSync as fi,readFileSync as ep,appendFileSync as op}from"fs";import{resolve as pn,dirname as sp}from"path";import{homedir as ia}from"os";var ip=new K$().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-FUYHN2F7.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=ob(t);break;case"bash":s=rb(t);break;case"fish":s=ab(t);break;default:console.error(_e.red(`unsupported shell: ${n}`)),console.error(_e.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?pn(String(e.output)):Z$(n);Q$(sp(i),{recursive:!0}),X$(i,s),console.log(_e.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),eb(n,i,!!e.yes)});function Z$(e){let o=ia();switch(e){case"zsh":return pn(o,".zsh","completions","_agentx");case"bash":return pn(o,".bash_completion.d","agentx.bash");case"fish":return pn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eb(e,o,t){if(e==="zsh"){let n=pn(ia(),".zshrc"),s=sp(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=fi(n)?ep(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(_e.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&fi(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),op(n,g.join(`
641
651
  `)+`
642
- `),console.log(_e.green("\u2713 Patched ~/.zshrc")),console.log(_e.dim("Reload your shell: exec zsh"));return}console.log(_e.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(_e.cyan(` ${i}`)),l&&console.log(_e.cyan(` ${r}`)),console.log(),console.log(_e.dim("Then reload: exec zsh")),console.log(_e.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=dn(Yr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((li(n)?Pm(n,"utf-8"):"").includes(o)){console.log(_e.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&li(n)){Mm(n,`
652
+ `),console.log(_e.green("\u2713 Patched ~/.zshrc")),console.log(_e.dim("Reload your shell: exec zsh"));return}console.log(_e.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(_e.cyan(` ${i}`)),l&&console.log(_e.cyan(` ${r}`)),console.log(),console.log(_e.dim("Then reload: exec zsh")),console.log(_e.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=pn(ia(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((fi(n)?ep(n,"utf-8"):"").includes(o)){console.log(_e.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&fi(n)){op(n,`
643
653
  # agentx completion
644
654
  ${s}
645
- `),console.log(_e.green("\u2713 Patched ~/.bashrc")),console.log(_e.dim("Reload your shell: exec bash"));return}console.log(_e.dim("Add this to ~/.bashrc:")),console.log(_e.cyan(` ${s}`)),console.log(),console.log(_e.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(_e.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Ke(e){return e._name||e.name()||""}function Ko(e){return e.commands.filter(o=>{let t=Ke(o);return!(!t||t==="help")})}function Kn(e){return e.options.filter(o=>!o.hidden)}function O$(e){let o=[];return o.push("#compdef agentx"),o.push(""),Wm(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
646
- `)}function Lm(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Wm(e,o,t){let n=Ko(e),i=Kn(e).map(I$).filter(c=>!!c),r=Lm(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(N$).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let l=Lm([...o,Ke(c)]);t.push(` (${Ke(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Wm(c,[...o,Ke(c)],t)}function C$(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function j$(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function I$(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=C$(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function N$(e){let o=j$(e.description()||"");return`'${Ke(e)}[${o}]'`}function R$(e){let o=Ko(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Ke).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=Ko(n).map(Ke),i=qm(n);if(t.push(` ${Ke(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of Ko(n)){let a=qm(r);t.push(` ${Ke(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
647
- `)}function qm(e){let o=[];for(let t of Kn(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function _$(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of Ko(e)){let n=Kr(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Ke(t)}" -d "${n}"`)}o.push("");for(let t of Kn(e)){let n=Vr(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Ko(e)){let n=Ke(t);o.push(`# ${n}`);for(let s of Kn(t)){let i=Vr(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Ko(t)){let i=Kr(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Ko(t).map(Ke).join(" ")}" -a "${Ke(s)}" -d "${i}"`);for(let r of Kn(s)){let a=Vr(r,[`__fish_seen_subcommand_from ${Ke(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
648
- `)}function Kr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Vr(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Kr(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}import{Command as P$}from"commander";import mn from"chalk";import{readFile as M$}from"node:fs/promises";var gn="anis-marrouchi/agentx",Xr=`https://raw.githubusercontent.com/${gn}/main/contrib/models.json`,gi=`https://github.com/${gn}/issues/new/choose`,Jm=`https://github.com/${gn}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,Bm=8e3,di={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,o){let t=e.trim().toLowerCase();return t?o.models.some(n=>{let s=n.id.toLowerCase();return t===s||t.startsWith(`${s}-`)||(n.aliases??[]).some(i=>i.toLowerCase()===t)}):!1}function Zr(e,o){return[`The model "${e}" is not on the recommended list for drafting AgentX issues.`,`The list (${o.models.map(t=>t.id).join(", ")}) keeps drafts clear and consistent; it says nothing about you or your idea.`,`Please write the issue yourself with the web form, which is always available: ${gi}`].join(`
649
- `)}function D$(e){return`---
650
- _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function Hm(e,o){let t=di[e.category];if(!t)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(di).join(", ")}`);let n=new Set(t.fields.map(l=>l.id)),s=Object.keys(e.fields).filter(l=>!n.has(l));if(s.length)throw new Error(`Unknown field(s) for ${e.category}: ${s.join(", ")}. Expected: ${[...n].join(", ")}`);let i=t.fields.filter(l=>l.required&&!e.fields[l.id]?.trim()).map(l=>l.id);if(i.length)throw new Error(`Missing required field(s) for ${e.category}: ${i.join(", ")}`);let r=e.title.trim();if(!r)throw new Error("The issue needs a title");r.toLowerCase().startsWith(t.titlePrefix.toLowerCase())||(r=t.titlePrefix+r);let a=new URLSearchParams({template:t.template,title:r});for(let l of t.fields){let g=e.fields[l.id]?.trim()??"";l.id===t.footerField&&(g=`${g}
651
-
652
- ${D$({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${gn}/issues/new?${a.toString()}`;if(c.length>Bm)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${Bm}). Shorten it, or paste it into the web form.`);return c}async function Gm(e,o=fetch){let t=`repo:${gn} is:issue is:open ${e}`,n=await o(`https://api.github.com/search/issues?per_page=10&q=${encodeURIComponent(t)}`,{headers:{accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`GitHub search failed (HTTP ${n.status}). Search by hand: https://github.com/${gn}/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 ea(e,o=fetch){let t;if(/^https?:\/\//.test(e)){let s=await o(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Could not read the model list (HTTP ${s.status}) from ${e}`);t=await s.text()}else{let{readFile:s}=await import("node:fs/promises");t=await s(e,"utf8")}let n=JSON.parse(t);if(!Array.isArray(n.models))throw new Error(`The model list at ${e} has no "models" array`);return n}var Xn=new P$().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(mn.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${gi}`),console.log(" 2. Let your agent help: install the skill with"),console.log(mn.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: ${Jm}`),console.log(` Categories: ${Object.keys(di).join(", ")}`),console.log()});Xn.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",Xr).action(async(e,o)=>{try{let t=await ea(o.models);if(Qr(e,t)){console.log(mn.green(` "${e}" is on the recommended list.`));return}console.log(Zr(e,t)),process.exitCode=1}catch(t){console.error(mn.red(` ${t.message}`)),console.error(` You can always write the issue yourself: ${gi}`),process.exitCode=1}});Xn.command("search <words...>").description("list open issues that match, most-voted first \u2014 check for duplicates before drafting").action(async e=>{try{let o=await Gm(e.join(" "));if(!o.length){console.log(" No open issue matches. It looks new.");return}for(let t of o)console.log(` #${t.number} \u{1F44D} ${t.votes} ${t.title}
653
- ${t.url}`)}catch(o){console.error(mn.red(` ${o.message}`)),process.exitCode=1}});Xn.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",Xr).action(async(e,o)=>{try{let t=await ea(o.models);if(!Qr(o.model,t)){console.log(Zr(o.model,t)),process.exitCode=1;return}let n=e==="-"?await L$():await M$(e,"utf8"),s=JSON.parse(n),{version:i}=await ns(),r=Hm({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(mn.red(` ${t.message}`)),process.exitCode=1}});async function L$(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function IC(){let e=await ns(),o=new q$().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=$l(n);bl(s)&&wl("cli",s)});for(let t of[Vl,Hl,Kt,Nt,Dt,to,fl,ot,Es,So,Ao,Vt,Ho,Ss,fm,Wo,ud,xd,Rn,_d,Ld,Fd,Jd,Hd,cg,mg,pg,Ht,qn,bm,An,Mo,Fm,Xn])o.addCommand(t);for(let t of zm)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=zm.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,U$(t,74," "),""].join(`
654
- `)}),o}var zm=[ee,Zt,Yo,mo,On,Gt,Ye,Oo,Go,gt,nn,sn,Uo,He,qt,Bs,mm,pm,vo,tt,El,nt,Yn,Vi,Vo,Mt,Yi,ti,$o,Co,Cm,Im,$m];function U$(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
655
- `)}export{IC as a};
656
- //# sourceMappingURL=chunk-AF46YOLU.js.map
655
+ `),console.log(_e.green("\u2713 Patched ~/.bashrc")),console.log(_e.dim("Reload your shell: exec bash"));return}console.log(_e.dim("Add this to ~/.bashrc:")),console.log(_e.cyan(` ${s}`)),console.log(),console.log(_e.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(_e.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Xe(e){return e._name||e.name()||""}function Zo(e){return e.commands.filter(o=>{let t=Xe(o);return!(!t||t==="help")})}function es(e){return e.options.filter(o=>!o.hidden)}function ob(e){let o=[];return o.push("#compdef agentx"),o.push(""),rp(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
656
+ `)}function tp(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function rp(e,o,t){let n=Zo(e),i=es(e).map(sb).filter(c=>!!c),r=tp(o);if(t.push(`${r}() {`),t.push(" local -a commands"),t.push(" local -a options"),t.push(" "),i.length===0&&n.length===0){t.push(" return 0"),t.push("}"),t.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(ib).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}t.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;t.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){t.push(""),t.push(" case $state in"),t.push(" (args)"),t.push(" case $line[1] in");for(let c of n){let l=tp([...o,Xe(c)]);t.push(` (${Xe(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)rp(c,[...o,Xe(c)],t)}function tb(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function nb(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function sb(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=tb(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function ib(e){let o=nb(e.description()||"");return`'${Xe(e)}[${o}]'`}function rb(e){let o=Zo(e),t=[];t.push("# bash completion for agentx"),t.push("_agentx_complete() {"),t.push(" local cur prev words cword"),t.push(" COMPREPLY=()"),t.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),t.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),t.push(""),t.push(` local top="${o.map(Xe).join(" ")}"`),t.push(""),t.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),t.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),t.push(" return 0"),t.push(" fi"),t.push(""),t.push(' local cmd="${COMP_WORDS[1]}"'),t.push(' local sub2="${COMP_WORDS[2]:-}"'),t.push(' case "$cmd" in');for(let n of o){let s=Zo(n).map(Xe),i=np(n);if(t.push(` ${Xe(n)})`),s.length>0){t.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),t.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),t.push(" return 0"),t.push(" fi"),t.push(' case "$sub2" in');for(let r of Zo(n)){let a=np(r);t.push(` ${Xe(r)})`),t.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),t.push(" return 0"),t.push(" ;;")}t.push(" esac")}else t.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);t.push(" ;;")}return t.push(" esac"),t.push("}"),t.push(""),t.push("complete -F _agentx_complete agentx"),t.push(""),t.join(`
657
+ `)}function np(e){let o=[];for(let t of es(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function ab(e){let o=[];o.push("# fish completion for agentx"),o.push(""),o.push("complete -c agentx -f"),o.push(""),o.push("# top-level commands");for(let t of Zo(e)){let n=ra(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Xe(t)}" -d "${n}"`)}o.push("");for(let t of es(e)){let n=sa(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of Zo(e)){let n=Xe(t);o.push(`# ${n}`);for(let s of es(t)){let i=sa(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of Zo(t)){let i=ra(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Zo(t).map(Xe).join(" ")}" -a "${Xe(s)}" -d "${i}"`);for(let r of es(s)){let a=sa(r,[`__fish_seen_subcommand_from ${Xe(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
658
+ `)}function ra(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function sa(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=ra(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}import{Command as lb}from"commander";import fn from"chalk";import{readFile as db}from"node:fs/promises";var un="anis-marrouchi/agentx",aa=`https://raw.githubusercontent.com/${un}/main/contrib/models.json`,yi=`https://github.com/${un}/issues/new/choose`,cp=`https://github.com/${un}/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc`,ap=8e3,hi={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 ca(e,o){let t=e.trim().toLowerCase();return t?o.models.some(n=>{let s=n.id.toLowerCase();return t===s||t.startsWith(`${s}-`)||(n.aliases??[]).some(i=>i.toLowerCase()===t)}):!1}function la(e,o){return[`The model "${e}" is not on the recommended list for drafting AgentX issues.`,`The list (${o.models.map(t=>t.id).join(", ")}) keeps drafts clear and consistent; it says nothing about you or your idea.`,`Please write the issue yourself with the web form, which is always available: ${yi}`].join(`
659
+ `)}function cb(e){return`---
660
+ _Prepared with \`agentx contribute\` \xB7 model: ${e.model} \xB7 AgentX ${e.version} \xB7 category: ${e.category}_`}function lp(e,o){let t=hi[e.category];if(!t)throw new Error(`Unknown category "${e.category}". Use one of: ${Object.keys(hi).join(", ")}`);let n=new Set(t.fields.map(l=>l.id)),s=Object.keys(e.fields).filter(l=>!n.has(l));if(s.length)throw new Error(`Unknown field(s) for ${e.category}: ${s.join(", ")}. Expected: ${[...n].join(", ")}`);let i=t.fields.filter(l=>l.required&&!e.fields[l.id]?.trim()).map(l=>l.id);if(i.length)throw new Error(`Missing required field(s) for ${e.category}: ${i.join(", ")}`);let r=e.title.trim();if(!r)throw new Error("The issue needs a title");r.toLowerCase().startsWith(t.titlePrefix.toLowerCase())||(r=t.titlePrefix+r);let a=new URLSearchParams({template:t.template,title:r});for(let l of t.fields){let g=e.fields[l.id]?.trim()??"";l.id===t.footerField&&(g=`${g}
661
+
662
+ ${cb({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/${un}/issues/new?${a.toString()}`;if(c.length>ap)throw new Error(`The draft is too long for a pre-filled link (${c.length} characters, limit ${ap}). Shorten it, or paste it into the web form.`);return c}async function dp(e,o=fetch){let t=`repo:${un} is:issue is:open ${e}`,n=await o(`https://api.github.com/search/issues?per_page=10&q=${encodeURIComponent(t)}`,{headers:{accept:"application/vnd.github+json"}});if(!n.ok)throw new Error(`GitHub search failed (HTTP ${n.status}). Search by hand: https://github.com/${un}/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 da(e,o=fetch){let t;if(/^https?:\/\//.test(e)){let s=await o(e,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error(`Could not read the model list (HTTP ${s.status}) from ${e}`);t=await s.text()}else{let{readFile:s}=await import("node:fs/promises");t=await s(e,"utf8")}let n=JSON.parse(t);if(!Array.isArray(n.models))throw new Error(`The model list at ${e} has no "models" array`);return n}var os=new lb().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(fn.bold(" Two equally welcome ways to contribute")),console.log(),console.log(` 1. Write it yourself: ${yi}`),console.log(" 2. Let your agent help: install the skill with"),console.log(fn.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: ${cp}`),console.log(` Categories: ${Object.keys(hi).join(", ")}`),console.log()});os.command("check-model <model>").description("check whether a model is on the recommended list (contrib/models.json)").option("--models <pathOrUrl>","model list to read",aa).action(async(e,o)=>{try{let t=await da(o.models);if(ca(e,t)){console.log(fn.green(` "${e}" is on the recommended list.`));return}console.log(la(e,t)),process.exitCode=1}catch(t){console.error(fn.red(` ${t.message}`)),console.error(` You can always write the issue yourself: ${yi}`),process.exitCode=1}});os.command("search <words...>").description("list open issues that match, most-voted first \u2014 check for duplicates before drafting").action(async e=>{try{let o=await dp(e.join(" "));if(!o.length){console.log(" No open issue matches. It looks new.");return}for(let t of o)console.log(` #${t.number} \u{1F44D} ${t.votes} ${t.title}
663
+ ${t.url}`)}catch(o){console.error(fn.red(` ${o.message}`)),process.exitCode=1}});os.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",aa).action(async(e,o)=>{try{let t=await da(o.models);if(!ca(o.model,t)){console.log(la(o.model,t)),process.exitCode=1;return}let n=e==="-"?await gb():await db(e,"utf8"),s=JSON.parse(n),{version:i}=await cs(),r=lp({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(fn.red(` ${t.message}`)),process.exitCode=1}});async function gb(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function Oj(){let e=await cs(),o=new mb().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=Il(n);Nl(s)&&jl("cli",s)});for(let t of[sd,nd,Zt,_t,Mt,no,Al,st,js,Eo,To,Kt,Yg,zo,Cs,Nm,Jo,Sd,Rd,Mn,Jd,Yd,Xd,eg,og,wg,vg,xg,zt,Bn,Mm,jn,qo,ip,os])o.addCommand(t);for(let t of gp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=gp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,pb(t,74," "),""].join(`
664
+ `)}),o}var gp=[oe,tn,Qo,po,Nn,Yt,Ke,Co,Vo,ut,an,cn,Wo,Ge,Ft,Ys,Cm,jm,xo,it,Ml,rt,Zn,sr,Xo,Yo,qt,ir,ci,bo,jo,zm,Vm,Pm];function pb(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
665
+ `)}export{Oj as buildProgram};
666
+ //# sourceMappingURL=program-FUYHN2F7.js.map