agentix-cli 0.25.0 → 0.27.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.
- package/README.md +2 -0
- package/dist/{App-6Y7B3YQH.js → App-U52IPUK2.js} +2 -2
- package/dist/{ChatApp-KIEUJ2DS.js → ChatApp-XP4OMHPL.js} +2 -2
- package/dist/agent-V2CA4TXD.js +2 -0
- package/dist/article-fields-L4D2BOGY.js +2 -0
- package/dist/article-quality-44ONVGLN.js +3 -0
- package/dist/article-quality-44ONVGLN.js.map +1 -0
- package/dist/{audit-JU3HWISB.js → audit-4245CX6P.js} +2 -2
- package/dist/backfill-MTD2B62I.js +6 -0
- package/dist/backfill-MTD2B62I.js.map +1 -0
- package/dist/{board-dashboard-CQ5F4GPD.js → board-dashboard-TTMAYRLG.js} +2445 -519
- package/dist/board-dashboard-TTMAYRLG.js.map +1 -0
- package/dist/{builtin-FRKAQMFS.js → builtin-B67DMJ3M.js} +2 -2
- package/dist/calibration-ILS5OI44.js +2 -0
- package/dist/chunk-2T5W3ETS.js +5 -0
- package/dist/{chunk-FDMWOPEL.js.map → chunk-2T5W3ETS.js.map} +1 -1
- package/dist/chunk-3SCPRYJB.js +5 -0
- package/dist/chunk-3SCPRYJB.js.map +1 -0
- package/dist/chunk-4BR7D2OU.js +36 -0
- package/dist/chunk-4BR7D2OU.js.map +1 -0
- package/dist/{chunk-P4VWIVKN.js → chunk-52ZPELD2.js} +403 -29
- package/dist/chunk-52ZPELD2.js.map +1 -0
- package/dist/{chunk-5U35WAZF.js → chunk-77OV7346.js} +6 -6
- package/dist/chunk-77OV7346.js.map +1 -0
- package/dist/chunk-AJ5RMU7X.js +2 -0
- package/dist/chunk-AJ5RMU7X.js.map +1 -0
- package/dist/chunk-AJONZWLT.js +2 -0
- package/dist/chunk-AJONZWLT.js.map +1 -0
- package/dist/chunk-AX2PWSRT.js +114 -0
- package/dist/chunk-AX2PWSRT.js.map +1 -0
- package/dist/chunk-BH3GTCZ6.js +2 -0
- package/dist/chunk-BH3GTCZ6.js.map +1 -0
- package/dist/chunk-BPIRO4YD.js +126 -0
- package/dist/chunk-BPIRO4YD.js.map +1 -0
- package/dist/chunk-CJQQIRPD.js +13 -0
- package/dist/chunk-CJQQIRPD.js.map +1 -0
- package/dist/chunk-DCDQZR7I.js +24 -0
- package/dist/chunk-DCDQZR7I.js.map +1 -0
- package/dist/chunk-EVWEG3VD.js +3 -0
- package/dist/chunk-EVWEG3VD.js.map +1 -0
- package/dist/chunk-F4HZTZHW.js +2 -0
- package/dist/chunk-F4HZTZHW.js.map +1 -0
- package/dist/chunk-F6CNF7V3.js +25 -0
- package/dist/chunk-F6CNF7V3.js.map +1 -0
- package/dist/chunk-FIEJDZVC.js +121 -0
- package/dist/chunk-FIEJDZVC.js.map +1 -0
- package/dist/chunk-FIOB3MEX.js +2 -0
- package/dist/{chunk-H5D7ATXS.js → chunk-FKBGJYWQ.js} +5 -5
- package/dist/chunk-FKBGJYWQ.js.map +1 -0
- package/dist/chunk-GDWJUGB5.js +9 -0
- package/dist/chunk-GDWJUGB5.js.map +1 -0
- package/dist/{chunk-TRJTTBE2.js → chunk-IB3F7VBE.js} +7 -7
- package/dist/{chunk-TRJTTBE2.js.map → chunk-IB3F7VBE.js.map} +1 -1
- package/dist/chunk-IBUSGCLQ.js +109 -0
- package/dist/chunk-IBUSGCLQ.js.map +1 -0
- package/dist/{chunk-LDHPMJ7M.js → chunk-IWMW5432.js} +3 -3
- package/dist/chunk-IWMW5432.js.map +1 -0
- package/dist/chunk-K33GIBSE.js +2 -0
- package/dist/chunk-K33GIBSE.js.map +1 -0
- package/dist/chunk-L2IZPR6P.js +45 -0
- package/dist/chunk-L2IZPR6P.js.map +1 -0
- package/dist/chunk-L2WSPY6S.js +2 -0
- package/dist/chunk-L2WSPY6S.js.map +1 -0
- package/dist/chunk-LCIREYTD.js +54 -0
- package/dist/chunk-LCIREYTD.js.map +1 -0
- package/dist/chunk-LNRB5MCU.js +530 -0
- package/dist/chunk-LNRB5MCU.js.map +1 -0
- package/dist/chunk-OPHIXXGI.js +157 -0
- package/dist/chunk-OPHIXXGI.js.map +1 -0
- package/dist/{chunk-JTJIPNXY.js → chunk-PNWNVOEZ.js} +1 -1
- package/dist/chunk-PNWNVOEZ.js.map +1 -0
- package/dist/{chunk-LNXCJWOU.js → chunk-UFAGYX73.js} +45 -47
- package/dist/chunk-UFAGYX73.js.map +1 -0
- package/dist/{chunk-DJEZ2HVU.js → chunk-VDMYBPYB.js} +1 -1
- package/dist/chunk-VDMYBPYB.js.map +1 -0
- package/dist/chunk-VTE7L6LO.js +5 -0
- package/dist/{chunk-G57RZCXM.js.map → chunk-VTE7L6LO.js.map} +1 -1
- package/dist/chunk-W5C2GDNC.js +32 -0
- package/dist/{chunk-JP5IEXR7.js.map → chunk-W5C2GDNC.js.map} +1 -1
- package/dist/chunk-WPMX3VGI.js +3 -0
- package/dist/chunk-WPMX3VGI.js.map +1 -0
- package/dist/chunk-WZ72HX5C.js +1182 -0
- package/dist/chunk-WZ72HX5C.js.map +1 -0
- package/dist/chunk-ZTEU5JVQ.js +2 -0
- package/dist/chunk-ZTEU5JVQ.js.map +1 -0
- package/dist/{chunk-2WVX3LEC.js → chunk-ZVP6GB4G.js} +1 -1
- package/dist/chunk-ZVP6GB4G.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-PX25MD47.js +2 -0
- package/dist/{compaction-NWEMOSHA.js → compaction-FD4R23HZ.js} +4 -4
- package/dist/config-HL5F36V4.js +2 -0
- package/dist/config-mutator-HBX53OMJ.js +2 -0
- package/dist/{conflict-detector-D7VIYPDI.js → conflict-detector-ZPOT3M2C.js} +2 -2
- package/dist/conflict-detector-ZPOT3M2C.js.map +1 -0
- package/dist/context-planner-AQHJMVY2.js +17 -0
- package/dist/context-planner-AQHJMVY2.js.map +1 -0
- package/dist/debug-3MEUO2P2.js +2 -0
- package/dist/{discover-XJXQXXIO.js → discover-D4VVRNAI.js} +2 -2
- package/dist/discover-D4VVRNAI.js.map +1 -0
- package/dist/doctor-PBAH6XL3.js +2 -0
- package/dist/editor-chat-OB7IQOB5.js +137 -0
- package/dist/editor-chat-OB7IQOB5.js.map +1 -0
- package/dist/entry-triage-LK34TSQD.js +2 -0
- package/dist/entry-triage-LK34TSQD.js.map +1 -0
- package/dist/facts-YVEJOM7O.js +22 -0
- package/dist/facts-YVEJOM7O.js.map +1 -0
- package/dist/heal-FVLBHYP7.js +2 -0
- package/dist/index.d.ts +1073 -65
- package/dist/index.js +13 -13
- package/dist/index.js.map +1 -1
- package/dist/{ingest-whatsapp-LZE62INA.js → ingest-whatsapp-NS4OWDOU.js} +2 -2
- package/dist/loader-4ZGTK7LD.js +2 -0
- package/dist/loader-BOKE5M5S.js +2 -0
- package/dist/memory-extract-F5ZHWY5E.js +2 -0
- package/dist/{migrate-v2-QO7SLKIM.js → migrate-v2-V4WN2VVM.js} +2 -2
- package/dist/ntfy-X7EPB3TG.js +4 -0
- package/dist/ntfy-X7EPB3TG.js.map +1 -0
- package/dist/processes-WU23U2OJ.js +2 -0
- package/dist/program-YGXVCV2Y.js +2 -0
- package/dist/{projects-api-KRME2YKZ.js → projects-api-QE6L65SK.js} +2 -2
- package/dist/{projects-mutate-3NHVG437.js → projects-mutate-MY7JTLSZ.js} +2 -2
- package/dist/providers-KO2DODIO.js +2 -0
- package/dist/query-ZKTFJMNE.js +2 -0
- package/dist/questions-4B4KSPXG.js +3 -0
- package/dist/questions-4B4KSPXG.js.map +1 -0
- package/dist/recipes-7S4MC5OJ.js +2 -0
- package/dist/registry-PSZDPFZK.js +2 -0
- package/dist/review-candidates-AEUXRQQC.js +4 -0
- package/dist/review-candidates-AEUXRQQC.js.map +1 -0
- package/dist/review-store-B4YE3EFK.js +4 -0
- package/dist/review-store-B4YE3EFK.js.map +1 -0
- package/dist/{rotation-memo-B3EXXSEH.js → rotation-memo-7T75BLEX.js} +2 -2
- package/dist/routing-4PV66BK6.js +2 -0
- package/dist/routing-4PV66BK6.js.map +1 -0
- package/dist/runner-YRBVNYTY.js +2 -0
- package/dist/scheduler-GZZAN6ZG.js +2 -0
- package/dist/seat-VZ7AVO27.js +2 -0
- package/dist/select-F5I5PO2O.js +2 -0
- package/dist/select-F5I5PO2O.js.map +1 -0
- package/dist/store-MCOA6N4F.js +2 -0
- package/dist/{subagent-WV7QKQ3L.js → subagent-2SJHSSJS.js} +2 -2
- package/dist/{surface-usage-PRL6Z4U3.js → surface-usage-NS74AXSE.js} +2 -2
- package/dist/timers-PCB4ZIBD.js +2 -0
- package/dist/triage-backtest-JNO7RKX7.js +2 -0
- package/dist/triage-backtest-JNO7RKX7.js.map +1 -0
- package/dist/types-H5ENIUIT.js +2 -0
- package/dist/types-OIFU3KSQ.js +2 -0
- package/dist/web/workflow-editor.global.js +1542 -0
- package/dist/web/workflow-editor.global.js.map +1 -0
- package/dist/{whatsapp-state-XMTCSRXU.js → whatsapp-state-6D6FHHD2.js} +2 -2
- package/dist/wiki-N5SMP3DT.js +2 -0
- package/dist/wiki-N5SMP3DT.js.map +1 -0
- package/dist/workflows/templates/branching.yaml +1 -1
- package/dist/{workspace-setup-TBQAHYHJ.js → workspace-setup-B3F3TUDE.js} +2 -2
- package/dist/workspace-setup-B3F3TUDE.js.map +1 -0
- package/package.json +1 -1
- package/dist/agent-QGZIAZMY.js +0 -2
- package/dist/architect-SEPWMWS4.js +0 -2
- package/dist/board-dashboard-CQ5F4GPD.js.map +0 -1
- package/dist/chunk-2WVX3LEC.js.map +0 -1
- package/dist/chunk-3WQFCIB6.js +0 -24
- package/dist/chunk-3WQFCIB6.js.map +0 -1
- package/dist/chunk-4YCH6IZV.js +0 -2
- package/dist/chunk-53GCFZPR.js +0 -116
- package/dist/chunk-53GCFZPR.js.map +0 -1
- package/dist/chunk-53NRX2NA.js +0 -2
- package/dist/chunk-53NRX2NA.js.map +0 -1
- package/dist/chunk-5U35WAZF.js.map +0 -1
- package/dist/chunk-BFXONUUN.js +0 -108
- package/dist/chunk-BFXONUUN.js.map +0 -1
- package/dist/chunk-BFZUG66X.js +0 -45
- package/dist/chunk-BFZUG66X.js.map +0 -1
- package/dist/chunk-DJEZ2HVU.js.map +0 -1
- package/dist/chunk-FDMWOPEL.js +0 -5
- package/dist/chunk-FDWOECJY.js +0 -54
- package/dist/chunk-FDWOECJY.js.map +0 -1
- package/dist/chunk-G57RZCXM.js +0 -5
- package/dist/chunk-H5D7ATXS.js.map +0 -1
- package/dist/chunk-HA3XI7Z2.js +0 -155
- package/dist/chunk-HA3XI7Z2.js.map +0 -1
- package/dist/chunk-HR4JSRZS.js +0 -3
- package/dist/chunk-HR4JSRZS.js.map +0 -1
- package/dist/chunk-ISEBLHWX.js +0 -118
- package/dist/chunk-ISEBLHWX.js.map +0 -1
- package/dist/chunk-JP5IEXR7.js +0 -32
- package/dist/chunk-JTJIPNXY.js.map +0 -1
- package/dist/chunk-JXWAGMI2.js +0 -13
- package/dist/chunk-JXWAGMI2.js.map +0 -1
- package/dist/chunk-KUCCW2VG.js +0 -431
- package/dist/chunk-KUCCW2VG.js.map +0 -1
- package/dist/chunk-LDHPMJ7M.js.map +0 -1
- package/dist/chunk-LNXCJWOU.js.map +0 -1
- package/dist/chunk-NGSIRE4X.js +0 -126
- package/dist/chunk-NGSIRE4X.js.map +0 -1
- package/dist/chunk-P4VWIVKN.js.map +0 -1
- package/dist/chunk-Q6YO7LYE.js +0 -47
- package/dist/chunk-Q6YO7LYE.js.map +0 -1
- package/dist/chunk-SR3X25TN.js +0 -3
- package/dist/chunk-SR3X25TN.js.map +0 -1
- package/dist/chunk-TMKLHTCG.js +0 -971
- package/dist/chunk-TMKLHTCG.js.map +0 -1
- package/dist/chunk-VJUTQAPJ.js +0 -2
- package/dist/chunk-VJUTQAPJ.js.map +0 -1
- package/dist/client-GGVVLOOF.js +0 -2
- package/dist/config-7FSZFRTQ.js +0 -2
- package/dist/config-mutator-POCOYYJ4.js +0 -2
- package/dist/conflict-detector-D7VIYPDI.js.map +0 -1
- package/dist/context-planner-45GEWKGL.js +0 -17
- package/dist/context-planner-45GEWKGL.js.map +0 -1
- package/dist/debug-N3B5NVJU.js +0 -2
- package/dist/discover-XJXQXXIO.js.map +0 -1
- package/dist/doctor-DHLBEKA4.js +0 -2
- package/dist/heal-HZ3EQD52.js +0 -2
- package/dist/loader-5CA3O5GM.js +0 -2
- package/dist/loader-6IHUCPVO.js +0 -2
- package/dist/memory-extract-AENFVVO5.js +0 -2
- package/dist/processes-UIC4XXA6.js +0 -2
- package/dist/program-WVAVJFND.js +0 -2
- package/dist/providers-L27BJ5A6.js +0 -2
- package/dist/query-HZYYRCLU.js +0 -2
- package/dist/recipes-EPLE2SNT.js +0 -2
- package/dist/registry-T36ZIAWV.js +0 -2
- package/dist/runner-BFYDWPUO.js +0 -2
- package/dist/scheduler-GH7TIKYS.js +0 -2
- package/dist/store-I3HEWVLQ.js +0 -2
- package/dist/timers-5LPZN55J.js +0 -2
- package/dist/types-VECTMYTO.js +0 -2
- package/dist/types-Y6ZCZ52Z.js +0 -2
- package/dist/wiki-M6YNRFC4.js +0 -2
- /package/dist/{App-6Y7B3YQH.js.map → App-U52IPUK2.js.map} +0 -0
- /package/dist/{ChatApp-KIEUJ2DS.js.map → ChatApp-XP4OMHPL.js.map} +0 -0
- /package/dist/{agent-QGZIAZMY.js.map → agent-V2CA4TXD.js.map} +0 -0
- /package/dist/{architect-SEPWMWS4.js.map → article-fields-L4D2BOGY.js.map} +0 -0
- /package/dist/{audit-JU3HWISB.js.map → audit-4245CX6P.js.map} +0 -0
- /package/dist/{builtin-FRKAQMFS.js.map → builtin-B67DMJ3M.js.map} +0 -0
- /package/dist/{chunk-4YCH6IZV.js.map → calibration-ILS5OI44.js.map} +0 -0
- /package/dist/{client-GGVVLOOF.js.map → chunk-FIOB3MEX.js.map} +0 -0
- /package/dist/{config-7FSZFRTQ.js.map → client-PX25MD47.js.map} +0 -0
- /package/dist/{compaction-NWEMOSHA.js.map → compaction-FD4R23HZ.js.map} +0 -0
- /package/dist/{config-mutator-POCOYYJ4.js.map → config-HL5F36V4.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → config-mutator-HBX53OMJ.js.map} +0 -0
- /package/dist/{doctor-DHLBEKA4.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{heal-HZ3EQD52.js.map → doctor-PBAH6XL3.js.map} +0 -0
- /package/dist/{loader-5CA3O5GM.js.map → heal-FVLBHYP7.js.map} +0 -0
- /package/dist/{ingest-whatsapp-LZE62INA.js.map → ingest-whatsapp-NS4OWDOU.js.map} +0 -0
- /package/dist/{loader-6IHUCPVO.js.map → loader-4ZGTK7LD.js.map} +0 -0
- /package/dist/{memory-extract-AENFVVO5.js.map → loader-BOKE5M5S.js.map} +0 -0
- /package/dist/{processes-UIC4XXA6.js.map → memory-extract-F5ZHWY5E.js.map} +0 -0
- /package/dist/{migrate-v2-QO7SLKIM.js.map → migrate-v2-V4WN2VVM.js.map} +0 -0
- /package/dist/{program-WVAVJFND.js.map → processes-WU23U2OJ.js.map} +0 -0
- /package/dist/{providers-L27BJ5A6.js.map → program-YGXVCV2Y.js.map} +0 -0
- /package/dist/{projects-api-KRME2YKZ.js.map → projects-api-QE6L65SK.js.map} +0 -0
- /package/dist/{projects-mutate-3NHVG437.js.map → projects-mutate-MY7JTLSZ.js.map} +0 -0
- /package/dist/{query-HZYYRCLU.js.map → providers-KO2DODIO.js.map} +0 -0
- /package/dist/{recipes-EPLE2SNT.js.map → query-ZKTFJMNE.js.map} +0 -0
- /package/dist/{registry-T36ZIAWV.js.map → recipes-7S4MC5OJ.js.map} +0 -0
- /package/dist/{runner-BFYDWPUO.js.map → registry-PSZDPFZK.js.map} +0 -0
- /package/dist/{rotation-memo-B3EXXSEH.js.map → rotation-memo-7T75BLEX.js.map} +0 -0
- /package/dist/{scheduler-GH7TIKYS.js.map → runner-YRBVNYTY.js.map} +0 -0
- /package/dist/{store-I3HEWVLQ.js.map → scheduler-GZZAN6ZG.js.map} +0 -0
- /package/dist/{surface-usage-PRL6Z4U3.js.map → seat-VZ7AVO27.js.map} +0 -0
- /package/dist/{timers-5LPZN55J.js.map → store-MCOA6N4F.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
- /package/dist/{types-VECTMYTO.js.map → surface-usage-NS74AXSE.js.map} +0 -0
- /package/dist/{types-Y6ZCZ52Z.js.map → timers-PCB4ZIBD.js.map} +0 -0
- /package/dist/{wiki-M6YNRFC4.js.map → types-H5ENIUIT.js.map} +0 -0
- /package/dist/{workspace-setup-TBQAHYHJ.js.map → types-OIFU3KSQ.js.map} +0 -0
- /package/dist/{whatsapp-state-XMTCSRXU.js.map → whatsapp-state-6D6FHHD2.js.map} +0 -0
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
import{a as or,b as Vt,g as tr}from"./chunk-VTE7L6LO.js";import{a as Vo,b as Ki,f as Kt,j as er}from"./chunk-UFAGYX73.js";import{a as Qi,c as Xi,d as Zi}from"./chunk-UCQ2N3KO.js";import{b as Vi}from"./chunk-IB3F7VBE.js";import{a as Ko}from"./chunk-GV7S5BAX.js";import{e as fi}from"./chunk-GSX4NK2N.js";import{c as hi}from"./chunk-SZDACK6O.js";import{A as Yn,B as Gi,C as Yi,a as Si,g as Oi,h as ji,i as bt,j as Yt,k as Ri,l as Ci,m as Ti,n as Ni,o as _i,p as Di,q as Pi,r as Mi,s as Li,t as Ui,u as Fi,v as qi,w as Wi,x as Bi,y as zi,z as Gn}from"./chunk-WZ72HX5C.js";import{i as Ji,j as Hn,k as Hi,l as zn}from"./chunk-F6CNF7V3.js";import{a as Ei,d as Ai,e as Ii}from"./chunk-DCDQZR7I.js";import{i as gi,k as zo,m as Wn,n as pi,p as lo,v as xi}from"./chunk-OPHIXXGI.js";import{b as Go,c as zt,d as Gt,e as Yo,f as ui,g as Eo,h as wt}from"./chunk-GDWJUGB5.js";import{a as $i}from"./chunk-M4AMWP3H.js";import{d as Jn,f as ki}from"./chunk-4BR7D2OU.js";import{f as yi,g as wi,h as Bn}from"./chunk-76Z4VHDX.js";import{a as mi,e as bi}from"./chunk-FIEJDZVC.js";import{a as ne,b as ce,c as Ao,d as vi}from"./chunk-2T5W3ETS.js";import{b as co,d as Ht,f as qn}from"./chunk-IBUSGCLQ.js";import{b as Ho,c as di}from"./chunk-EVWEG3VD.js";import{a as Fn,b as Xs,c as pc,d as Bt,e as Zs,f as si,g as fc,h as ii,i as hc,m as Jo,n as ai,o as ci,s as li,v as Ge,w as yt}from"./chunk-AX2PWSRT.js";import{a as ri,b as yc}from"./chunk-AJONZWLT.js";import{a as to,b as Bo,e as oi,f as ht}from"./chunk-F4HZTZHW.js";import{a as oo,b as mc}from"./chunk-L2WSPY6S.js";import{f as ei,g as H,h as Jt,j as Te}from"./chunk-CJQQIRPD.js";import{g as ti,k as ni,l as uc}from"./chunk-BH3GTCZ6.js";import{a as gc}from"./chunk-FIOB3MEX.js";import{Command as xc}from"commander";import{open as Sc}from"fs/promises";import{existsSync as Zt,mkdirSync as wc,readFileSync as en,writeFileSync as nr}from"fs";import{homedir as bc}from"os";import{dirname as $c,resolve as Kn}from"path";var Vn="/attach/",sr="/guard/check";function ir(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 Qt(e,o,t){let n={hooks:[{type:"command",command:ir(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function kc(e){return{SessionStart:[Qt("/attach/session-start",e,"")],UserPromptSubmit:[Qt("/attach/prompt",e)],Stop:[Qt("/attach/stop",e)],SessionEnd:[Qt("/attach/session-end",e)]}}function vc(e){let o=ir("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function Xt(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function $t(){return Kn(bc(),".claude/settings.json")}function kt(e=process.cwd()){for(let o of[e,Kn(e,"..")]){let t=Kn(o,"agentx.json");if(Zt(t))try{let n=JSON.parse(en(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function rr(e,o={}){let t=o.path??$t(),n=o.withGuard!==!1,s={};if(Zt(t))try{s=JSON.parse(en(t,"utf-8"))}catch(d){throw new Error(`${t} is not valid JSON (${d?.message}) \u2014 refusing to overwrite it`)}let i=JSON.stringify(s),r=s.hooks??={},a=[];for(let[d,g]of Object.entries(kc(e))){let u=Array.isArray(r[d])?r[d].filter(p=>!Xt(p,Vn)):[];r[d]=[...u,...g],a.push(d)}let c=!1;if(n){let d=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(g=>!Xt(g,sr)):[];r.PreToolUse=[...d,...vc(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(wc($c(t),{recursive:!0}),nr(t,`${JSON.stringify(s,null,2)}
|
|
2
|
+
`)),{path:t,changed:l,events:a,guardInstalled:c}}function ar(e={}){let o=e.path??$t();if(!Zt(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(en(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"?sr:Vn;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(d=>!Xt(d,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&&nr(o,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`),{path:o,changed:r,events:i,guardInstalled:!1}}function on(e=$t()){if(!Zt(e))return!1;try{return!!JSON.parse(en(e,"utf-8"))?.hooks?.Stop?.some?.(t=>Xt(t,Vn))}catch{return!1}}var tn=new xc("monitor").description("Register external CLI sessions and report ended runs to the briefing"),cr=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${kt()}`;async function lr(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)}`)}tn.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",cr).action(async e=>{try{await lr(e.url,"register",Ai.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}});tn.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",cr).action(async e=>{try{let o=await Sc(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]
|
|
4
|
+
`:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await lr(e.url,"ended",Ii.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 yp}from"commander";import{Command as Ec}from"commander";Te();import I from"chalk";import{existsSync as Ac,readFileSync as Ic}from"fs";async function Oc(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 Ye=new Ec().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ye.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:d,writeFileSync:g,existsSync:u}=await import("fs"),p=process.argv[1];(!p||!u(p))&&(console.error(I.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${p||"?"}).`)),console.error(I.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let f=[p,"daemon","start"];e.config&&f.push("-c",e.config),e.port&&f.push("--port",e.port);let w="/tmp/agentx-daemon.log",y;try{y=d(w,"a")}catch(b){console.error(I.red(` Failed to open ${w} for writing: ${b.message}`)),process.exit(1)}let k=l(process.execPath,f,{detached:!0,stdio:["ignore",y,y],cwd:process.cwd()});k.unref(),g("/tmp/agentx-daemon.pid",String(k.pid)),console.log(I.green(`Daemon started in background (PID: ${k.pid})`)),console.log(I.dim(` Logs: tail -f ${w}`)),console.log(I.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(I.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(I.dim(` tail -n 40 ${w}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(o(a,"utf-8").trim(),10);if(l&&l!==process.pid){let d=!1;try{process.kill(l,0),d=!0}catch{}d&&await Oc(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{jc(i(process.cwd(),".env"))}catch{}await new Yn(e.config).start()});function jc(e){if(!Ac(e))return;let o=Ic(e,"utf-8");for(let t of o.split(`
|
|
5
|
+
`)){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}}Ye.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);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(I.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(I.green("Daemon stopped"))}catch{console.log(I.yellow("No daemon process found"))}});Ye.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=H(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(I.bold(` ${r.node.name}`)+I.dim(` (${r.node.id})`)),console.log(I.green(" Status: running")+I.dim(` \u2014 uptime ${Rc(r.uptime)}`)),console.log(),console.log(I.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?I.yellow(` [${c.active} active]`):"",d=c.errors>0?I.red(` (${c.errors} errors)`):"";console.log(` ${I.cyan(c.name)} ${I.dim(`(${c.tier})`)}${l}${d}`),console.log(I.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(I.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?I.green("\u25CF"):I.dim("\u25CB"),d=c.nextRun?I.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${d}`)}}if(r.mesh?.length){console.log(),console.log(I.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?I.green("\u25CF"):I.red("\u25CF"),d=c.skills?.length?I.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${I.dim(c.peerUrl)}${d}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(I.red(" Daemon is not running")),console.log(I.dim(" Start with: agentx daemon start"));else try{let t=H(e.config),n=Jt(t);if(console.log(),console.log(I.bold(` ${t.node.name}`)+I.dim(` (${t.node.id})`)),console.log(I.yellow(" Status: stopped")),console.log(I.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(I.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(I.red(` ${t.message}`))}}});Ye.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(I.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"})});Ye.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(H(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(I.dim(` Connecting to ${n}...`)),console.log(I.dim(` Press Ctrl+C to stop
|
|
6
|
+
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(I.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 d=a.split(`
|
|
7
|
+
`);a=d.pop()||"";for(let g of d)if(g.startsWith("data: "))try{let u=JSON.parse(g.slice(6)),p=new Date(u.time).toLocaleTimeString(),f=u.message?.replace(/^\[agentx\]\s*/,"")||"";f.includes("executing")?console.log(`${I.dim(p)} ${I.cyan("\u25B6")} ${f}`):f.includes("completed")?console.log(`${I.dim(p)} ${I.green("\u2713")} ${f}`):f.includes("error")||f.includes("Error")?console.log(`${I.dim(p)} ${I.red("\u2717")} ${f}`):f.includes("Routing")?console.log(`${I.dim(p)} ${I.yellow("\u2192")} ${f}`):f.includes("mention")?console.log(`${I.dim(p)} ${I.magenta("@")} ${f}`):f.includes("Skipping")?console.log(`${I.dim(p)} ${I.dim("\u2298")} ${I.dim(f)}`):console.log(`${I.dim(p)} ${f}`)}catch{}else g.startsWith("event: status")}}catch(s){console.log(I.red(` Connection failed: ${s.message}`)),console.log(I.dim(" Is the daemon running? Diagnostic order:")),console.log(I.dim(" 1) agentx daemon status # is the daemon up?")),console.log(I.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(I.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(I.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(I.dim(" to see the error in the foreground."))}});Ye.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=H(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(I.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let g=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();t.json?console.log(JSON.stringify(g,null,2)):g.error?console.log(I.red(` Error: ${g.error}`)):(console.log(),console.log(g.content||g.response||"No response"),g.duration&&console.log(I.dim(`
|
|
8
|
+
(${(g.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(I.red(` Failed: ${s.message}`)),console.log(I.dim(" Is the daemon running? Try: agentx daemon status"))}});Ye.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(I.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(I.green(" \u2713 Tests passed"))}catch{console.log(I.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(I.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(I.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(I.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(I.green(" \u2713 Build complete")))}console.log(I.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(I.green(" \u2713 Deploy complete")),o.restart){console.log(I.dim(" Restarting remote daemon..."));let i=o.identity?`ssh -i ${o.identity}`:"ssh";t(`${i} ${o.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${o.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(I.green(" Remote daemon restarted"))}}catch(i){console.log(I.red(` Deploy failed: ${i.message}`))}});Ye.action(async e=>{await new Yn(e.config).start()});function Rc(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`}import{Command as Cc}from"commander";import We from"chalk";import{existsSync as vt,readFileSync as Tc,writeFileSync as dr,mkdirSync as gr}from"fs";import{hostname as mr}from"os";import{resolve as Qo}from"path";var pr=new Cc().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Qo(o,"agentx.json"),n=Qo(o,".env"),s=Qo(o,".agentx/sessions");if(console.log(),console.log(We.bold(" agentx init")),console.log(),vt(t)&&!e.force){console.log(We.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Qo(o,"agentx.example.json"),Qo(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(vt(c)){r=Tc(c,"utf-8");break}r||(r=JSON.stringify({node:{id:mr().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:mr(),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)),dr(t,r),console.log(We.green(" \u2713 Created agentx.json")),vt(n)||(dr(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
9
|
+
`)),console.log(We.green(" \u2713 Created .env template"))),vt(s)||(gr(s,{recursive:!0}),console.log(We.green(" \u2713 Created .agentx/sessions/")));let a=Qo(o,".claude");vt(a)||(gr(a,{recursive:!0}),console.log(We.green(" \u2713 Created .claude/"))),console.log(),console.log(We.bold(" Next steps:")),console.log(` 1. Edit ${We.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${We.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${We.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${We.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Nc}from"commander";import Io from"chalk";import{spawn as fr}from"child_process";import{existsSync as _c}from"fs";import{dirname as Dc,resolve as Pc}from"path";import{fileURLToPath as Mc}from"url";Te();var hr=new Nc().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=Ki(),t=e.port?parseInt(e.port,10):Lc(),n=`http://127.0.0.1:${t}/setup`;if(console.log(),o.configExists?console.log(Io.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Io.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Io.bold(` Opening ${n}`)),console.log(),await Fc(n).catch(()=>!1))console.log(Io.dim(" Dashboard is already running.")),e.open!==!1&&ur(n);else{console.log(Io.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=Uc(),r=fr(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&ur(n),await new Promise(a=>r.on("exit",()=>a()))}});function Lc(){try{return H().dashboard.port||4202}catch{return 4202}}function Uc(){let e=Pc(Dc(Mc(import.meta.url)),"cli.js");return _c(e)?e:process.argv[1]||e}async function Fc(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function ur(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=fr(o,[e],{stdio:"ignore",detached:!0});t.once("error",()=>{console.log(Io.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),t.unref()}catch{console.log(Io.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as qc}from"commander";import xe from"chalk";var xt=new qc().name("token").description("scoped API tokens for external access (mesh peers, integrations)");xt.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 Kt,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(xe.bold(" Token created.")),console.log(),console.log(` id: ${xe.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||xe.dim("never")}`),console.log(),console.log(xe.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${xe.green.bold(s)}`),console.log(),console.log(xe.dim(" Use it via the Authorization header:")),console.log(xe.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});xt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Kt().list();if(e.length===0){console.log(xe.dim(`
|
|
10
|
+
No tokens issued.
|
|
11
|
+
`));return}console.log();for(let o of e){let t=o.revokedAt?xe.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?xe.red("expired"):xe.green("active");console.log(` ${xe.cyan(o.id)} ${t} ${o.name}`),console.log(xe.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(xe.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});xt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new Kt().revoke(e);o||(console.log(xe.red(` Token ${e} not found.`)),process.exit(1)),console.log(xe.green(`
|
|
12
|
+
\u2713 Revoked ${e} (${o.name})
|
|
13
|
+
`))}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Te();import{Command as Ve}from"commander";import h from"chalk";import Se from"prompts";import{readFileSync as mo,writeFileSync as Xo,existsSync as me,mkdirSync as Ke,cpSync as Qn,readdirSync as Zn}from"fs";import{resolve as B,join as go,dirname as Wc}from"path";import{fileURLToPath as Bc}from"url";function se(){let e=B(process.cwd(),"agentx.json");if(!me(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(mo(e,"utf-8"))}function Ie(e){return ne(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var Oo=new Ve().name("agent").description("manage agents \u2014 add, list, remove");Oo.command("list").alias("ls").description("list configured agents").action(()=>{let e=se();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});Oo.command("add").description("add a new agent interactively").action(async()=>{let e=se(),o=await Se([{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:B(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:go(o.workspace,o.id);Ke(B(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-B3F3TUDE.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=B(process.cwd(),"src/wiki/SKILL.md"),a=B(Wc(Bc(import.meta.url)),"../wiki/SKILL.md"),c=me(r)?r:a;me(c)&&(Ke(B(t,".claude/skills/wiki"),{recursive:!0}),Qn(c,B(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Ie(e),console.log(h.green(`
|
|
14
|
+
Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});Oo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=se();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Ie(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Oo.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=se(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Ie(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var St=new Ve().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");St.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=se().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
|
|
15
|
+
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
16
|
+
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[d,g]of Object.entries(c))typeof g=="string"&&/^[A-Z][A-Z0-9_]*$/.test(g)?a.push(process.env[g]?h.green(`${d}:${g}=set`):h.yellow(`${d}:${g}=UNSET`)):d==="auth"&&g==="keyring"?a.push(h.dim("auth:keyring")):d==="sessionDir"&&typeof g=="string"&&a.push(h.dim(`sessionDir:${g}`));let l=Object.entries(i.metadata??{}).map(([d,g])=>`${d}=${g}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});St.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=se();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-HL5F36V4.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Se({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Se({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Se({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 Se({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 Se({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let d={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[p,...f]=u.split("=");p&&(d[p.trim()]=f.join("=").trim())}else if(n){let u=await Se({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let p of String(u.metadata).split(",")){let[f,...w]=p.split("=");f&&(d[f.trim()]=w.join("=").trim())}}let g={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),g.tokenEnv=a),c==="keyring"&&(g.auth="keyring"),l&&(g.sessionDir=l),Object.keys(g).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:g,metadata:d,enabled:!0}),await Ie(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});St.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=se(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Ie(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});St.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=se().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},l=[];for(let[d,g]of Object.entries(c))typeof g=="string"&&/^[A-Z][A-Z0-9_]*$/.test(g)&&!process.env[g]&&l.push(`${d}: env var ${g} is unset`);if(l.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let d of l)console.log(` ${h.dim(d)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});Oo.addCommand(St);var nn=new Ve().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");nn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=se();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[i,r]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let i of t.routes||[]){let r=i.contact?`contact ${i.contact}`:`group "${i.group}"`;console.log(` ${r} -> agent: ${i.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.discord;n?.enabled?(console.log(h.bold(" Discord:")),console.log(` agent: ${n.agentBinding||"(none)"}`)):console.log(h.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let i of s.routes||[])console.log(` ${i.project} -> agent: ${i.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});nn.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=se(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Se({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:"Discord \u2014 bot via Discord developer portal",value:"discord"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Se([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await Ie(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Se([{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 Se([{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 Ie(e),Ke(B(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="discord"){let s=await Se([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.token)return;e.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await Ie(e),console.log(h.green(` Discord added -> ${s.agentBinding}`))}if(n==="gitlab"){let s=await Se([{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 Se([{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 Ie(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Zo=new Ve().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Zo.command("list").alias("ls").description("list cron jobs").action(()=>{let e=se();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Zo.command("add").description("add a cron job").action(async()=>{let e=se(),o=Object.keys(e.agents||{}),t=await Se([{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 Ie(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Zo.command("enable <id>").description("enable a cron job").action(async e=>{let o=se();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await Ie(o),console.log(h.green(` Cron "${e}" enabled`))});Zo.command("disable <id>").description("disable a cron job").action(async e=>{let o=se();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Ie(o),console.log(h.green(` Cron "${e}" disabled`))});var et=new Ve().name("mesh").description("manage mesh peers \u2014 add, list, remove");et.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=se();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});et.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=se(),o=await Se([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Ie(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});et.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=se();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Ie(o),console.log(h.green(` Peer "${e}" removed`)))});et.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=se();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Ie(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var jo=new Ve().name("skill").description("manage skills \u2014 add to agent(s), list");jo.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=se(),n=B(e);if(!me(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=me(go(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 Se({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=B(a.workspace,".claude/skills",s);Ke(c,{recursive:!0}),me(go(n,"SKILL.md"))?Qn(n,c,{recursive:!0}):n.endsWith(".md")&&Qn(n,go(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});jo.command("list").alias("ls").description("list skills per agent").action(()=>{let e=se();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=B(t.workspace,".claude/skills"),s=me(n)?Zn(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});jo.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]:[B(n,"src",e,"SKILL.md"),B(n,"skills",e,"SKILL.md")],i=s.find(k=>me(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=mo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=H()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let d=Object.entries(l.agents||{}),g=o.agent?d.filter(([k])=>k===o.agent):d;if(g.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,p=0,f=0,w=0;for(let[k,b]of g){let x=b.workspace;if(!x||!me(x)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(x||"undefined")+")")}`),w++;continue}let A=B(x,".claude/skills",e),v=B(A,"SKILL.md");if(!me(v)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}o.dryRun||(Ke(A,{recursive:!0}),Xo(v,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let E=mo(v,"utf-8");if(t("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),f++;continue}let T=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Xo(v,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${T} \u2192 v${c}`)}`),p++}console.log();let y=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${y} seed ${u}, ${y} update ${p}, ${f} already current, ${w} skipped.`)),o.dryRun&&(u>0||p>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});jo.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-BOKE5M5S.js"),{auditAll:t}=await import("./audit-4245CX6P.js"),{loadReferences:n}=await import("./loader-4ZGTK7LD.js"),{loadRecipes:s}=await import("./recipes-7S4MC5OJ.js"),i=[];if(e.workspace){let p=se().agents?.[e.workspace];p||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(B(p.workspace))}else if(e.allWorkspaces){let u=se();for(let p of Object.values(u.agents||{}))p?.workspace&&i.push(B(p.workspace))}else i.push(B(e.cwd));let r=B(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,d]=await Promise.all([n(r),s(r)]),g=t({skills:c,references:l,recipes:d});if(e.json)console.log(JSON.stringify(g.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 p of g)u[p.verdict]++;console.log();for(let p of g){let f=p.verdict==="PASS"?h.green("PASS "):p.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${f} ${h.bold(p.name)}${p.skill?.path?h.dim(` (${p.skill.path})`):""}`);for(let w of p.reasons)console.log(` ${h.dim("\xB7")} ${w}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(g.some(u=>u.verdict==="FAILING")?1:0)});jo.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=se(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([d])=>d===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-BOKE5M5S.js"),{pickSkillForTask:a}=await import("./select-F5I5PO2O.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
|
|
17
|
+
shortlist (lexical -> judged)`));for(let d of l.shortlist.slice(0,6)){let g=d.p===void 0?" - ":d.p.toFixed(2);console.log(h.dim(` ${d.lexical.toFixed(2)} -> ${g} ${d.name}`))}}l.judged||console.log(h.dim(`
|
|
18
|
+
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Et=new Ve().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Et.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=B(o.cwd),n=B(t,"references/example"),s=B(t,"references/recipes/example.yaml");me(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=B(t,".agentx/references",e),r=B(t,".agentx/references/recipes");Ke(i,{recursive:!0}),Ke(r,{recursive:!0});let a=Zn(n).filter(g=>g.endsWith(".yaml")||g.endsWith(".yml")),c=0,l=0;for(let g of a){let u=go(i,g);if(me(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let f=mo(go(n,g),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Xo(u,f),console.log(h.green(` + ${u}`)),c++}let d=go(r,`${e}.yaml`);if(me(d)&&!o.force)console.log(h.dim(` skip ${d} (exists; --force to overwrite)`)),l++;else if(me(s)){let g=mo(s,"utf-8").replaceAll("example.",`${e}.`);Xo(d,g),console.log(h.green(` + ${d}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Et.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-BOKE5M5S.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-D4VVRNAI.js"),i=B(o.cwd),r=o.from?String(o.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let d=s(c,e),g=B(o.referencesCwd||o.cwd),u=B(g,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[w,y]of Object.entries(d))console.log(h.cyan(`
|
|
19
|
+
--- ${w} ---`)),console.log(y.split(`
|
|
20
|
+
`).slice(0,30).map(k=>` ${k}`).join(`
|
|
21
|
+
`)),y.split(`
|
|
22
|
+
`).length>30&&console.log(h.dim(` \u2026 (${y.split(`
|
|
23
|
+
`).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}Ke(u,{recursive:!0});let p=0,f=0;for(let[w,y]of Object.entries(d)){let k=go(u,w);if(me(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),f++;continue}Xo(k,y),console.log(h.green(` + ${k}`)),p++}console.log(),console.log(h.dim(` ${p} written, ${f} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Et.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-4ZGTK7LD.js"),t=await o(B(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var es=new Ve().name("hook").description("manage hooks \u2014 add to agent workspace");es.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=se().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=B(t.workspace,".claude/settings.json"),s=me(n)?JSON.parse(mo(n,"utf-8")):{},i=await Se([{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),Ke(B(t.workspace,".claude"),{recursive:!0}),Xo(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var os=new Ve().name("migrate").description("import configuration from OpenClaw or other tools");os.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,B(process.env.HOME||"",".openclaw/openclaw.json"),B(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let p of t)if(p&&me(p)){n=p;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(mo(n,"utf-8")),i=me(B(process.cwd(),"agentx.json"))?se():{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 p of a)p.match?.channel==="telegram"&&(c[p.match.accountId]=p.agentId);r.find(p=>p.id==="main"||p.default)&&(c.default="main");let l=0;for(let p of r){if(p.workspace?.startsWith("/data"))continue;let f=p.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=p.groupChat?.mentionPatterns||[];if(w.some(y=>y===f)||w.push(f),i.agents[f]={name:p.name,workspace:p.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:p.id==="main"?2:1,systemPrompt:`You are ${p.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){Ke(B(p.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-B3F3TUDE.js");y(f,i.agents[f])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let d=s.channels?.telegram?.accounts||{},g=0;for(let[p,f]of Object.entries(d)){if(!f.botToken)continue;let y=c[p]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[p]={token:f.botToken,agentBinding:y},i.channels.telegram.enabled=!0,g++}console.log(` ${h.green(g)} Telegram accounts imported`);let u=B(n,"../cron/jobs.json");if(me(u)){let p=JSON.parse(mo(u,"utf-8")),f=0;for(let w of p.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},f++}console.log(` ${h.green(f)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
|
|
24
|
+
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Ie(i),console.log(h.green(`
|
|
25
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var po=new Ve().name("config").description("validate and inspect configuration");po.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=H(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Jt(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=me(B(r,".claude")),c=me(B(r,"CLAUDE.md")),l=me(B(r,".claude/settings.json")),d=me(B(r,".claude/skills"))?Zn(B(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,g=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${d} skills`];console.log(` ${h.cyan(s)}: ${g.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});po.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=H(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Jc(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 Xn(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}po.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-HBX53OMJ.js"),{expandEnvVars:r}=await import("./config-HL5F36V4.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),d=i(l,e);o.json?console.log(JSON.stringify(d)):console.log(Xn(d))});po.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-HBX53OMJ.js"),r=Jc(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${Xn(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${Xn(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});po.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-HBX53OMJ.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});po.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 g=H(e.config);o=!!g.business?.enabled,t=(g.business?.projects??[]).length}catch(g){n=g?.message??String(g)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let d=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${d}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/master/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Hc}from"commander";import uo from"chalk";import{resolve as fo}from"path";import{existsSync as zc}from"fs";var no=new Hc().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ro(e){let o=fo(e,".agentx/db.sqlite");zc(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=$i({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 Co(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])))}no.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=Ro(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=`
|
|
26
|
+
SELECT agent_id, channel, status, duration_ms,
|
|
27
|
+
input_tokens, output_tokens,
|
|
28
|
+
substr(message_preview, 1, 60) AS message,
|
|
29
|
+
started_at
|
|
30
|
+
FROM task_history
|
|
31
|
+
${t.length?"WHERE "+t.join(" AND "):""}
|
|
32
|
+
ORDER BY started_at DESC
|
|
33
|
+
LIMIT @limit
|
|
34
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});Co(i,!!e.json)});no.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=Ro(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?`
|
|
35
|
+
SELECT agent_id, reason, COUNT(*) AS n,
|
|
36
|
+
ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
|
|
37
|
+
MAX(last_turn_input_tokens) AS max_input_tokens
|
|
38
|
+
FROM rotations
|
|
39
|
+
${s}
|
|
40
|
+
GROUP BY agent_id, reason
|
|
41
|
+
ORDER BY n DESC
|
|
42
|
+
`:`
|
|
43
|
+
SELECT agent_id, channel, reason, last_turn_input_tokens, rotated_at
|
|
44
|
+
FROM rotations
|
|
45
|
+
${s}
|
|
46
|
+
ORDER BY rotated_at DESC
|
|
47
|
+
LIMIT @limit
|
|
48
|
+
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});Co(r,!!e.json)});no.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=Ro(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=`
|
|
49
|
+
SELECT day, agent_id, model, tasks,
|
|
50
|
+
input_tokens AS in_tok, output_tokens AS out_tok,
|
|
51
|
+
cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
|
|
52
|
+
FROM usage_daily
|
|
53
|
+
${t.length?"WHERE "+t.join(" AND "):""}
|
|
54
|
+
ORDER BY day DESC, agent_id
|
|
55
|
+
`,i=o.prepare(s).all(n);Co(i,!!e.json)});no.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=Ro(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?`
|
|
56
|
+
SELECT channel, kind, deciding_stage, COUNT(*) AS n
|
|
57
|
+
FROM route_traces
|
|
58
|
+
${s}
|
|
59
|
+
GROUP BY channel, kind, deciding_stage
|
|
60
|
+
ORDER BY n DESC
|
|
61
|
+
`:`
|
|
62
|
+
SELECT channel, chat_id, kind, deciding_stage, agent_id,
|
|
63
|
+
substr(reason, 1, 60) AS reason, at
|
|
64
|
+
FROM route_traces
|
|
65
|
+
${s}
|
|
66
|
+
ORDER BY at DESC
|
|
67
|
+
LIMIT @limit
|
|
68
|
+
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});Co(r,!!e.json)});no.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=Ro(fo(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
|
|
69
|
+
SELECT agent_id, channel, duration_ms,
|
|
70
|
+
substr(error, 1, 120) AS error,
|
|
71
|
+
started_at
|
|
72
|
+
FROM task_history
|
|
73
|
+
WHERE ${t.join(" AND ")}
|
|
74
|
+
ORDER BY started_at DESC
|
|
75
|
+
LIMIT @limit
|
|
76
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});Co(i,!!e.json)});no.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Ro(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}));Co(n,!!e.json)});no.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=Ro(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();Co(n,!!o.json)}catch(n){console.log(uo.red(` ${n.message}`)),process.exit(1)}});import{Command as Kc}from"commander";import z from"chalk";import{mkdtempSync as Vc}from"fs";import{tmpdir as Qc}from"os";import{resolve as wr,join as br}from"path";import{existsSync as Xc}from"fs";import Zc from"better-sqlite3";function yr(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(f){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${f?.message??f}`})}continue}let l=c.decision,d=s.get(l.eventId);if(!d){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 g=Gc(l),u={id:d.id,ts:d.ts,source:d.source,sourceEventId:d.sourceEventId,project:d.project,subject:d.subject,intent:d.intent,rawJson:d.rawJson},p=bi(e,u,g,()=>l.decidedAt);a+=1,(p.outcome!==l.outcome||p.agentId!==l.agentId)&&r.push({eventId:d.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:p.agentId,outcome:p.outcome},reason:Yc(l,p)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Gc(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Yc(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 ho=new Kc().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function ot(e){let o=wr(e.cwd??process.cwd()),t=wr(o,e.path??".agentx/intent/ledger.sqlite");Xc(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 Zc(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 To(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 el(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 sn(e){if(!e)return;let o=el(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}ho.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=ot(e),t=sn(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,d=o.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:t}),g=o.prepare(`
|
|
77
|
+
SELECT COUNT(*) as n FROM intent_decisions d
|
|
78
|
+
LEFT JOIN intent_resolutions r
|
|
79
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
80
|
+
WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
|
|
81
|
+
`).get().n;if(e.json){console.log(JSON.stringify({since:t??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:d,inFlight:g},null,2));return}console.log(z.bold("Events by source")),To(r,!1),console.log(),console.log(z.bold(`Decisions: ${a}`)),To(c,!1),console.log(),console.log(z.bold(`Divergences: ${l}`)),To(d,!1),console.log(),console.log(z.bold(`In-flight (dispatched, no resolution): ${g}`))});ho.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=ot(e),t=sn(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(`
|
|
82
|
+
SELECT
|
|
83
|
+
datetime(ts/1000, 'unixepoch') AS at,
|
|
84
|
+
source,
|
|
85
|
+
decided_by,
|
|
86
|
+
ledger_outcome AS L_outcome,
|
|
87
|
+
COALESCE(ledger_agent_id, '-') AS L_agent,
|
|
88
|
+
legacy_outcome AS X_outcome,
|
|
89
|
+
COALESCE(legacy_agent_id, '-') AS X_agent,
|
|
90
|
+
substr(COALESCE(legacy_reason, ledger_reason, ''), 1, 60) AS reason
|
|
91
|
+
FROM intent_divergences
|
|
92
|
+
${i}
|
|
93
|
+
ORDER BY ts DESC
|
|
94
|
+
LIMIT @limit
|
|
95
|
+
`).all(s);To(r,!!e.json)});ho.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=ot(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(`
|
|
96
|
+
SELECT
|
|
97
|
+
datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
|
|
98
|
+
e.source,
|
|
99
|
+
d.decided_by,
|
|
100
|
+
COALESCE(d.agent_id, '-') AS agent,
|
|
101
|
+
COALESCE(e.project, '-') AS project,
|
|
102
|
+
COALESCE(e.subject, '-') AS subject,
|
|
103
|
+
ROUND((strftime('%s', 'now')*1000 - d.decided_at) / 1000.0) AS age_s
|
|
104
|
+
FROM intent_decisions d
|
|
105
|
+
JOIN intent_events e ON e.id = d.event_id
|
|
106
|
+
LEFT JOIN intent_resolutions r
|
|
107
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
108
|
+
WHERE ${t.join(" AND ")}
|
|
109
|
+
ORDER BY d.decided_at DESC
|
|
110
|
+
LIMIT @limit
|
|
111
|
+
`).all(n);To(s,!!e.json)});ho.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=ot(e),t=sn(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(`
|
|
112
|
+
SELECT
|
|
113
|
+
datetime(ts/1000, 'unixepoch') AS at,
|
|
114
|
+
source,
|
|
115
|
+
COALESCE(project, '-') AS project,
|
|
116
|
+
COALESCE(subject, '-') AS subject,
|
|
117
|
+
COALESCE(intent, '-') AS intent
|
|
118
|
+
FROM intent_events
|
|
119
|
+
${i}
|
|
120
|
+
ORDER BY ts DESC
|
|
121
|
+
LIMIT @limit
|
|
122
|
+
`).all(s);To(r,!!e.json)});ho.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=ot(o),n=null,s=null;if(o.bySubject){let g=e.indexOf(":");g<0&&(console.log(z.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,g),s=e.slice(g+1)}else{let g=t.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);g||(console.log(z.red(` no event with id ${e}`)),process.exit(1)),n=g.project,s=g.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
|
|
123
|
+
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(g=>g.id),a=r.map((g,u)=>`@id${u}`).join(", "),c=Object.fromEntries(r.map((g,u)=>[`id${u}`,g])),l=t.prepare(`
|
|
124
|
+
SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
|
|
125
|
+
r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
|
|
126
|
+
FROM intent_decisions d
|
|
127
|
+
LEFT JOIN intent_resolutions r
|
|
128
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
129
|
+
WHERE d.event_id IN (${a})
|
|
130
|
+
ORDER BY d.decided_at ASC
|
|
131
|
+
`).all(c);if(o.json){let g=i.map(u=>({event:u,decisions:l.filter(p=>p.event_id===u.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:g},null,2));return}let d=new Set;for(let g of l)g.outcome==="dispatched"&&g.agent_id&&d.add(g.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), ${d.size} distinct agent(s) dispatched`)),console.log();for(let g of i){let u=new Date(g.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${z.dim(u)} ${z.bold(g.id)} ${z.dim(`(${g.source}/${g.intent})`)}`);let p=l.filter(f=>f.event_id===g.id);if(p.length===0){console.log(z.dim(" (no decisions yet)"));continue}for(let f of p){let w=f.outcome==="dispatched"?z.green(f.outcome):f.outcome==="dropped"?z.dim(f.outcome):z.yellow(f.outcome),y=f.agent_id?z.cyan(f.agent_id):z.dim("-"),k=f.reason?z.dim(` \u2014 ${f.reason.slice(0,60)}`):"";if(console.log(` ${z.dim(f.decided_by)} \u2192 ${w} ${y}${k}`),f.resolution_status){let b=f.resolution_status==="ok"?z.green(f.resolution_status):z.red(f.resolution_status),x=f.duration_ms?`${(f.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${z.dim("resolved")} ${b} ${z.dim(x)}`)}else f.outcome==="dispatched"&&console.log(` ${z.yellow("(in-flight, no resolution)")}`)}}console.log()});ho.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=ot(e),t=sn(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(`
|
|
132
|
+
SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
133
|
+
FROM intent_events
|
|
134
|
+
${n.length?"WHERE "+n.join(" AND "):""}
|
|
135
|
+
ORDER BY ts ASC
|
|
136
|
+
${i}
|
|
137
|
+
`).all(s).map(f=>({id:f.id,ts:f.ts,source:f.source,sourceEventId:f.source_event_id,project:f.project,subject:f.subject,intent:f.intent,rawJson:f.raw_json}));if(r.length===0){console.log(z.dim(" (no events match filter)"));return}let a=new Set(r.map(f=>f.id)),c=r.map((f,w)=>`@id${w}`).join(", "),l=Object.fromEntries(r.map((f,w)=>[`id${w}`,f.id])),d=o.prepare(`
|
|
138
|
+
SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
|
|
139
|
+
FROM intent_decisions
|
|
140
|
+
WHERE event_id IN (${c})
|
|
141
|
+
`).all(l).map(f=>({eventId:f.event_id,decidedAt:f.decided_at,decidedBy:f.decided_by,agentId:f.agent_id,outcome:f.outcome,reason:f.reason})),g=o.prepare(`
|
|
142
|
+
SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
|
|
143
|
+
FROM intent_resolutions
|
|
144
|
+
WHERE decision_event_id IN (${c})
|
|
145
|
+
`).all(l).map(f=>({decisionEventId:f.decision_event_id,decisionDecidedBy:f.decision_decided_by,resolvedAt:f.resolved_at,status:f.status,durationMs:f.duration_ms,resultSummary:f.result_summary})),u=Vc(br(Qc(),"agentx-ledger-replay-")),p=new mi({path:br(u,"target.sqlite")});try{let f=yr(p,r,d,g);if(e.json){console.log(JSON.stringify(f,null,2));return}console.log(z.bold(`Replayed ${f.eventsCount} events, ${f.decisionsCount} decisions, ${g.length} resolutions`)),f.divergences.length===0?console.log(z.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(z.red(` \u2717 ${f.divergences.length} divergences`)),To(f.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{p.close()}});Zs();uc();fc();hc();pc();ai();ht();import{Command as ol}from"commander";import U from"chalk";import{existsSync as $r}from"fs";import{resolve as ts}from"path";import tl from"better-sqlite3";var Ne=new ol().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Be=".agentx/decisions/decisions.sqlite";function nl(e){return ts(ts(e.cwd??process.cwd()),e.path??Be)}function Xe(e,o=!1){let t=nl(e);$r(t)||(console.log(U.red(` No decision store at ${t}`)),console.log(U.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 Bt({path:t,readonly:!o})}catch(n){console.log(U.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(U.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Qe(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(U.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(U.bold(s(t)));for(let i of e)console.log(s(t.map(r=>i[r])))}function ns(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 ss(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:ns(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}Ne.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",Be).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=Xe(e),t=ns(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
|
|
146
|
+
COUNT(*) AS calls,
|
|
147
|
+
SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
|
|
148
|
+
SUM(retries) AS retries,
|
|
149
|
+
SUM(truncated) AS truncated,
|
|
150
|
+
ROUND(AVG(latency_ms)) AS avgMs,
|
|
151
|
+
SUM(input_tokens) AS inTokens
|
|
152
|
+
FROM decision_calls
|
|
153
|
+
WHERE ts >= ?
|
|
154
|
+
GROUP BY seat, mode, backend, model, structure_mode
|
|
155
|
+
ORDER BY calls DESC`).all(t);Qe(n,e.json);let s=o.db.prepare(`SELECT seat, mode, COALESCE(action,'(none)') AS action, explored, COUNT(*) AS calls
|
|
156
|
+
FROM decision_calls WHERE ts >= ? GROUP BY seat, mode, action, explored
|
|
157
|
+
ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(U.bold(`
|
|
158
|
+
policy`)),Qe(s,!1),console.log(U.dim(`
|
|
159
|
+
explored=1 means the policy wanted to skip and the expensive path ran anyway.
|
|
160
|
+
Those are the only rows in the skip region that can ever be graded.`))),o.close()});Ne.command("calls").description("recent calls").option("--path <file>","store path",Be).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Xe(e),t=["ts >= ?"],n=[ns(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,
|
|
161
|
+
structure_mode AS structure, latency_ms AS ms, retries, truncated, error
|
|
162
|
+
FROM decision_calls WHERE ${t.join(" AND ")}
|
|
163
|
+
ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));Qe(s,e.json),o.close()});Ne.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",Be).option("--json").action((e,o)=>{let t=Xe(o),n=t.gradedRows({}).filter(s=>s.callId===e);if(n.length===0){console.log(U.dim(` (no answers for ${e} \u2014 check \`decisions calls\`)`)),t.close();return}Qe(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()});Ne.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",Be).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=Xe(n,!0);s.label(e,o,t,{kind:n.kind,labeledBy:n.by,note:n.note}),console.log(U.green(` labeled ${e}.${o} = ${t}`)),s.close()});Ne.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",Be).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Xe(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));Qe(t.map(n=>({callId:n.callId,question:n.question,predicted:n.predicted,confidence:n.confidence.toFixed(3),incumbent:n.incumbent??""})),e.json),o.close()});Ne.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",Be).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=Xe(e,!0),t=ts(process.cwd(),e.db);$r(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new tl(t,{readonly:!0});try{let s=Ei(n,o);console.log(U.green(` wrote ${s} label(s)`)),s===0&&console.log(U.dim(` Rows whose outcome is genuinely ambiguous stay unlabeled on purpose \u2014
|
|
164
|
+
label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});Ne.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",Be).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=Xe(e),t=o.gradedRows(ss(e)),n=ni(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(U.bold(`
|
|
165
|
+
${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(U.yellow(`
|
|
166
|
+
Not enough ground truth: ${n.nLabeled} labeled rows, need ${n.minN}.`)),console.log(U.dim(" An ECE on this little data is noise, and a noisy number on a dashboard gets acted on.")),console.log(U.dim(` Label the most informative rows: agentx decisions unlabeled --seat ${e.seat}`)),o.close();return}console.log(`
|
|
167
|
+
accuracy ${(n.accuracy*100).toFixed(1)}%`),console.log(` ECE ${n.ece.toFixed(4)} `+U.dim(`[95% CI ${n.eceInterval.lo.toFixed(4)}\u2013${n.eceInterval.hi.toFixed(4)}]`)),console.log(` ECE (mass) ${n.eceEqualMass.toFixed(4)} ${U.dim("equal-mass bins")}`),console.log(` MCE ${n.mce.toFixed(4)} ${U.dim("worst single bin")}`),console.log(` Brier ${n.brier.toFixed(4)} ${U.dim("proper score, lower is better")}`),console.log(` log loss ${n.logLoss.toFixed(4)}`);let s=n.temperature;console.log(`
|
|
168
|
+
fitted temperature ${s.temperature} `+U.dim(`(NLL ${s.nllBefore.toFixed(4)} \u2192 ${s.nll.toFixed(4)})`)),s.temperature>1.15&&console.log(U.dim(` T > 1 means the backend is overconfident. Set decisions.seats.${e.seat}.temperature = ${s.temperature}.`));let i=t.filter(a=>a.action==="skip"),r=i.filter(a=>a.explored&&a.truth!==void 0);i.length>0&&(console.log(`
|
|
169
|
+
skip region ${i.length} answers (${(i.length/t.length*100).toFixed(1)}% of traffic), ${r.length} gradeable`),r.length===0&&console.log(U.yellow(` Nothing in the skip region has been graded. Everything below describes
|
|
170
|
+
only the decisions this policy chose NOT to skip \u2014 it cannot tell you
|
|
171
|
+
what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(U.bold(`
|
|
172
|
+
reliability (equal-width bins)`)),Qe(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()});Ne.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",Be).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=Xe(e),t=o.gradedRows(ss(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=si(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(U.yellow(` ${s.n} labeled rows, need ${s.minN}.`)),o.close();return}console.log(U.bold(`
|
|
173
|
+
${e.seat} \u2014 held-out comparison (${s.folds}-fold, n=${s.n})`)),console.log(U.dim(` Cross-validated, because more parameters always fit training data better.
|
|
174
|
+
`)),Qe(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(U.green(`
|
|
175
|
+
Calibration differs by ${n.join("/")} \u2014 a single temperature averages groups`)),console.log(U.dim(" that need different corrections."))):s.best==="temperature"?console.log(U.dim(`
|
|
176
|
+
One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(U.dim(`
|
|
177
|
+
Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});Ne.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",Be).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=Xe(e),t=o.gradedRows({...ss(e),labeledOnly:!0}),n=ti(t,Number(e.steps));if(n.length===0){console.log(U.yellow(` No labeled rows for seat "${e.seat}".`)),o.close();return}Qe(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()});Ne.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",Be).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=>{Jo();let o=Xe(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
|
|
178
|
+
WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
|
|
179
|
+
${e.call?"AND id = ?":""}
|
|
180
|
+
ORDER BY ts DESC LIMIT 1`).get(...e.call?[e.seat,e.call]:[e.seat]);if(!t){console.log(U.yellow(` No recorded call with stored state for seat "${e.seat}".`)),console.log(U.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 ii(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(U.bold(`
|
|
181
|
+
${e.seat} on ${i.backend} (${i.model})`)),console.log(U.dim(` ${i.samples} samples of call ${t.id}, ${i.totalMs}ms, ${i.usage.inputTokens.toLocaleString()} input tokens
|
|
182
|
+
`)),Qe(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?U.red("NO"):"yes"})),!1),console.log(`
|
|
183
|
+
mean stdev ${i.meanStdev.toFixed(4)}`),console.log(U.dim(" TypeSafe publish 0.0102 for jev across a 14-question rubric, as a reference.")),i.unstable.length>0?(console.log(U.red(`
|
|
184
|
+
Unstable: ${i.unstable.join(", ")} \u2014 identical calls disagree about what to DO,`)),console.log(U.dim(` not merely by how much. Usually a compound question: one name, several questions.
|
|
185
|
+
Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(U.green(`
|
|
186
|
+
Every question held its decision across all samples.`)),console.log(U.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()});Ne.command("backends").description("registered decision backends and what they claim").action(()=>{Jo();let e=Xs().map(o=>{let t=Fn(o).capabilities;return{backend:o,source:t.probabilitySource,calibrated:t.calibratedProbabilities?"yes":"no",maxOptions:t.maxChoiceOptions,maxStateChars:t.maxStateChars}});Qe(e,!1),console.log(U.dim(`
|
|
187
|
+
source where the numbers come from. "verbalized" means the model wrote them
|
|
188
|
+
into its answer; "logits" means they were read off its next-token
|
|
189
|
+
distribution. Logits are the model's actual posterior \u2014 verbalized
|
|
190
|
+
ones are quantized at round values and are not.
|
|
191
|
+
calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
|
|
192
|
+
traffic. Reading real logits does not buy this: a posterior can be
|
|
193
|
+
confidently wrong. It comes from a recalibrator fitted on your own
|
|
194
|
+
labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});Ne.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=>{Jo();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=Bo(s,"Which option fits this state?")}e.noul&&(o.verdict=to(String(e.noul))),Object.keys(o).length===0&&(console.log(U.red(" Give at least one of --choice or --noul.")),process.exit(1));let n=await Fn(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as sl}from"commander";import O from"chalk";import{resolve as kr}from"path";import{existsSync as il}from"fs";import rl from"better-sqlite3";var At=new sl().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function rs(e){let o=kr(e.cwd??process.cwd()),t=kr(o,e.path??".agentx/db.sqlite");il(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 rl(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 al(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 cl(e){if(!e)return;let o=al(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 ll(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 is(e){return e==="ok"?O.green:e==="error"||e==="timeout"?O.red:e==="in-flight"?O.yellow:O.dim}At.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=rs(e),t=ki(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:cl(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=is(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(ll(n.startedAt))}`),n.error&&console.log(` ${O.red("error:")} ${n.error}`)}});At.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=rs(o),n=Jn(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}dl(n.task,n.steps)});function dl(e,o){let t=is(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.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?is(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(`
|
|
195
|
+
`).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2192")} ${a}`).join(`
|
|
196
|
+
`)),n.inputSummary.split(`
|
|
197
|
+
`).length>8&&console.log(` ${O.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
|
|
198
|
+
`).slice(0,8);console.log(r.map(a=>` ${O.dim("\u2190")} ${a}`).join(`
|
|
199
|
+
`)),n.outputSummary.split(`
|
|
200
|
+
`).length>8&&console.log(` ${O.dim("\u2026")}`)}n.error&&console.log(` ${O.red("error:")} ${n.error}`)}}At.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=rs(o),n=Jn(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(),d;try{d=await fetch(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})}catch(p){console.log(O.red(` daemon unreachable at ${a}: ${p.message||p}`)),process.exit(1)}let g=await d.json().catch(()=>({})),u=Date.now()-l;if(d.ok||(console.log(O.red(` replay failed (${d.status}): ${g.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(O.bold(" INPUT (replayed verbatim)")),console.log(),rn(i),console.log(),console.log(O.bold(` ORIGINAL OUTPUT ${O.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?rn(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=${g.error?"error":"ok"} ${u}ms tokens=in:${g.usage?.inputTokens??0}/out:${g.usage?.outputTokens??0}`)}`)),console.log(),rn(g.content??"(empty reply)"),g.error&&console.log(O.red(` error: ${g.error}`)),console.log();let p=(s.finalResponse??"").trim()===(g.content??"").trim();s.finalResponse&&(console.log(p?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(),rn(g.content??"(empty reply)"),g.error&&console.log(O.red(`
|
|
201
|
+
error: ${g.error}`)),console.log(),console.log(O.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function rn(e){let o=e.split(`
|
|
202
|
+
`),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 ul}from"commander";import le from"chalk";import{existsSync as fl,mkdirSync as hl,writeFileSync as yl}from"fs";import{resolve as Sr,join as xr,dirname as wl}from"path";var gl=`# AgentX destructive-action guardrails \u2014 global policy
|
|
203
|
+
#
|
|
204
|
+
# This file + environments/*.yaml + agents/<id>.yaml are deep-merged
|
|
205
|
+
# (most specific wins). The built-in catalog (prisma / rm -rf / docker /
|
|
206
|
+
# terraform / git push --force ... patterns) is ALWAYS applied underneath.
|
|
207
|
+
# The guard reads policy live on every tool call \u2014 edits take effect on the
|
|
208
|
+
# next command, no daemon restart needed.
|
|
209
|
+
version: 1
|
|
210
|
+
|
|
211
|
+
# warn = compute + audit but never block (Phase 1 rollout stance).
|
|
212
|
+
# enforce = honor the verdict (deny blocks; escalate asks).
|
|
213
|
+
# off = kill-switch, allow everything.
|
|
214
|
+
# Flip to enforce once \`agentx guard log\` shows an acceptable false-positive rate.
|
|
215
|
+
mode: warn
|
|
216
|
+
|
|
217
|
+
defaults:
|
|
218
|
+
fail_mode: closed # guard error on a protected-target command => deny
|
|
219
|
+
unmatched: allow # commands no rule matches run freely (keep routine work fast)
|
|
220
|
+
|
|
221
|
+
# Extra global rules beyond the catalog go here. Example:
|
|
222
|
+
# rules:
|
|
223
|
+
# - id: no-prod-ssh
|
|
224
|
+
# match: { tool: Bash, command_regex: "ssh ", target_in: production }
|
|
225
|
+
# action: escalate
|
|
226
|
+
# severity: high
|
|
227
|
+
rules: []
|
|
228
|
+
`,ml=`# Production protected resources.
|
|
229
|
+
#
|
|
230
|
+
# The catalog rules reference \`target_in: production\`, so DECLARING this set is
|
|
231
|
+
# what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
|
|
232
|
+
# the workspace before matching \u2014 so \`--shadow-database-url $DATABASE_URL\` is
|
|
233
|
+
# caught even though the literal string "production" never appears in the command
|
|
234
|
+
# (this is exactly the 2026-07-21 incident class).
|
|
235
|
+
protected_resources:
|
|
236
|
+
production:
|
|
237
|
+
resolve_env: true
|
|
238
|
+
db_urls:
|
|
239
|
+
- "\${PROD_DATABASE_URL}"
|
|
240
|
+
hosts:
|
|
241
|
+
- "api.demosite.example.com"
|
|
242
|
+
- "203.0.113.12"
|
|
243
|
+
# buckets:
|
|
244
|
+
# - "my-prod-uploads"
|
|
245
|
+
# contexts: # k8s contexts, droplet ids, cluster names
|
|
246
|
+
# - "do-fra1-prod"
|
|
247
|
+
|
|
248
|
+
# Production-only rules beyond the catalog:
|
|
249
|
+
rules: []
|
|
250
|
+
`,pl=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
|
|
251
|
+
# this agent (the filename names it). coder agents never touch production.
|
|
252
|
+
rules:
|
|
253
|
+
- id: coder-no-prod
|
|
254
|
+
match:
|
|
255
|
+
target_in: production
|
|
256
|
+
action: deny
|
|
257
|
+
severity: critical
|
|
258
|
+
message: "coder-agent is not permitted to run commands against production."
|
|
259
|
+
`,vr=[{relPath:"policy.yaml",content:gl},{relPath:"environments/production.yaml",content:ml},{relPath:"agents/coder-agent.yaml",content:pl}];var yo=new ul().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function as(e){return e==="deny"?le.red:e==="escalate"||e==="ask"?le.yellow:e==="warn"?le.magenta:le.green}function an(e){return e.root?Sr(e.root):Bi()}yo.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 Wi({root:an(e),agentId:e.agent,env:e.env}),process.exit(0)});yo.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=an(o),n=o.enforce?"enforce":void 0,{verdict:s,mode:i,ms:r}=qi({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}bl(s,i,r)});function bl(e,o,t){let n=as(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":le.dim(" (no rule matched)")}`),console.log(` enforced as ${as(e.effectiveAction)(e.effectiveAction)} ${le.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${le.cyan(e.ruleId)}${e.severity?le.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${le.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${le.dim(`evaluated in ${t}ms`)}`),console.log()}yo.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=Fi({root:an(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(le.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=as(t.verdict),i=t.effective_action!==t.verdict?le.dim(`->${t.effective_action}`):"";console.log(` ${le.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${le.cyan((t.agent_id??"?").padEnd(16))} ${le.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(le.dim(` target: ${t.resolved_target}`))}});yo.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=xr(Sr(e.root),Li),t=0;for(let n of vr){let s=xr(o,n.relPath);if(fl(s)&&!e.force){console.log(le.dim(` skip (exists) ${n.relPath}`));continue}hl(wl(s),{recursive:!0}),yl(s,n.content),console.log(le.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${le.cyan(o)}`),console.log(le.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(le.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});yo.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(le.green(` daemon reloaded (${e.url})`)):console.log(le.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(le.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});yo.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=Ui(an(e),e.agent);console.log(JSON.stringify(o,null,2))});yt();import{Command as Il}from"commander";import{execFile as Ol}from"child_process";import{promisify as jl}from"util";import{existsSync as Rl}from"fs";import{resolve as Cl}from"path";import Je from"chalk";ht();var Ot="ui-element";function cn(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:It(t.tried,80),screenChanged:t.changed,note:t.note?It(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:Er(t.role),label:It(t.label,120),value:t.value?It(t.value,80):null,enabled:t.enabled}))}}function ln(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${Er(t.role)}: ${It(n,80)}`}return{target:Bo(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:to("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 dn(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 Er(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function It(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{execFile as vl}from"child_process";import{promisify as xl}from"util";import{existsSync as Sl}from"fs";import{resolve as El}from"path";var $l=/^AX(Button|MenuItem|MenuButton|TextField|TextArea|CheckBox|RadioButton|PopUpButton|Link|Tab|Row|Cell|ComboBox|SearchField|Slider|Disclosure|Toolbar|StaticText)/;function kl(e){let o=new Map(e.map(i=>[i.id,i])),t=new Set(e.filter(i=>i.role==="AXWebArea").map(i=>i.id));if(t.size===0)return e;let n=i=>{let r=i;for(let a=0;r&&a<64;a++){if(t.has(r.id))return!0;if(r.parent<0)return!1;r=o.get(r.parent)}return!1},s=e.filter(n);return s.length>=2?s:e}function Ar(e,o=60){let t=n=>/^AX(TextField|TextArea|SearchField|ComboBox)/.test(n)?0:/^AX(Button|MenuItem|MenuButton|PopUpButton|CheckBox|RadioButton|Tab|Link)/.test(n)?1:/^AX(Row|Cell|Slider|Disclosure|Toolbar)/.test(n)?2:3;return kl(e).filter(n=>$l.test(n.role)).filter(n=>n.width>=1&&n.height>=1).map((n,s)=>({e:n,i:s})).sort((n,s)=>t(n.e.role)-t(s.e.role)||n.i-s.i).map(({e:n})=>n).slice(0,o).map((n,s)=>({id:n.id,role:n.role,label:(n.label||n.value||"").trim()||`${n.role.replace(/^AX/,"")} ${s+1}`,value:n.value??null,enabled:n.enabled}))}var Ir=xl(vl),Ze=El(process.cwd(),"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper"),Al=6;async function gn(e={}){if(!Sl(Ze))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let{stdout:o}=await Ir(Ze,["read","--max","400"]),t=JSON.parse(o),n=Ar(t.elements,e.max??60),s=new Map;if(!(e.ocr!==!1&&n.length<Al))return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s};try{let{stdout:r}=await Ir(Ze,["ocr"],{maxBuffer:8388608}),a=JSON.parse(r),c=Math.max(0,...t.elements.map(d=>d.id))+1,l=[];for(let d of a.hits){if(d.confidence<.5||d.text.length<2)continue;let g=c++;if(s.set(g,{x:d.x,y:d.y,width:d.width,height:d.height}),l.push({id:g,role:"OCRText",label:d.text,value:null,enabled:!0}),l.length>=(e.max??60))break}return{app:t.app,window:t.window??null,candidates:[...n,...l],elements:t.elements,usedOCR:l.length>0,ocrRects:s}}catch{return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s}}}function jt(e,o){let t=e.elements.find(n=>n.id===o);return t?{x:t.x,y:t.y,width:t.width,height:t.height}:e.ocrRects.get(o)??null}var Or=jl(Ol),cs=Cl(process.cwd(),"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper"),jr=new Il().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)=>{Rl(cs)||(console.log(Je.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await gn({max:Number(o.max)||40})}catch(g){console.log(Je.red(` could not read the screen: ${g?.message??g}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(Je.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let g=jt(t,n[0].id);g&&(console.log(Je.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+Je.bold(n[0].label)),await Or(cs,["point","--x",String(g.x),"--y",String(g.y),"--w",String(g.width),"--h",String(g.height),"--label",n[0].label]));return}let s=await Ge(Ot,cn({request:e,app:t.app,window:t.window,candidates:n}),ln(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(Je.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Ot}.mode`)),process.exit(1));let i=dn(s.answers,n),r=jt(t,i.id),a=n.find(g=>g.id===i.id)?.label??"",c=t.ocrRects.has(i.id),l=Number(o.minPresent)||.5;if((i.present<l||!r)&&(console.log(Je.yellow(` nothing on screen matches "${e}"`)+Je.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(g=>({...g,label:n.find(u=>u.id===g.id)?.label}))},null,2));return}let d=a;console.log(` ${Je.green("\u2192")} ${Je.bold(d)} `+Je.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Or(cs,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",d])});import{Command as nd}from"commander";import _e from"chalk";import{execFile as Tl}from"child_process";import{promisify as Nl}from"util";import{existsSync as _l,readFileSync as ls}from"fs";import{homedir as Dl,tmpdir as Pl}from"os";import{join as Rr}from"path";var Ml=Nl(Tl),Cr=12e5,Ll="https://openrouter.ai/api/v1/chat/completions",Ul=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function Fl(e={kind:"window"},o=Cr){if(!_l(Ze))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",Rr(Pl(),`agentx-look-${Date.now()}.png`),"--max-pixels",String(o)];e.kind==="menubar"&&n.push("--menubar"),e.kind==="screen"&&n.push("--screen-full"),(e.kind==="screen"||e.kind==="menubar")&&e.index!==void 0&&n.push("--screen",String(e.index)),e.kind==="rect"&&n.push("--x",String(e.x),"--y",String(e.y),"--w",String(e.width),"--h",String(e.height));let{stdout:s}=await Ml(Ze,n),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=ls(i.path).length;return{path:i.path,region:{x:i.region.x,y:i.region.y,width:i.region.w,height:i.region.h},bytes:r}}var ql=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
260
|
+
|
|
261
|
+
Report only what is visible in this image.
|
|
262
|
+
|
|
263
|
+
The failure that matters: an application that performs an action is on screen, and you report that the action is happening. Those are different claims. A recorder being open is not a recording in progress. A button existing is not a button that has been pressed. A dialog offering a choice is not a choice that was made.
|
|
264
|
+
|
|
265
|
+
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.
|
|
266
|
+
|
|
267
|
+
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 Wl(e,o,t,n){let s=Jl();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=ls(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
|
|
268
|
+
|
|
269
|
+
The image is the region ${Bl(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:ql,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(Ll,{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 f=await l.text().catch(()=>"");throw new Error(`vision model ${l.status}: ${f.slice(0,300)}`)}let d=await l.json(),g=d?.choices?.[0]?.message?.tool_calls?.[0];if(!g?.function?.arguments)throw new Error("vision model returned no structured report");let u=JSON.parse(g.function.arguments),p=u.reading==="yes"||u.reading==="no"?u.reading:"unclear";return{observation:(u.observation??"").trim(),evidence:(u.evidence??"").trim(),reading:p,model:typeof d.model=="string"?d.model:t,usage:{inputTokens:d?.usage?.prompt_tokens??0,outputTokens:d?.usage?.completion_tokens??0}}}async function mn(e,o={}){let t=Date.now(),n=await Fl(o.region??{kind:"window"},o.maxPixels??Cr),s=await Wl(e,n,o.model??Ul,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 Bl(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 Rt;function Jl(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(Rt!==void 0)return Rt??void 0;try{let e=ls(Rr(Dl(),".agentx","openrouter-key.txt"),"utf-8").trim();Rt=e.length>0?e:null}catch{Rt=null}return Rt??void 0}import{execFile as Hl}from"child_process";import{promisify as zl}from"util";var Gl=zl(Hl),Yl=["screencapture"],Kl=["Screen Studio","OBS","QuickTime Player","Zoom"];async function Nr(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Vl()),t}async function Vl(){let e=await Tr(Yl);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 Tr(Kl);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 Tr(e){let o=[];for(let t of e)try{let{stdout:n}=await Gl("pgrep",["-x",t]),s=n.trim().split(`
|
|
270
|
+
`)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}yt();ht();var _r="screen-state",Dr={observable:to("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:to("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 Pr(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 Mr(e){return{observable:e.observable.noul,holds:e.holds.noul}}var Ql=.6,Xl=.7,Zl=.3;async function un(e,o={}){let[t,n]=await Promise.all([mn(e,o),Nr(e).catch(()=>[])]),s=o.observableFloor??Ql,i=await Ge(_r,Pr({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:td(t),treeNote:o.treeNote,probes:n}),Dr,{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:od(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=Mr(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 (${pn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Xl?"confirmed":a<=Zl?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:ed(c,a,t),sighting:t,probes:n}}function ed(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${pn(o)}). ${n}`:e==="refuted"?`Not true (${pn(1-o)} it is false). ${n}`:`Inconclusive (${pn(o)}, between the thresholds). ${n}`}function od(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 td(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 pn=e=>`${Math.round(e*100)}%`;var Lr=new nd().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("--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(_e.red(" --rect wants x,y,w,h")),process.exit(1)),t={kind:"rect",x:n[0],y:n[1],width:n[2],height:n[3]}}try{if(o.verify){let s=await un(e,{region:t,model:o.model});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"?_e.green("\u2713"):s.outcome==="refuted"?_e.red("\u2717"):_e.yellow("?");console.log(` ${i} ${_e.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(_e.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(_e.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 mn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${_e.bold(n.observation)}`),n.evidence&&console.log(_e.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${sd(n.reading)}`),console.log(_e.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(_e.red(` ${n?.message??n}`)),process.exit(1)}});function sd(e){return e==="yes"?_e.green(e):e==="no"?_e.red(e):_e.yellow(e)}yt();import{Command as ad}from"commander";import{execFile as zr}from"child_process";import{promisify as cd}from"util";import{existsSync as ld,readFileSync as dd,writeFileSync as Gr,mkdirSync as gd}from"fs";import{homedir as md}from"os";import{join as pd,dirname as ud}from"path";import Oe from"chalk";ht();var ds="paste-transform";function Ur(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function Fr(e){let o={};for(let t of e)o[t.id]=t.criterion;return{worthChanging:to("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:Bo(o,"What shape should this paste arrive in?")}}function qr(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 id=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"]),rd=e=>/^https?:\/\/\S+$/i.test(e.trim()),gs=[{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(`
|
|
271
|
+
`);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(`
|
|
272
|
+
`).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
|
|
273
|
+
|
|
274
|
+
`)}},{id:"bullets",criterion:"Turn the lines into a markdown bullet list. For several short lines that are plainly separate items, going somewhere that renders markdown.",label:"bullet list",apply:e=>{let o=e.split(`
|
|
275
|
+
`).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
|
|
276
|
+
`)}},{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(`
|
|
277
|
+
`);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
|
|
278
|
+
`)}},{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(!rd(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])id.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(`
|
|
279
|
+
`)||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,`
|
|
280
|
+
`).trim();return o===e?null:o}}];function Wr(e){let o=[];for(let t of gs){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function Br(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
|
|
281
|
+
\u2026[${e.length-o} more characters]\u2026
|
|
282
|
+
${e.slice(-n)}`}function Jr(e){let o=e.trim();return o.includes(`
|
|
283
|
+
`)||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 ms=cd(zr),Yr=new ad().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 (${gs.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=hd();c===null&&(console.log(Oe.yellow(" nothing to undo")),process.exit(2)),await Vr(c),console.log(` ${Oe.green("\u2192")} clipboard restored`);return}let o=await yd();if(o||(console.log(Oe.yellow(" clipboard is empty")),process.exit(2)),Jr(o)){Kr(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=Wr(o),n=await wd();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Oe.red(` "${e.as}" does not apply to this clipboard`)),console.log(Oe.dim(` available: ${t.map(l=>l.transform.id).join(", ")}`)),process.exit(1)),await tt(e,c.transform.id,c.result,o,"forced",1);return}if(t.length<2){await tt(e,"asIs",o,o,"nothing else applies",0);return}let s=await Ge(ds,Ur({preview:Br(o),length:o.length,lineCount:o.split(`
|
|
284
|
+
`).length,app:n.app,destination:n.role,destinationLabel:n.label}),Fr(t.map(c=>c.transform)),{incumbent:{shape:"asIs"},features:{app:n.app,options:t.length,chars:o.length}});if(!s){await tt(e,"asIs",o,o,`seat unavailable \u2014 set decisions.seats.${ds}.mode`,0);return}let i=qr(s.answers),r=Number(e.min)||.6;if(i.worthChanging<r){await tt(e,"asIs",o,o,`paste as copied (P(worth changing) ${i.worthChanging.toFixed(2)} below ${r})`,i.worthChanging);return}let a=t.find(c=>c.transform.id===i.id);if(!a){await tt(e,"asIs",o,o,`seat chose "${i.id}", which was not offered`,i.worthChanging);return}await tt(e,a.transform.id,a.result,o,`${a.transform.label} (confidence ${i.confidence.toFixed(2)})`,i.worthChanging)});async function tt(e,o,t,n,s,i){let r=t!==n;r&&(e.apply||e.paste)&&(fd(n),await Vr(t)),Kr(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await ms(Ze,["key","--name","v","--mod","command"]).catch(a=>{console.log(Oe.red(` could not paste: ${a?.message??a}`))})}function Kr(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Oe.dim("\u2192")} ${Oe.bold("unchanged")} ${Oe.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Oe.green("\u2192")} ${Oe.bold(o.applied)} ${Oe.dim(`\xB7 ${o.reason}`)}`),console.log(Oe.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Oe.dim(Hr(o.original))),console.log(Oe.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(Hr(o.result)),!e.apply&&!e.paste&&console.log(Oe.dim(`
|
|
285
|
+
(dry run \u2014 pass --apply to write it back)`))}var Hr=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
|
|
286
|
+
`).map(t=>` ${t}`).join(`
|
|
287
|
+
`),fn=pd(md(),".agentx","paste-undo.txt");function fd(e){try{gd(ud(fn),{recursive:!0}),Gr(fn,e,{mode:384})}catch{}}function hd(){try{let e=dd(fn,"utf-8");return Gr(fn,"",{mode:384}),e.length?e:null}catch{return null}}async function yd(){let{stdout:e}=await ms("pbpaste",[],{maxBuffer:16777216});return e}async function Vr(e){await new Promise((o,t)=>{zr("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function wd(){if(!ld(Ze))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await ms(Ze,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:bd(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function bd(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 $d}from"commander";import He from"chalk";var kd=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function vd(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
|
|
288
|
+
${n}`:n,a=await fetch(`${kd}/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)}`)}}var Qr=new $d().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","Secretary").option("--priority <n>","1 (min) to 5 (max)","4").option("--urgent","deliver even during Focus").option("--channel <name>","delivery channel","ntfy").option("--chat-id <id>","channel address","default").option("--no-sound","do not play a sound on this machine").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 Ni,n=Ci(),s=o.sound===!1?!1:void 0;if(o.status){let r=t.list();if(o.json){console.log(JSON.stringify({focus:n,held:r},null,2));return}console.log(` ${n.active?He.yellow("\u25D0"):He.green("\u25CB")} ${Ti(n)} ${He.dim(`\xB7 ${n.reason}`)}`),console.log(` ${r.length} held`);for(let a of r.slice(0,8)){let c=new Date(a.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(He.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=vd(o.channel,o.chatId);if(o.flush){let r=await Di(i,{queue:t,sound:s});console.log(r?He.green(` delivered ${r} held notification(s)`):He.dim(" nothing was held"));return}e?.trim()||(console.log(He.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await _i({message:e.trim(),from:o.from,title:o.title,priority:Number(o.priority)||4,urgent:!!o.urgent,channel:o.channel,chatId:o.chatId},i,{queue:t,sound:s,focus:n});if(o.json){console.log(JSON.stringify(r,null,2));return}let a=r.delivered?He.green("\u2192"):He.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(He.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(He.red(` ${r?.message??r}`)),s!==!1&&Pi(),process.exit(1)}});yt();ai();Zs();ht();import{Command as xd}from"commander";import{readFileSync as Sd}from"fs";var Xr=new xd().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?Sd(e.file,"utf8"):await Ed()}catch(r){No(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return No("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return No(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return No("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return No("spec needs at least one entry in `questions`");try{oi(t.questions)}catch(r){return No(r?.message??String(r))}let n=t.seat||e.seat;Jo(),process.env[li(n)]="active";let s=null;if(e.record!==!1)try{s=new Bt({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
|
|
289
|
+
`)}ci({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ge(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return No(`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 No(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function Ed(){if(process.stdin.isTTY)return"";let e=[];for await(let o of process.stdin)e.push(Buffer.from(o));return Buffer.concat(e).toString("utf8")}yt();import{Command as Od}from"commander";import{execFile as jd,spawn as Zr}from"child_process";import{promisify as Rd}from"util";import{existsSync as Cd,readFileSync as Td,writeFileSync as Nd,unlinkSync as _d,statSync as Dd}from"fs";import{resolve as Pd,join as ea}from"path";import{tmpdir as Md}from"os";import te from"chalk";var Ad={id:"x-advanced-search",title:"X search: find anyone's best posts",appHint:"Open x.com in Chrome first, signed in.",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",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",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.",type:"from:naval min_faves:500",holdSeconds:1.8},{say:"And submit.",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."}]},Id={id:"x-bookmark-folders",title:"X bookmarks: turn the pile into folders",appHint:"Open x.com in Chrome first, signed in.",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"},{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."}]},ps=[Ad,Id];var yn=Rd(jd),hn=Pd(process.cwd(),"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper"),oa=new Od().name("teach").description("walk through something on screen, speaking and pointing as it goes").argument("[lesson]","lesson id (omit to list)").option("--voice <id>","ElevenLabs voice id").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").action(async(e,o)=>{if(!e){console.log(te.bold(`
|
|
290
|
+
lessons
|
|
291
|
+
`));for(let l of ps)console.log(` ${te.cyan(l.id.padEnd(22))} ${l.title}`),console.log(` ${" ".repeat(22)} ${te.dim(l.appHint)}
|
|
292
|
+
`);return}let t=ps.find(l=>l.id===e);t||(console.log(te.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),Cd(hn)||(console.log(te.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1)),console.log(te.bold(`
|
|
293
|
+
${t.title}`)),console.log(te.dim(` ${t.appHint}
|
|
294
|
+
`));let n=null,s=null;o.record&&(s=ea(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(te.dim(` recording \u2192 ${s}`)),n=Zr("/usr/sbin/screencapture",["-v","-x","-C",s],{stdio:["pipe","ignore","ignore"]}),await so(2e3));let i=o.hud===!1?null:Zr(hn,["hud"],{stdio:["pipe","ignore","ignore"]}),r=(l,d,g,u)=>{try{i?.stdin?.write(JSON.stringify({title:l,body:d,state:g,avoid:u})+`
|
|
295
|
+
`)}catch{}},a=[],c=!1;for(let[l,d]of t.steps.entries()){console.log(` ${te.dim(String(l+1).padStart(2))} ${d.say}`),r(`Step ${l+1} of ${t.steps.length}`,d.say,"talking");let g=o.speak===!1?Promise.resolve():Ud(d.say,o.voice),u=d.find?await Ld(d.find,a):null;if(d.find&&!u&&(a.push({tried:d.find,changed:!1,note:"not found on screen"}),console.log(te.yellow(` (couldn't find "${d.find}" \u2014 narrating only)`))),await g,u&&(r(`Step ${l+1} of ${t.steps.length}`,d.say,"pointing",{x:u.x,y:u.y,w:u.width,h:u.height}),await yn(hn,["point","--x",String(u.x),"--y",String(u.y),"--w",String(u.width),"--h",String(u.height),"--label",d.label??d.find??"","--hold",String(d.click||d.type?.5:d.holdSeconds??2.6)]).catch(()=>{}),d.click)){let{error:p,changed:f}=await us(["click"]);p&&console.log(te.red(` \u2717 ${p}`)),a.push({tried:d.label??d.find??"control",changed:f!==!1,note:p??void 0}),f===!1&&console.log(te.yellow(" \xB7 clicked, but the screen did not change")),await so(d.afterClickWaitMs??1500)}if(d.type){r(`Step ${l+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await us(["type","--text",d.type]);p&&(console.log(te.red(` \u2717 ${p}`)),r("Blocked",p,"waiting"),a.push({tried:`type into ${d.label??"the field"}`,changed:!1,note:p}),await so(2e3))}if(d.key){r(`Step ${l+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await us(["key","--name",d.key]);p&&(console.log(te.red(` \u2717 ${p}`)),r("Blocked",p,"waiting"),a.push({tried:`press ${d.key}`,changed:!1,note:p}),await so(2e3))}if(!u&&!d.type&&!d.key?await so((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await so(d.holdSeconds*1e3),d.verify){r(`Step ${l+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p;try{p=await un(d.verify)}catch(f){p=null,console.log(te.yellow(` ? could not check: ${f?.message??f}`))}if(p){let f=p.outcome==="confirmed"?te.green("\u2713"):p.outcome==="refuted"?te.red("\u2717"):te.yellow("?");if(console.log(` ${f} ${te.dim(p.reason)}`),!p.ok&&!d.verifyOptional){r("Stopped",`That did not work: ${d.verify}`,"waiting"),console.log(te.red(`
|
|
296
|
+
stopping: could not confirm \u2014 ${d.verify}`)),console.log(te.dim(` ${p.reason}`)),console.log(te.dim(` screenshot: ${p.sighting.shot.path}`)),await so(2500);try{i?.stdin?.end()}catch{}c=!0;break}}}}if(!c){r("Done",t.title,"done"),await so(1200);try{i?.stdin?.end()}catch{}}if(n&&s){n.kill("SIGINT"),await so(2500);try{let{size:l}=Dd(s);console.log(te.green(` recorded ${(l/1048576).toFixed(1)} MB \u2192 ${s}`))}catch{console.log(te.yellow(" recording produced no file \u2014 check Screen Recording permission"))}}if(c){console.log(te.red(` lesson stopped before the end.
|
|
297
|
+
`)),process.exitCode=3;return}console.log(te.green(`
|
|
298
|
+
done.
|
|
299
|
+
`))});async function us(e){try{let{stdout:o}=await yn(hn,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 Ld(e,o=[]){try{let t=await gn({max:45});if(t.candidates.length<2)return null;let n=await Ge(Ot,cn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),ln(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=dn(n.answers,t.candidates);return s.present<.5?null:jt(t,s.id)}catch{return null}}async function Ud(e,o){let t=Fd();if(t)try{let n=o||process.env.AGENTX_VOICE_ID||"21m00Tcm4TlvDq8ikWAM",s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n}`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:e,model_id:"eleven_turbo_v2_5"})});if(s.ok){let i=ea(Md(),`agentx-teach-${Date.now()}.mp3`);Nd(i,Buffer.from(await s.arrayBuffer())),await yn("/usr/bin/afplay",[i]);try{_d(i)}catch{}return}}catch{}await yn("/usr/bin/say",[e]).catch(()=>{})}function Fd(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let e of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let o=Td(e,"utf8").trim();if(o)return o}catch{}return null}var so=e=>new Promise(o=>setTimeout(o,e));import{Command as qd}from"commander";import M from"chalk";var _o=new qd().name("attach").description("wear an agentx agent identity in this Claude Code session"),fs=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${kt()}`;function hs(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function ys(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 ${M.cyan("agentx daemon start")}`:o}function ta(e){return e==="auto"?M.yellow:e==="manual"?M.gray:M.green}function Wd(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):M.gray("(not bound)"),n=e.pending?M.yellow(`${e.pending} pending`):M.gray("empty"),s=o?M.cyan(" \u2190 this session"):"";console.log(` ${M.bold(t)} ${ta(e.mode)(e.mode)} ${n} ${M.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${M.gray(e.cwd)}`)}_o.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Wn.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",fs).action(async(e,o)=>{let t=hs(o.session);t||(console.error(M.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${M.cyan("--session <id>")} (list them with ${M.cyan("agentx attach list")}).`),process.exit(1)),pi(o.mode)||(console.error(M.red(`Invalid mode "${o.mode}". Expected one of: ${Wn.join(", ")}`)),process.exit(1)),on()||(console.error(M.yellow("Attach hooks are not installed yet.")),console.error(`Run ${M.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await ys(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${M.green("\u2713")} This session is now wearing ${M.bold(e)} (${ta(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(M.yellow(` ${s} message(s) already queued for it.`)),console.log(M.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(M.red(`Bind failed: ${ws(n)}`)),process.exit(1)}});_o.command("detach").description("stop wearing an identity 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",fs).action(async e=>{let o=hs(e.session);o||(console.error(M.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await ys(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${M.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(M.red(`Detach failed: ${ws(t)}`)),process.exit(1)}});_o.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",fs).option("--json","raw JSON output").action(async e=>{let o=hs();try{let n=(await ys(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:on(),sessions:n},null,2));return}console.log(),console.log(on()?`${M.green("\u2713")} Attach hooks installed ${M.gray($t())}`:`${M.yellow("!")} Attach hooks not installed \u2014 run ${M.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(M.gray(" No session is wearing an identity right now."));else for(let r of s)Wd(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(M.gray(`
|
|
300
|
+
${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(M.red(`Could not read attach state: ${ws(t)}`)),process.exit(1)}});_o.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||kt()),t=rr(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${M.green("\u2713")} Installed attach hooks in ${M.gray(t.path)}`:`${M.green("\u2713")} Attach hooks already up to date in ${M.gray(t.path)}`),console.log(M.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(M.gray(" PreToolUse guard installed at user scope.")),console.log(M.gray(` (An attached session runs under your permissions, not the agent's workspace
|
|
301
|
+
settings \u2014 without this an attached production identity would be less
|
|
302
|
+
guarded than a spawned one.)`))):console.log(M.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${M.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(M.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});_o.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=ar({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${M.green("\u2713")} Removed attach hooks from ${M.gray(o.path)} (${o.events.join(", ")})`:`${M.gray("Nothing to remove.")}`),e.removeGuard||console.log(M.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(M.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});Te();import{Command as Bd}from"commander";import ue from"chalk";var wn=new Bd().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function sa(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=H(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 ia(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function na(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 Jd(e){return e==="busy"?ue.magenta:e==="warm-hot"?ue.green:e==="warm-cold"?ue.cyan:e==="idle"?ue.yellow:e==="dead"?ue.red:ue.dim}wn.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}=sa(e),n;try{n=await fetch(`${o}/api/processes`,{headers:ia(t)})}catch(r){console.log(ue.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ue.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ue.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(ue.dim(" (no processes)"));return}for(let r of i){let a=Jd(r.state)(r.state.padEnd(9)),c=na(r.spawnedAt),l=r.lastTurnAt?na(r.lastTurnAt)+" ago":"\u2014",d=r.lastInputTokens?ue.dim(`last_in=${r.lastInputTokens} tok`):"",g=r.claudeSessionId?ue.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ue.dim("sess=\u2014"),u=r.pendingTaskId?ue.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ue.bold(r.key.agentId)}${ue.dim(":"+r.key.channel+":"+r.key.chatId)} ${ue.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${g} ${d} ${u}`),r.deadReason&&console.log(` ${ue.red("dead:")} ${r.deadReason}`)}});wn.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}=sa(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:ia(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ue.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ue.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(ue.red(` ${a}`)),process.exit(1)}console.log(ue.green(` killed ${e}:${o}:${t}`))});import{Command as Hd}from"commander";import je from"chalk";import{existsSync as bs,rmSync as zd}from"fs";import{resolve as $s}from"path";var nt=new Hd().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");nt.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(je.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await yi(e,o,{verbose:n}),r=Date.now()-s;console.log(je.green(` \u2713 indexed ${i.docs} doc(s) for ${je.bold(e)} in ${r}ms`)),console.log(je.dim(` \u2192 ${i.path}`))});nt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=$s(e.cwd,".agentx","rag");if(!bs(o)){console.log(je.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>bs($s(o,s,"index.json")));if(n.length===0){console.log(je.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Bn(s);console.log(` ${je.bold(s)} ${i.docs} doc(s) ${je.dim(i.path)}`)}});nt.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=wi(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Bn(e);i.exists?console.log(je.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(je.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${je.bold(i.title)} ${je.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${je.dim(i.path)}`),console.log(` ${je.dim(i.snippet.slice(0,200))}`)});nt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=$s(process.cwd(),".agentx","rag",e);if(!bs(o)){console.log(je.dim(` no index for ${e} \u2014 nothing to clear`));return}zd(o,{recursive:!0,force:!0}),console.log(je.green(` \u2713 cleared index for ${e}`))});Te();import{Command as Gd}from"commander";import V from"chalk";import st from"prompts";var Do=new Gd().name("backlog").description("manage the local backlog used by business workSource=backlog");function Ct(e){let o=H(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Ji(n)}}function Yd(e){return e?V.cyan(`${e.type}:${e.project}#${e.iid}`):V.dim("manual")}function Kd(e){return{todo:V.gray("todo"),doing:V.yellow("doing"),blocked:V.red("blocked"),done:V.green("done")}[e]}Do.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}=Ct(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(V.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?V.magenta(`@${n.assignee}`):V.dim("unassigned");console.log(` ${Kd(n.status).padEnd(7)} ${Yd(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(V.dim(` ${n.source.url}`))}console.log(),console.log(V.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});Do.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=Ct(t.config);n.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(V.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Hi([o],i.source,n.config),a=await zn(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(V.dim(" sync:"),...c));console.log(a.ok?V.dim(` synced -> ${a.url??i.source.type}`):V.yellow(` sync failed: ${a.error}`))}});Do.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=Ct(o.config);t.store.findById(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(V.green(` done: ${s.title}`)),s.source){let i=await zn(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(V.dim(" sync:"),...r));console.log(i.ok?V.dim(` synced -> ${i.url??s.source.type}`):V.yellow(` sync failed: ${i.error}`))}});Do.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}=Ct(o.config);t.remove(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1)),console.log(V.green(` removed ${e}`))});Do.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=Ct(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(V.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await st({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(V.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(V.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Qd(o.config):Xd(o.config);y.length?(i=(await st({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await st({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await st({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await st({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(V.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Zd(o.config,i,a):await eg(o.config,i,a);if(!c.length){console.log(V.yellow(" no open issues matched"));return}console.log(V.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,d=new Set(o.store.list().map(y=>y.id)),g=c.map(y=>{let k=Hn({type:s,project:l,iid:y.iid,url:y.url}),b=d.has(k),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${b?V.dim(" (already imported)"):""}`,value:y,disabled:b}}),p=(await st({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:g,min:1})).selected||[];if(!p.length){console.log(V.dim(" nothing selected"));return}let f=p.map(y=>{let k={type:s,host:s==="gitlab"?Vd(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Hn(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(f);console.log(V.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(V.dim(` ${y.id} \u2014 ${y.title}`))});function Vd(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Qd(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 Xd(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 Zd(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 eg(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(ra)}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(ra):[]}function ra(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 ng}from"commander";import G from"chalk";import{existsSync as sg,readFileSync as ig}from"fs";import{resolve as rg}from"path";import ag from"prompts";Te();import og from"cronstrue";var ks={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},bn={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function eo(e){try{return og.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function tg(e){if(/\b(noon|midday)\b/.test(e))return bn.noon;if(/\bmidnight\b/.test(e))return bn.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function vs(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let g=parseInt(t[1],10);return g<1||g>59?null:{cron:`*/${g} * * * *`,human:eo(`*/${g} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:eo("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let g=parseInt(t[1],10);return g<1||g>23?null:{cron:`0 */${g} * * *`,human:eo(`0 */${g} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:eo("0 * * * *"),matched:"every hour"};let n=tg(o),s=null;for(let[g,u]of Object.entries(bn))if(!(g==="noon"||g==="midnight")&&new RegExp(`\\b(every\\s+)?${g}s?\\b`).test(o)){s=u;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let g=r[1],u=1;if(g==="last"||(/^\d+(st|nd|rd|th)?$/.test(g)?u=parseInt(g,10):g==="first"||g==="1st"?u=1:g==="2nd"?u=2:g==="3rd"&&(u=3),u<1||u>31))return null;let p=i||{h:9,m:0},f=`${p.m} ${p.h} ${u} * *`;return{cron:f,human:eo(f),matched:r[0]}}let a=[],c=Object.keys(ks).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),d=o.match(l);if(d){let g=d[1];for(let u of Object.keys(ks))if(new RegExp(`\\b${u}s?\\b`).test(g)){let p=ks[u];a.includes(p)||a.push(p)}}if(a.length){let g=i||{h:9,m:0};a.sort((f,w)=>f-w);let u=a.join(","),p=`${g.m} ${g.h} * * ${u}`;return{cron:p,human:eo(p),matched:`on ${u}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let g=i||{h:9,m:0},u=`${g.m} ${g.h} * * 1-5`;return{cron:u,human:eo(u),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let g=i||{h:9,m:0},u=`${g.m} ${g.h} * * 0,6`;return{cron:u,human:eo(u),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let g=i||{h:9,m:0},u=`${g.m} ${g.h} * * *`;return{cron:u,human:eo(u),matched:s&&Object.entries(bn).find(([,p])=>p===s)?.[0]||"daily"}}if(n){let g=`${n.m} ${n.h} * * *`;return{cron:g,human:eo(g),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function aa(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function ca(e){let o=e||rg(process.cwd(),"agentx.json");return sg(o)||(console.log(G.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(ig(o,"utf-8"))}function cg(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function lg(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(G.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await ag([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp/discord):"},{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(G.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wo=new ng().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wo.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){wo.help();return}o.agent||(console.log(G.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(G.red(' --do "<prompt>" is required')),process.exit(1));let t=vs(e);t||(console.log(G.red(` Couldn't parse: "${e}"`)),console.log(G.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(G.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(G.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=ca(o.config),s=ei(n);n.agents?.[o.agent]||(console.log(G.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(G.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=cg(o.onError),r=await lg(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||aa(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let l=await ne(g=>ce(g,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(G.red(` \u2717 ${l.error}`)),process.exit(1));let d=o.dryRun?"would add":"Added";console.log(G.green(` \u2713 ${d} cron ${G.cyan(a)}`)),console.log(G.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(G.dim(` Agent: ${o.agent}`)),r&&console.log(G.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(G.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(G.dim(" Daemon hot-reloaded."))});wo.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=ca(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(G.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?G.green("\u25CF"):G.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${G.cyan(s.padEnd(32))} ${G.dim(i.schedule.padEnd(14))} ${G.dim("\u2192")} ${i.agent}`),console.log(G.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(G.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])wo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await ne(s=>{if(!Ao(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);ce(s,`crons.${t}.enabled`,o)});n.success||(console.log(G.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(G.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(G.dim(" Daemon hot-reloaded."))});wo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ne(t=>{if(!Ao(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);vi(t,`crons.${e}`)});o.success||(console.log(G.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(G.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(G.dim(" Daemon hot-reloaded."))});wo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=vs(o);t||(console.log(G.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(G.green(` "${o}"`)),console.log(G.dim(` \u2192 ${t.cron}`)),console.log(G.dim(` \u2192 ${t.human}`))});import{Command as Dg}from"commander";import Mo from"chalk";import X from"chalk";import Tt from"prompts";import{readFileSync as dg,writeFileSync as gg,existsSync as mg}from"fs";import{resolve as la}from"path";var pg=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function ug(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function xs(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function da(e=".env"){let o=la(e);if(!mg(o))return[];let t=dg(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(pg);i?n.push({kind:"kv",key:i[1],value:ug(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function fg(e){return e.map(o=>o.kind==="kv"?`${o.key}=${xs(o.value)}`:o.raw).join(`
|
|
303
|
+
`)+`
|
|
304
|
+
`}function Po(e,o,t=".env"){let n=la(t),s=da(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${xs(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${xs(o)}`})),gg(n,fg(s))}function Ss(e,o=".env"){return da(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var ga="https://t.me/BotFather";async function hg(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 yg(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 ma(e={}){console.log(),console.log(X.bold(" Connect Telegram")),console.log(),console.log(X.dim(` 1. Open ${ga}`)),console.log(X.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(X.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Tt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(x,[ga],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Tt({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(X.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await hg(t.trim());n||(console.log(X.red("\u2717 invalid or revoked")),process.exit(1)),console.log(X.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(X.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(X.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await Tt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),d||(console.log(X.red(" Aborted")),process.exit(1));let g=c.channels?.telegram?.accounts||{},u=e.account||d;g[u]&&g[u].agentBinding!==d&&(u=(await Tt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${d}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(X.red(" Aborted")),process.exit(1));let p=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Po(p,t.trim()),process.env[p]=t.trim();let f=await ne(b=>{ce(b,"channels.telegram.enabled",!0),ce(b,`channels.telegram.accounts.${u}`,{token:`\${${p}}`,agentBinding:d});let x=Ao(b,`agents.${d}.mentions`)||[],A=`@${n.username}`;x.includes(A)||(x.push(A),ce(b,`agents.${d}.mentions`,x))},{configPath:e.configPath});if(f.success||(console.log(X.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(X.green(` \u2713 Bot @${n.username} bound to agent "${d}"`)),console.log(X.dim(` Token stored in .env as ${p}`)),console.log(X.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(X.dim(" Daemon hot-reloaded.")):console.log(X.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Tt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(X.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(X.dim(" Waiting up to 90s..."));let y=await yg(t.trim(),9e4);if(!y){console.log(X.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(X.dim(" agentx config set notifications.destination.channel telegram")),console.log(X.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(X.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ne(b=>{ce(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(X.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(X.green(" \u2713 Default --notify target set")),console.log(X.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(X.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))}import be from"chalk";import $n from"prompts";import{spawn as wg}from"child_process";var pa="https://discord.com/developers/applications",bg="67584";async function $g(e){try{let o=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${e}`},signal:AbortSignal.timeout(8e3)});return o.ok?await o.json():null}catch{return null}}function ua(e){try{let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";wg(o,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function fa(e={}){console.log(),console.log(be.bold(" Connect Discord")),console.log(),console.log(be.dim(" 1. Open the Discord Developer Portal")),console.log(be.dim(` ${pa}`)),console.log(be.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(be.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(be.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:o}=await $n({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});o&&ua(pa);let{token:t}=await $n({type:"password",name:"token",message:"Paste the bot token:",validate:y=>y.trim().length>20||"that looks too short for a Discord token"});t||(console.log(be.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await $g(t.trim());n||(console.log(be.red("\u2717 invalid or revoked \u2014 did you enable MESSAGE CONTENT INTENT and copy the right token?")),process.exit(1));let s=n.discriminator&&n.discriminator!=="0"?`${n.username}#${n.discriminator}`:n.username;console.log(be.green(`\u2713 ${s} (bot id ${n.id})`));let{readFileSync:i,existsSync:r}=await import("fs"),{resolve:a}=await import("path"),c=e.configPath||a(process.cwd(),"agentx.json");r(c)||(console.log(be.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let l=JSON.parse(i(c,"utf-8")),d=Object.keys(l.agents||{});d.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await $n({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(k=>({title:k,value:k})),initial:0})).agent),g||(console.log(be.red(" Aborted")),process.exit(1));let u="DISCORD_BOT_TOKEN";Po(u,t.trim()),process.env[u]=t.trim();let p=await ne(y=>{ce(y,"channels.discord.enabled",!0),ce(y,"channels.discord.token",`\${${u}}`),ce(y,"channels.discord.agentBinding",g)},{configPath:e.configPath});p.success||(console.log(be.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 Discord bot ${s} bound to agent "${g}"`)),console.log(be.dim(` Token stored in .env as ${u}`)),p.reloaded?console.log(be.dim(" Daemon hot-reloaded.")):console.log(be.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(be.bold(" Install the bot to a server")),console.log();let f=`https://discord.com/oauth2/authorize?client_id=${n.id}&scope=bot&permissions=${bg}`;console.log(` ${be.cyan(f)}`),console.log();let{openInstall:w}=await $n({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});w&&ua(f),console.log(),console.log(be.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(be.dim(" Mention the bot in any channel to route messages to the agent."))}import fe from"chalk";import Es from"prompts";import{existsSync as Is,mkdirSync as kg,readdirSync as vg,readFileSync as ha}from"fs";import{resolve as As}from"path";var xg=".agentx/whatsapp-sessions";function Sg(){let e=As(process.cwd(),".agentx/daemon.pid");if(!Is(e))return!1;try{let o=parseInt(ha(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Eg(e){if(!Is(e))return!1;try{return vg(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Ag(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(fe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(fe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;kg(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(d=>{let u=setTimeout(()=>{o(fe.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}d(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){o(fe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:f}=await import("qrcode-terminal");f.generate(p.qr,{small:!0})}catch{o(` QR: ${p.qr}`)}o("")}if(p.connection==="open"){clearTimeout(u),o(fe.green(" \u2713 Paired"));try{l.end(void 0)}catch{}d(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(fe.red(" \u2717 Authorization failed \u2014 rescan required")),d(!1))})})}async function ya(e={}){if(console.log(),console.log(fe.bold(" Connect WhatsApp")),console.log(),Sg()){console.log(fe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(fe.dim(" agentx daemon stop")),console.log();let{cont:l}=await Es({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(fe.red(" Aborted")),process.exit(1))}let o=e.configPath||As(process.cwd(),"agentx.json");Is(o)||(console.log(fe.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(ha(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||xg,s=As(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(fe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Es({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(d=>({title:d,value:d})),initial:0})).agent),r||(console.log(fe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Eg(s)&&a){let{keep:l}=await Es({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(fe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Ag(s,d=>console.log(d))||(console.log(fe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ne(l=>{ce(l,"channels.whatsapp.enabled",!0),ce(l,"channels.whatsapp.sessionDir",n),ce(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(fe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(fe.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(fe.dim(` Session: ${n}`)),console.log(fe.dim(" Start the daemon to begin receiving:")),console.log(fe.dim(" agentx daemon start")),console.log(fe.dim(" Add routes later with:")),console.log(fe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Ig}from"crypto";import $e from"chalk";import wa from"prompts";var kn="agentx-mesh:",vn="//join/";function Og(e){return Buffer.from(e,"utf-8").toString("base64url")}function jg(e){return Buffer.from(e,"base64url").toString("utf-8")}function Rg(e){return`${kn}${vn}${Og(JSON.stringify(e))}`}function Cg(e){if(!e.startsWith(`${kn}${vn}`))throw new Error(`Not a mesh invite link \u2014 expected ${kn}${vn}\u2026`);let o=e.slice(kn.length+vn.length),t=JSON.parse(jg(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 Tg(){return Ig(32).toString("hex")}function Ng(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function _g(e){return e?.node?.name||e?.node?.id||"node"}async function ba(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($e.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Ss("MESH_TOKEN");r||(r=Tg(),Po("MESH_TOKEN",r),console.log($e.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ng(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:g}=await wa({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://"});g||(console.log($e.red(" Aborted")),process.exit(1)),a=g}let l=await ne(g=>{ce(g,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log($e.red(` \u2717 ${l.error}`)),process.exit(1));let d=Rg({url:a,token:r,name:_g(i),version:1});console.log(),console.log($e.bold(" Mesh invite")),console.log(),console.log(` ${$e.cyan(d)}`),console.log(),console.log($e.dim(" Run on the other node:")),console.log($e.dim(` agentx connect mesh join "${d}"`)),console.log(),console.log($e.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function $a(e,o={}){let t;try{t=Cg(e)}catch(i){console.log($e.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Ss("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await wa({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log($e.red(" Aborted (keeping existing .env)")),process.exit(1))}Po("MESH_TOKEN",t.token);let s=await ne(i=>{ce(i,"mesh.enabled",!0);let r=Ao(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),ce(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log($e.red(` \u2717 ${s.error}`)),process.exit(1)),console.log($e.green(" \u2713 Joined mesh")),console.log($e.dim(` Peer: ${t.name} @ ${t.url}`)),console.log($e.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log($e.dim(" Daemon hot-reloaded.")):console.log($e.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($e.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log($e.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log($e.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Lo=new Dg().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Lo.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 ma({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Lo.command("discord").description("pair a Discord bot \u2014 verify token, emit install URL, save to .env").option("--agent <id>","agent to bind the bot to").option("-c, --config <path>","path to agentx.json").action(async e=>{await fa({agent:e.agent,configPath:e.config})});Lo.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 ya({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var ka=Lo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");ka.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 ba({url:e.url,configPath:e.config})});ka.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 $a(e,{configPath:o.config})});Lo.action(()=>{console.log(),console.log(Mo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Mo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Mo.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${Mo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Mo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Mo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Mo.dim(" GitLab connect is the next slice.")),console.log()});Te();import{Command as Pg}from"commander";import de from"chalk";var Nt=new Pg().name("usage").description("token usage analysis and reporting");Nt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=H(),[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(de.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(de.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${de.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: ${de.red(String(s.totalErrors))}`),console.log(),console.log(de.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),d=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${de.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${de.dim(d)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(de.red(" Daemon not running. Start with: agentx daemon start")):console.log(de.red(` ${e.message}`))}});Nt.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(de.red(` Script not found: ${s}`)),console.log(de.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(de.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(de.red(" Analysis failed. Is Python 3 installed?"))}});Nt.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-NS74AXSE.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-YGXVCV2Y.js"),r=await i(),a=new Set(n.filter(g=>g.kind==="cli").map(g=>g.name)),c=[],l=(g,u)=>{for(let p of g.commands??[]){let f=u?`${u} ${p.name()}`:p.name();c.push(f),l(p,f)}};l(r,"");let d=c.filter(g=>!a.has(g)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:d},null,2));return}console.log(),console.log(de.bold(` Never used in the last ${e.days} days (${d.length}/${c.length})`)),console.log();for(let g of d)console.log(` ${de.dim("\xB7")} ${g}`);console.log(),console.log(de.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(de.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(de.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(de.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(de.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(de.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=de.dim(`${i.days}d`);console.log(` ${de.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(de.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Mg}from"commander";import he from"chalk";import{resolve as Lg}from"path";Te();var bo=new Mg().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");bo.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{di(Lg(process.cwd(),".env"))}catch{}let o=Ug(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-TTMAYRLG.js");t(o)}catch(o){console.log(he.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(he.dim(o.stack)),process.exit(1)}});function Ug(e,o){try{let t=H();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(he.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(he.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
305
|
+
`)),{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}}}}bo.command("list").description("list configured boards").action(()=>{try{let e=H();if(!e.boards?.length){console.log(he.dim(`
|
|
306
|
+
No boards configured.
|
|
307
|
+
`));return}console.log();for(let o of e.boards){console.log(` ${he.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(he.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(he.dim(` primary label: ${o.primaryToolLabel}`)),console.log(he.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(he.red(` ${e.message}`)),process.exit(1)}});bo.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{_t(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(he.red(` ${t.message}`)),process.exit(1)}});bo.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{_t(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(he.red(` ${t.message}`)),process.exit(1)}});var Os=bo.command("column").description("manage a board's columns (add / remove / edit / list)");Os.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(gc("fs").readFileSync("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(he.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(` ${he.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${he.dim(i)}`)}}catch(o){console.log(he.red(` ${o.message}`)),process.exit(1)}});Os.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{_t(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(he.red(` ${n.message}`)),process.exit(1)}});Os.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{_t(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(he.red(` ${t.message}`)),process.exit(1)}});bo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{_t(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(he.red(` ${o.message}`)),process.exit(1)}});function _t(e){let{summary:o,backupPath:t}=Vo(n=>e(n));console.log(he.green(`
|
|
308
|
+
\u2713 ${o}
|
|
309
|
+
`)),t&&console.log(he.dim(` Backup: ${t}`)),console.log(he.dim(` Restart the dashboard to pick up the change if not auto-reloading.
|
|
310
|
+
`))}import{Command as Fg}from"commander";import m from"chalk";import{resolve as F,relative as va,dirname as xa}from"path";import{execSync as Uo}from"child_process";import{writeFileSync as Fo,mkdirSync as io,readFileSync as Dt,readdirSync as qg,renameSync as xn,rmSync as Wg,existsSync as Fe}from"fs";function ke(e,o){return new qn(Pt(e),void 0,o||"graph")}function Pt(e){return e||F(process.cwd(),".agentx/wiki")}function Rs(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Z=new Fg().name("wiki").description("wiki knowledge base management");Z.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let o=e.mode,t=ke(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Rs(o)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(m.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});Z.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let o=ke(e.dir,e.mode),t=e.agent?[e.agent]:o.listAgents(),n=0;console.log();for(let s of t){let r=o.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${m.cyan(s)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(s)}: ${m.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${m.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});Z.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").action(async e=>{let o=e.mode,t=ke(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=F(process.cwd(),".agentx/graph");return Fe(u)?new co({baseDir:u}):null}catch{return null}})(),r=new Map;if(i)try{let u=i.loadIndex();for(let[p,f]of Object.entries(u.entries))r.set(p,f.path)}catch{}let a,c=u=>{let p=u.meta?.intentPath;if(Array.isArray(p)&&p.every(y=>typeof y=="string")&&p.length>0)return p;if(!i||r.size===0)return;let f=String(u.meta?.sender??""),w=i.fingerprint({text:u.content,channel:u.source,sender:f});return r.get(w)},l=(u,p)=>{let f=new Map;for(let y of u){let k=p.find(v=>v.id===y);if(!k)continue;let b=c(k);if(!b?.length)continue;let x=b.join("/"),A=f.get(x);A?A.n++:f.set(x,{path:b,n:1})}if(f.size===0)return;let w;for(let y of f.values())(!w||y.n>w.n)&&(w=y);return w?.path},d=0,g=0;for(let u of n){let p=typeof e.since=="string"?e.since.trim():"",f=t.getUnabsorbedEntries(u).filter($=>!p||($.date??"")>=p).slice(0,s);if(f.length===0){console.log(` ${m.cyan(u)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(u)}: ${f.length} entries to absorb`));for(let $ of f.slice(0,3))console.log(m.dim(` [${$.date} via ${$.source}] ${$.content.slice(0,80)}...`));if(f.length>3&&console.log(m.dim(` ... and ${f.length-3} more`)),e.dryRun)continue;let w=t.getAgentWiki(u),y=w.rebuildIndex(),k=w.getWorldview()||t.getSharedStore().getWorldview()||"",b=f.map($=>`--- ENTRY ${$.id} [${$.date} ${$.agentId} via ${$.source}] ---
|
|
311
|
+
${$.content}
|
|
312
|
+
--- END ENTRY ---`).join(`
|
|
313
|
+
|
|
314
|
+
`),x="";if(e.facts!==!1){let{extractHints:$,resolveFacts:T,mergeRecords:R,renderFactsBlock:j,installPrompts:D,defaultSources:q,recordsFromEntries:P}=await import("./facts-YVEJOM7O.js");if(!a){let W=new Set;for(let ve of t.listAgents())for(let ye of t.getAgentWiki(ve).listArticles(ve))ye.meta.type==="person"&&W.add(ye.meta.title);a=[...W]}let J=$(f.map(W=>({context:W.sourceContext,content:W.content,sender:typeof W.meta?.sender=="string"?W.meta.sender:void 0})),{known:a}),ae=P(f);if(J.length>0||ae.length>0){let W=q(),{records:ve,results:ye}=J.length>0?await T(J,{sources:W}):{records:[],results:[]},_=R([...ae,...ve]);x=j(_);let Me=[...ae.length>0?[`entries:${ae.length}`]:[],...ye.filter(we=>we.records.length>0).map(we=>`${we.source}:${we.records.length}`)];console.log(m.dim(` Facts: ${J.length} entities \u2192 ${_.length} resolved${Me.length?` (${Me.join(" ")})`:""}`));for(let we of D(ye,W))console.log(m.yellow(` ! ${we.source} ${we.kind} \u2014 would supply ${we.provides.join(", ")}`)),console.log(m.dim(` ${we.hint}`))}}let A=Oi(o,u,k,y.articles,b,f.length,x);console.log(m.dim(` Mode: ${Rs(o)}`));let v=F(w.baseDir,"_tmp");io(v,{recursive:!0});let E=F(v,"absorb-prompt.txt");Fo(E,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=Uo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ho({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(_){if($=_.stdout||"",!$)throw _}let T=$;try{let _=JSON.parse($);T=_.result||_.content||"",T||(console.log(m.dim(` Claude envelope keys: ${Object.keys(_).join(", ")}`)),console.log(m.dim(` is_error: ${_.is_error}, stop_reason: ${_.stop_reason}`)))}catch{}let R,j=[],D=T.indexOf("{"),q=T.indexOf("["),P=D>=0&&(q<0||D<q)?D:q;if(P===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(T.slice(0,500)));continue}let J=T[P],ae=J==="{"?"}":"]",W=0,ve=-1;for(let _=P;_<T.length;_++)if(T[_]===J)W++;else if(T[_]===ae&&(W--,W===0)){ve=_+1;break}if(ve===-1){console.log(m.red(" Unbalanced JSON"));continue}let ye=T.slice(P,ve);try{let _=JSON.parse(ye);Array.isArray(_)?R=_:(R=_.articles||[],j=_.gaps||[])}catch(_){console.log(m.red(` JSON parse error: ${_.message}`)),console.log(m.dim(` First 300 chars: ${ye.slice(0,300)}`));continue}for(let _ of R){let Me=new Date().toISOString().slice(0,10),we=l(_.sources||[],f);w.writeArticle(_.path,{title:_.title,type:_.type,related:Array.isArray(_.related)?_.related:void 0,tags:_.tags||[],owner:u,access:"public",created:Me,lastUpdated:Me,sources:_.sources||[],graphPath:we},_.content,u);let So=_.type?m.magenta(`[${_.type}]`)+" ":"",C=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${So}${_.path}: ${_.title}${m.dim(C)}`);let pe=(_.tags||[]).slice(0,4).join(", ");pe&&console.log(m.dim(` tags: ${pe}`)),we?.length&&(console.log(m.dim(` graphPath: ${we.join(" \u203A ")}`)),g++),d++}if(j.length>0){console.log(),console.log(m.yellow(` Gaps detected (${j.length} missing pieces):`));for(let _ of j)console.log(m.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),Me=new _(Pt(e.dir)).add(j.map(we=>({kind:"article",agentId:u,path:"",subject:String(we).slice(0,120),question:`No article yet for: ${String(we).slice(0,160)}`})));Me.added>0&&console.log(m.dim(` queued ${Me.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch($){console.log(m.red(` Absorb failed: ${$.message?.slice(0,200)}`)),$.stderr&&console.log(m.dim(String($.stderr).slice(0,300))),$.stdout&&console.log(m.dim("stdout: "+String($.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(d>0&&(console.log(m.green(` ${d} articles compiled across ${n.length} agent(s)`)),i)){let u=d>0?Math.round(g/d*100):0;console.log(m.dim(` ${g}/${d} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Z.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--commit","write articles and ledger (default: dry-run)",!1).action(async e=>{let o=Bg(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-AEUXRQQC.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Fe(l))console.log(m.yellow(` --reviews: no ${l}`));else{let d=new c(l,{readonly:!0});try{let g=d.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(g,{kinds:String(e.reviewKinds).split(",").map(f=>f.trim()).filter(Boolean)});let u=i.filter(f=>(f.occurrences??1)>1).length;console.log(m.dim(` ${g.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let p=i[0];p&&(p.occurrences??1)>1&&console.log(m.dim(` most recurrent (${p.occurrences} sessions): ${p.memory.description.slice(0,84)}`))}finally{d.close()}}}let r=await ji({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,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 promote")),console.log();return}for(let a of r.written){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=a.related?.length?` \u2192 ${a.related.slice(0,3).join(", ")}${a.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${c}${a.path}: ${a.title}${m.dim(l)}`),console.log(m.dim(` from: ${a.stamps.join(", ")}`))}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.written.length} promoted, ${r.errors.length} error(s)`):m.green(` ${r.written.length} promoted, ${r.skipped.length} skipped`)),console.log(),r.errors.length&&process.exit(1)});function Bg(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Z.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",F(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:o}=await import("./query-ZKTFJMNE.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ke(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),d=parseInt(e.n),g=i(e.history,c);if(!s(g)){console.log(m.yellow(` no task-history at ${g}`));return}let u=[],p=t(g).sort().reverse();for(let y of p){let k=r(g,y),b=[];try{b=t(k).filter(x=>x.endsWith(".json")).sort().reverse()}catch{continue}for(let x of b){if(u.length>=d)break;try{let A=JSON.parse(n(r(k,x),"utf-8")),v=A.message||A.task?.message;typeof v=="string"&&v.trim().length>10&&u.push({id:A.id||x.replace(".json",""),message:v.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=d)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${g}`));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 f=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<u.length;y++){let k=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let x=l.findRelevant(k.message,c,3).map(v=>`- **${v.meta.title}** [${v.meta.type||"?"}] (${v.path})`).join(`
|
|
315
|
+
`)||"_(none returned)_",A;try{let v=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(v.status!=="ok")A=`_(status: ${v.status}${v.error?" \u2014 "+v.error:""})_`;else{let E=v.citations.map($=>`\`${$.title}\` [${$.type||"?"}]`).join(", ");A=`**Answer:**
|
|
316
|
+
|
|
317
|
+
${v.answer}
|
|
318
|
+
|
|
319
|
+
**Citations:** ${E}`}}catch(v){A=`_(error: ${v.message})_`}console.log(m.dim("done")),f.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",x,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=f.join(`
|
|
320
|
+
`);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});Z.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'Globex deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-OIFU3KSQ.js"),s=e.answers?Dt(e.answers,"utf-8").split(/\r?\n/).filter(C=>C.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=ke(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(C){console.log(m.red(` can't open wiki for agent "${e.agent}": ${C.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async C=>{if(s){let pe=s[i++]??"";return process.stdout.write(C+m.dim(`[scripted] ${pe.slice(0,80)}${pe.length>80?"\u2026":""}`)+`
|
|
321
|
+
`),pe.trim()}return(await c.question(C)).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 d=e.topic||"";if(!d&&(d=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!d||d==="/abort")){c?.close();return}let g=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(g)){console.log(m.dim(` Types: ${n.join(" | ")}`));let C=await l(m.cyan(" Type? "));if(C==="/abort"){c?.close();return}u.has(C)?g=C:(console.log(m.yellow(` "${C}" isn't a valid type. Falling back to "concept".`)),g="concept")}let p={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?"]},f=p[g]||p.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(d)} \xB7 Type: ${m.magenta(g)}`)),console.log(m.dim(` ${f.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let C=0;C<f.length;C++){let pe=f[C],qe=await l(` ${m.dim(`[${C+1}/${f.length}]`)} ${pe}
|
|
322
|
+
${m.green(">")} `);if(qe==="/abort"){y=!0;break}if(qe==="/done")break;qe!=="/skip"&&qe&&w.push({q:pe,a:qe})}if(!y){let C=await l(`
|
|
323
|
+
${m.dim("Anything else worth capturing?")}
|
|
324
|
+
${m.green(">")} `);C&&C!=="/abort"&&C!=="/done"&&w.push({q:"Anything else worth capturing?",a:C})}if(y||w.length===0){console.log(m.yellow(`
|
|
325
|
+
Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(C=>`- ${C.meta.title} [${C.meta.type||"?"}]`).join(`
|
|
326
|
+
`),x=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${d}`,`**Type:** ${g}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(C=>`
|
|
327
|
+
Q: ${C.q}
|
|
328
|
+
A: ${C.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\`: ${g}`,' - `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(`
|
|
329
|
+
`),A=F(a.baseDir,"_tmp");io(A,{recursive:!0});let v=F(A,`interview-${t().slice(0,8)}.txt`);Fo(v,x),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let E="";try{let C=`cat '${v}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,pe=Uo(C,{env:Ho({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let qe=JSON.parse(pe);E=String(qe.result||qe.content||"")}catch{E=pe}}catch(C){console.log(m.red(` synthesis failed: ${C.message?.slice(0,200)}`)),c?.close();return}E=E.trim();let $=E.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(E=$[1].trim());let T=E.indexOf("---");T>0&&(E=E.slice(T));let R=E.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!R){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(E.slice(0,600)),c?.close();return}let j={};for(let C of R[1].split(`
|
|
330
|
+
`)){let pe=C.match(/^(\w+):\s*(.+)$/);pe&&(j[pe[1]]=pe[2].trim().replace(/^"(.*)"$/,"$1"))}let D=R[2],q=j.title||d,P=q.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ae=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[g]||g+"s"}/${P}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${ae}`)),console.log(),console.log(E),console.log();let W=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),W==="scrap"||W==="/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 ${v} (prompt only; no article file)`));return}let ve=D,ye={title:q,type:j.type||g,related:j.related?j.related.replace(/^\[|\]$/g,"").split(",").map(C=>C.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:j.tags?j.tags.replace(/^\[|\]$/g,"").split(",").map(C=>C.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(W==="edit"){let C=process.env.EDITOR||"vi",pe=F(A,`draft-${t().slice(0,8)}.md`);Fo(pe,E);try{Uo(`${C} '${pe}'`,{stdio:"inherit"});let Ln=Dt(pe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Ln){let ao={};for(let ft of Ln[1].split(`
|
|
331
|
+
`)){let Un=ft.match(/^(\w+):\s*(.+)$/);Un&&(ao[Un[1]]=Un[2].trim().replace(/^"(.*)"$/,"$1"))}ve=Ln[2],ye={...ye,title:ao.title||ye.title,type:ao.type||ye.type,access:ao.access||ye.access,related:ao.related?ao.related.replace(/^\[|\]$/g,"").split(",").map(ft=>ft.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ye.related,tags:ao.tags?ao.tags.replace(/^\[|\]$/g,"").split(",").map(ft=>ft.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ye.tags}}}catch(qe){console.log(m.red(` editor failed: ${qe.message}`));return}}if(!a.writeArticle(ae,ye,ve,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${ae} saved.`));let Me=a.extractWikilinks(ve),we=new Map;for(let C of a.listArticles(e.agent))we.set(C.meta.title.toLowerCase(),!0);let So=Me.filter(C=>!we.has(C.toLowerCase()));if(So.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let C of So.slice(0,8))console.log(m.dim(` - ${C}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-ZKTFJMNE.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ke(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(p){console.log(m.red(` can't open wiki for agent "${e.agent}": ${p.message}`));return}let r=null;if(e.script){let f=Dt(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of f){let y=w.split(/\r?\n/).filter(x=>x.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async p=>a?(await a.question(p)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),d=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${d?"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 g=[],u=0;for(let p=0;p<l;p++){let f,w;if(r){let J=r[p];if(!J)break;f=J.q,w=J.verdict,console.log(m.cyan(` [${p+1}] Q: `)+f)}else{if(f=await c(m.cyan(` [${p+1}] Q: `)),!f||f==="/done"||f==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(f,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(J){console.log(m.red(`failed: ${J.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let J=y.citations.map(ae=>`${ae.title} [${ae.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
332
|
+
`)),console.log(m.dim(" citations: "+J))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let k={q:f,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),g.push(k);continue}let x=b[1].toLowerCase(),A=(b[2]||"").trim();if(g.push(k),x==="/ok"||x==="/skip")continue;if(!A){console.log(m.yellow(` ${x} without note \u2014 skipping.`));continue}let v=y.citations[0];if(!v){console.log(m.yellow(" no cited article to patch."));continue}let E=i.readArticle(v.path);if(!E){console.log(m.red(` can't read ${v.path} to patch.`));continue}console.log(m.dim(` patching ${v.title} (${v.path})...`));let $=Hg(E.content,x,A,E.meta.title,E.meta.type),T=F(i.baseDir,"_tmp");io(T,{recursive:!0});let R=F(T,`quiz-patch-${t().slice(0,8)}.txt`);Fo(R,$);let j="";try{let J=`cat '${R}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ae=Uo(J,{env:Ho({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let ve=JSON.parse(ae);j=String(ve.result||ve.content||"")}catch{j=ae}let W=j.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);W&&(j=W[1].trim()),j=j.trim()}catch(J){console.log(m.red(` patch failed: ${J.message?.slice(0,120)}`));continue}if(!j||j.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=E.content.split(`
|
|
333
|
+
`).length,q=j.split(`
|
|
334
|
+
`).length;if(console.log(m.dim(` diff: ${D} \u2192 ${q} lines (${q-D>=0?"+":""}${q-D})`)),!d){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=v.path+" (dry)";continue}if(!i.writeArticle(v.path,{...E.meta,lastUpdated:new Date().toISOString().slice(0,10)},j,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=v.path,console.log(m.green(` \u2713 patched ${v.path}`))}if(a&&a.close(),u>0&&d&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${g.length} rounds, ${u} patches applied.`)),e.out){let p=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${g.length} rounds \xB7 ${u} patches_`,""];for(let f=0;f<g.length;f++){let w=g[f];p.push(`## ${f+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}Fo(e.out,p.join(`
|
|
335
|
+
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});Z.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,o,t)=>{let n=ke(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=Aa(s,o,e);if(!i){console.log(m.yellow(` no article matches "${o}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=F(s.baseDir,i),a=t.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${i} in ${a}...`));try{Uo(`${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,d=s.extractWikilinks(c.content).filter(p=>l.has(p)?!1:(l.add(p),!0)),g=c.meta.related||[];(d.some(p=>!g.includes(p))||g.some(p=>!d.includes(p)))&&(s.writeArticle(i,{...c.meta,related:d.length?d:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${d.length} wikilink${d.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});Z.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,o,t,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ke(n.dir),a;try{a=r.getAgentWiki(e)}catch(v){console.log(m.red(` can't open wiki for agent "${e}": ${v.message}`));return}let c=Aa(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 d=Jg(l.content,l.meta.title,l.meta.type,t),g=F(a.baseDir,"_tmp");io(g,{recursive:!0});let u=F(g,`patch-${i().slice(0,8)}.txt`);Fo(u,d),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let p="";try{let v=`cat '${u}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,E=Uo(v,{env:Ho({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let T=JSON.parse(E);p=String(T.result||T.content||"")}catch{p=E}let $=p.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);$&&(p=$[1].trim()),p=p.trim()}catch(v){console.log(m.red(` patch failed: ${v.message?.slice(0,150)}`));return}if(!p||p.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let f=l.content.split(`
|
|
336
|
+
`).length,w=p.split(`
|
|
337
|
+
`).length;if(console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${f} \u2192 ${w} lines (${w-f>=0?"+":""}${w-f})`)),console.log(),console.log(p),console.log(),!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let v=s.createInterface({input:process.stdin,output:process.stdout}),E=(await v.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();v.close(),y=E==="y"||E==="yes"}if(!y){console.log(m.dim(" aborted."));return}let k=new Set,b=a.extractWikilinks(p).filter(v=>k.has(v)?!1:(k.add(v),!0));if(!a.writeArticle(c,{...l.meta,related:b.length?b:void 0,lastUpdated:new Date().toISOString().slice(0,10)},p,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex();let A=(l.meta.related||[]).filter(v=>!b.includes(v));A.length&&console.log(m.dim(` (pruned stale related: ${A.slice(0,3).join(", ")}${A.length>3?", \u2026":""})`)),console.log(m.green(` \u2713 ${c} patched.`))});function Aa(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`,d=s.find(g=>g.path===l||g.path===n);if(d)return d.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let d=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return d===a||d.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function Jg(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(`
|
|
338
|
+
`)}function Hg(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
|
|
339
|
+
|
|
340
|
+
${t}
|
|
341
|
+
|
|
342
|
+
Edit the article to correct ONLY this mistake. Do not rewrite untouched sections. Keep the existing prose style. If the correction invalidates a larger passage, revise the minimum that must change.`,"/add":`The operator wants to add this detail:
|
|
343
|
+
|
|
344
|
+
${t}
|
|
345
|
+
|
|
346
|
+
Incorporate it into the most relevant existing section, or create a short new section if nothing fits. Keep the prose encyclopedic and under 100 additional words.`,"/link":`The operator wants to add this resource:
|
|
347
|
+
|
|
348
|
+
${t}
|
|
349
|
+
|
|
350
|
+
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(`
|
|
351
|
+
`)}Z.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=!!e.commit,s=e.dir?F(e.dir):F(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(m.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(m.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,d=0;for(let g of t){let u=F(s,"agents",g);if(!Fe(u))continue;let p=F(u,i),f=r.map(b=>({mode:b,dir:F(u,b)})).filter(b=>Fe(b.dir));if(f.length===0)continue;let w=new Map;js(p,b=>{let x=va(p,b);if(x.startsWith("_")||x.startsWith("raw/")||x.includes("_tmp/"))return;let A=Sa(Dt(b,"utf-8"));A?.meta.title&&w.set(A.meta.title.trim().toLowerCase(),{relPath:x,type:A.meta.type,lastUpdated:A.meta.lastUpdated||""})});let y=[];for(let b of f)js(b.dir,x=>{let A=va(b.dir,x);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let v=Sa(Dt(x,"utf-8"));v?.meta.title&&y.push({mode:b.mode,relPath:A,absPath:x,title:v.meta.title.trim(),type:v.meta.type,lastUpdated:v.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=f.map(b=>b.mode).join("+");console.log(m.bold(` ${m.cyan(g)}: ${y.length} legacy article(s) across ${k}`));for(let b of y){let x=b.title.toLowerCase(),A=w.get(x),v;A?!A.type&&b.type||!!A.type==!!b.type&&b.lastUpdated&&A.lastUpdated&&b.lastUpdated>A.lastUpdated?v="upgrade":v="archive":v="promote";let E=b.type?m.magenta(`[${b.type}]`):m.yellow("[untyped]"),$=v==="promote"?m.green("\u2192 promote "):v==="upgrade"?m.cyan("\u27F3 upgrade "):m.dim("\u2717 archive "),T=b.relPath.length>46?b.relPath.slice(0,43)+"...":b.relPath.padEnd(46);if(console.log(` ${$} ${E} ${m.dim(b.mode+"/")}${T}`),v==="upgrade"&&console.log(m.dim(` (replaces ${A.relPath}, old version kept under _versions/)`)),!n){v==="promote"?c++:v==="upgrade"?l++:d++;continue}try{if(v==="promote"){let R=F(p,b.relPath);Fe(R)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Ea(u,b),d++):(io(xa(R),{recursive:!0}),xn(b.absPath,R),w.set(x,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(v==="upgrade"){let R=F(p,A.relPath);if(Fe(R)){let j=F(u,"_versions",A.relPath.replace(/\.md$/,""));io(j,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");xn(R,F(j,`${D}.md`))}io(xa(R),{recursive:!0}),xn(b.absPath,R),w.set(x,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else Ea(u,b),d++}catch(R){console.log(m.red(` ! ${v} failed: ${R.message?.slice(0,120)}`))}}if(n){for(let b of f)try{Wg(b.dir,{recursive:!0,force:!0})}catch{}try{o.getAgentWiki(g).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: ${d}`)),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 ${d}`)),console.log(m.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function js(e,o){if(Fe(e))for(let t of qg(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?js(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Sa(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
|
|
352
|
+
`)){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 Ea(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));io(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");xn(o.absPath,F(t,`${n}.md`))}Z.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let o=ke(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 d=o.getAgentWiki(l),g=d.listArticles(l),u=g.filter(k=>!k.meta.type);if(r+=g.length,a+=u.length,u.length===0){console.log(` ${m.cyan(l)}: ${m.green("all typed")} (${g.length} articles)`);continue}let p=Math.max(0,s-c),f=Math.min(u.length,p);if(f===0){console.log(m.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(m.bold(` ${m.cyan(l)}: ${f}/${u.length} untyped articles`));let w=d.baseDir,y=F(w,"_tmp");io(y,{recursive:!0});for(let k=0;k<f;k+=n){let b=u.slice(k,Math.min(k+n,f)),x=Gg(b),A=F(y,"migrate-prompt.txt");Fo(A,x);let v;try{let E=`cat '${A}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$=Uo(E,{env:Ho({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),T=JSON.parse($),j=String(T.result||T.content||"").match(/\[[\s\S]*\]/);if(!j)throw new Error("no JSON array in classifier response");v=JSON.parse(j[0])}catch(E){console.log(m.red(` LLM classify failed: ${E.message?.slice(0,150)}`));continue}for(let E of b){let $=v.find(P=>P.path===E.path),T=zg($?.type);if(!$||!T){console.log(m.yellow(` ? ${E.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let R=d.extractWikilinks(E.content),j={...E.meta,type:T.type,related:R.length?R:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=R.length?m.dim(` \u2192 ${R.slice(0,3).join(", ")}${R.length>3?", \u2026":""}`):"",q=T.alias?m.dim(` (from "${T.alias}")`):"";console.log(` ${m.green("+")} ${m.magenta("["+T.type+"]")}${q} ${E.path}${D}`),i&&(d.writeArticle(E.path,j,E.content,l),c++)}}i&&d.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 zg(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 Gg(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}"
|
|
353
|
+
title: "${t.meta.title}"
|
|
354
|
+
tags: [${i}]
|
|
355
|
+
body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
|
|
356
|
+
|
|
357
|
+
`);return`Classify each of these ${e.length} wiki articles into EXACTLY ONE type from this closed set (no synonyms, no plurals, no new values):
|
|
358
|
+
|
|
359
|
+
person | project | place | concept | event | decision | pattern
|
|
360
|
+
|
|
361
|
+
What each type means:
|
|
362
|
+
- person: an individual human (team member, stakeholder, contact)
|
|
363
|
+
- project: a named initiative, repo, product, service, bot, agent, team, or org
|
|
364
|
+
- place: a physical or logical location (office, server, environment, infrastructure)
|
|
365
|
+
- concept: a recurring idea, philosophy, methodology, or thinking pattern
|
|
366
|
+
- event: a specific dated thing that happened (incident, deploy, launch, GitLab issue, MR)
|
|
367
|
+
- decision: a specific choice made and why (architecture decision, policy, ADR)
|
|
368
|
+
- pattern: a reusable workflow, template, recipe, procedure, runbook, or SOP
|
|
369
|
+
|
|
370
|
+
Explicit mappings (you WILL be tempted to volunteer these \u2014 don't; use the right-hand value):
|
|
371
|
+
- "agent" / "bot" / "service" / "repo" / "team" \u2192 project
|
|
372
|
+
- "issue" / "MR" / "ticket" / "incident" / "deploy" \u2192 event
|
|
373
|
+
- "process" / "procedure" / "runbook" / "workflow" \u2192 pattern
|
|
374
|
+
- "infrastructure" / "server" / "environment" \u2192 place
|
|
375
|
+
- "ADR" / "decision record" \u2192 decision
|
|
376
|
+
|
|
377
|
+
Rules:
|
|
378
|
+
- Return EXACTLY one type per article, by path, from the 7 allowed values above.
|
|
379
|
+
- Do not invent new types. Do not return plurals. Do not return synonyms.
|
|
380
|
+
- If the title is a person's name, it's person. If it's a repo/product/bot name, it's project. If it's dated + past tense, it's event.
|
|
381
|
+
- If you genuinely cannot decide, pick "concept" as the fallback.
|
|
382
|
+
- Output ONLY valid JSON, no markdown fencing, no prose.
|
|
383
|
+
|
|
384
|
+
Articles:
|
|
385
|
+
|
|
386
|
+
${o}
|
|
387
|
+
|
|
388
|
+
Output (JSON array, one entry per input article, same order):
|
|
389
|
+
[
|
|
390
|
+
{"path": "path/to/article.md", "type": "project"},
|
|
391
|
+
...
|
|
392
|
+
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ke(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});Z.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-HL5F36V4.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(),er(o,t,e.agent,n,e.mode)});Z.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-44ONVGLN.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-VZ7AVO27.js"),c=ke(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),d=parseInt(e.limit),g=parseFloat(e.min),u=[];e:for(let y of l){let k=c.getAgentWiki(y);for(let b of k.listArticles(y)){if(u.length>=d)break e;let x=k.readArticle(b.path);if(!x||e.type&&x.meta.type!==e.type)continue;let A={...o(x.meta.type),...e.fields?i(x.meta.type):{}},v=await a(s,t({path:b.path,title:x.meta.title,type:x.meta.type,tags:x.meta.tags,body:x.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:x.meta.type??"?"}});if(!v){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let E=n(v.answers),$=e.fields?r(x.meta.type,v.answers):null;E.completeness>=g&&!($&&!$.fit)||u.push({agent:y,type:x.meta.type??"?",score:E.completeness.toFixed(2),standsAlone:E.standsAlone.toFixed(2),gap:E.biggestGap,...$?{missing:$.missingCritical.join(",")||"-",cov:`${Math.round($.coverage*100)}%`}:{},title:x.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((y,k)=>parseFloat(y.score)-parseFloat(k.score));let p=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],f=p.map(y=>Math.max(y.length,...u.map(k=>String(k[y]).length))),w=y=>y.map((k,b)=>String(k).padEnd(f[b])).join(" ");console.log(),console.log(m.bold(w(p)));for(let y of u)console.log(w(p.map(k=>y[k])));if(e.fields){let y=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
|
|
393
|
+
${u.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
|
|
394
|
+
${u.length} article(s) below ${g}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});Z.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-ZKTFJMNE.js"),n=ke(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),d=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(d)){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(d=>d.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Z.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,o)=>{let t=ke(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});Z.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ke(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Fe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new co({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[g,u]of Object.entries(i.entries))r.set(g,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,d=0;for(let g of t){let u=o.getAgentWiki(g),p=u.listArticles(g),f=o.getSharedStore().listEntries(),w=new Map(f.map(x=>[x.id,x])),y=0,k=0,b=0;for(let x of p){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,c++;let A=new Map;for(let E of x.meta.sources){let $=w.get(E);if(!$)continue;let T=String($.meta?.sender??""),R=s.fingerprint({text:$.content,channel:$.source,sender:T}),j=r.get(R);if(!j?.length)continue;let D=j.join("/"),q=A.get(D);q?q.n++:A.set(D,{path:j,n:1})}if(A.size===0)continue;k++,l++;let v;for(let E of A.values())(!v||E.n>v.n)&&(v=E);v&&(e.dryRun||(u.writeArticle(x.path,{...x.meta,graphPath:v.path},x.content,g),b++,d++))}console.log(` ${m.cyan(g)}: ${m.bold(p.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${d} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ke(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-HL5F36V4.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||[],d=c.nodeId||"unknown";console.log(m.dim(` Node: ${d} \u2014 ${l.length} entries`));let g=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}@${d}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),g++);g>0?console.log(m.green(` ${g} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=g;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let p=await u.json();for(let f of p.agents||[])f.totalEntries>0&&console.log(m.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});Z.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||F(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new qn(o,void 0,c),g=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),p=l.getUnabsorbedEntries(t),f=new Set,w=0,y=new Set;for(let b of g.articles){for(let x of b.tags||[])f.add(x);w+=b.tags?.length||0;for(let x of b.sources||[])y.add(x)}let k=new Set(g.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Rs(c),articles:g.articles.length,entries:u.length,unabsorbed:p.length,uniqueTags:f.size,avgTags:g.articles.length>0?(w/g.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:g.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 d=s.map(g=>l(g).padEnd(i));console.log(` ${c.padEnd(20)} ${d.join(" ")}`)}console.log();let a=(c,l)=>{let d=Math.max(...s.map(u=>u[c])),g=s.filter(u=>u[c]===d).map(u=>u.label);d>0&&console.log(m.dim(` Best ${l}: ${g.join(", ")} (${d})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Z.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");Fe(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:d}=await import("fs"),g=Fe(s)?d(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Yg(g)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-L4D2BOGY.js"),{askSeat:a}=await import("./seat-VZ7AVO27.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),l=ke(e.dir,e.mode),d=[],g=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),p=0,f=[];e:for(let E of g){let $=l.getAgentWiki(E);for(let T of $.listArticles(E)){if(p>=u)break e;let R=$.readArticle(T.path);if(!R||e.type&&R.meta.type!==e.type)continue;p++;let j=await a(r,n({title:R.meta.title,type:R.meta.type,body:R.content}),o(R.meta.type),{links:[{kind:"article",id:T.path}],features:{agent:E,type:R.meta.type??"?"}});if(!j){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(R.meta.type,j.answers);for(let q of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&q.needsHuman||(e.ask&&q.needsHuman&&d.push({kind:"field",agentId:E,path:T.path,subject:R.meta.title,field:q.field,tier:q.tier,question:`${R.meta.title} (${R.meta.type??"?"}) \u2014 ${q.label}?`}),f.push({tier:q.tier,need:q.field,how:q.needsHuman?m.yellow("ask"):q.sources.join("/"),uncertain:q.uncertain?"?":"",agent:E,article:R.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&d.length>0&&(w=new c(Pt(e.dir)).add(d)),e.json){console.log(JSON.stringify(f,null,2));return}if(f.length===0){console.log(m.green(` ${p} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],k=E=>String(E).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(E=>Math.max(E.length,...f.map($=>k($[E]).length))),x=(E,$)=>String(E)+" ".repeat(Math.max(0,b[$]-k(E).length));console.log(),console.log(m.bold(y.map((E,$)=>x(E,$)).join(" ")));for(let E of f)console.log(y.map(($,T)=>x(E[$],T)).join(" "));let A=f.filter(E=>E.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${f.length} gap(s) across ${p} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${f.length-A} need a person.`));let v=f[0]?.tier;if(v&&console.log(m.dim(` Start at ${v} \u2014 ${i[v]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:E}=await import("./article-fields-L4D2BOGY.js"),$=E[e.notifyTier]??E.pillar,T=d.filter(R=>(E[R.tier??"furniture"]??9)<=$);if(T.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:R}=await import("./config-HL5F36V4.js"),j=R(),D=j?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let q=T.slice(0,10).map(W=>`\u2022 ${W.question}`).join(`
|
|
395
|
+
`),P=T.length>10?`
|
|
396
|
+
\u2026and ${T.length-10} more`:"",J=`${T.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
397
|
+
${q}${P}
|
|
398
|
+
|
|
399
|
+
agentx wiki questions`,ae=j?.daemon?.port??j?.port??18800;try{let W=await fetch(`http://127.0.0.1:${ae}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:J})});console.log(W.ok?m.cyan(` Pushed ${T.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${W.status}) \u2014 questions are still queued.`))}catch(W){console.log(m.yellow(` Push failed (${String(W?.message??W).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-L4D2BOGY.js"),{askSeat:r}=await import("./seat-VZ7AVO27.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:d,recordsFromEntries:g}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),p=ke(e.dir,e.mode),f=e.agent?[e.agent]:p.listAgents(),w=parseInt(e.limit),y=d(),k=c(g(p.getSharedStore().listEntries())),b=new Map(k.map(j=>[j.name.toLowerCase().trim(),j])),x=0,A=0,v=[],E=!1;e:for(let j of f){let D=p.getAgentWiki(j);for(let q of D.listArticles(j)){if(x>=w)break e;if(q.meta.type!=="person")continue;let P=D.readArticle(q.path);if(!P)continue;x++;let J=await r(s,n({title:P.meta.title,type:P.meta.type,body:P.content}),o(P.meta.type),{links:[{kind:"article",id:q.path}],features:{agent:j,op:"backfill"}});if(!J){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let W=t(P.meta.type,J.answers).missing.filter(C=>i.includes(C));if(W.length===0)continue;let{records:ve,results:ye}=await a([{name:P.meta.title,type:"person"}],{sources:y}),_=b.get(P.meta.title.toLowerCase().trim());if(!E){for(let C of l(ye,y))console.log(m.yellow(` ! ${C.source} ${C.kind} \u2014 would supply ${C.provides.join(", ")}`)),console.log(m.dim(` ${C.hint}`));E=!0}let Me=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([C,pe])=>[C,pe.value]))}]:[],...ve]);if(Me.length===0)continue;let{content:we,edits:So}=u(P.content,Me[0],W);if(So.length!==0){for(let C of So)v.push({agent:j,article:P.meta.title.slice(0,32),field:C.field,action:C.replaced?"replace":"add",got:`${C.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(q.path,P.meta,we,j)?A++:console.log(m.red(` could not write ${q.path}`)))}}}if(e.json){console.log(JSON.stringify(v,null,2));return}if(v.length===0){console.log(m.green(` ${x} person article(s) considered \u2014 nothing to backfill`));return}let $=["agent","article","field","action","got"],T=$.map(j=>Math.max(j.length,...v.map(D=>String(D[j]).length))),R=j=>j.map((D,q)=>String(D).padEnd(T[q])).join(" ");console.log(),console.log(m.bold(R($)));for(let j of v)console.log(R($.map(D=>j[D])));console.log(),e.apply?(console.log(m.green(` ${v.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${v.length} field(s) would be written across ${x} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:o}=await import("./questions-4B4KSPXG.js"),{TIER_RANK:t}=await import("./article-fields-L4D2BOGY.js"),n=new o(Pt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Z.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,o,t)=>{let{QuestionStore:n}=await import("./questions-4B4KSPXG.js"),{patchIdentityField:s}=await import("./backfill-MTD2B62I.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-L4D2BOGY.js"),r=new n(Pt(t.dir));if(t.dismiss){let p=r.resolve(e,"dismissed");console.log(p?m.dim(` dismissed: ${p.question}`):m.red(` no question matching "${e}"`));return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let a=r.resolve(e,"answered",o);if(!a){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${a.question}`)),a.kind!=="field"||!a.field||!a.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[a.field]){console.log(m.dim(` recorded against ${a.path}. "${a.field}" has no fixed slot, so nothing was rewritten.`));return}let l=ke(t.dir,t.mode).getAgentWiki(a.agentId),d=l.readArticle(a.path);if(!d){console.log(m.yellow(` article gone: ${a.path}`));return}let g=s(d.content,a.field,`${o} (answered by operator)`);if(!g){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=l.writeArticle(a.path,d.meta,g.content,a.agentId);console.log(u?m.green(` wrote ${a.field} into ${a.path} (prior version kept)`):m.red(` could not write ${a.path}`))});Z.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LK34TSQD.js"),{askSeat:i}=await import("./seat-VZ7AVO27.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:d}=await import("./triage-backtest-JNO7RKX7.js"),{calibrationReport:g}=await import("./calibration-ILS5OI44.js"),p=ke(e.dir,"graph").getSharedStore(),f=p.listEntries(),w=new Set(p.getUnabsorbedEntries().map(P=>P.id)),{labeled:y,backlog:k}=r(f,w),b=a(y,P=>P.absorbed,parseInt(e.n)),x={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],v=0,E=Date.now();if(e.load){let{readFileSync:P}=await import("fs");A.push(...JSON.parse(P(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let P of e.load?[]:b){let J=await i(o,n(P),t,{features:{source:P.source??"",absorbed:P.absorbed}});if(!J){v++;continue}let ae=J.answers;A.push({entry:P,verdict:s(J.answers,x),citeWorthy:ae.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:P}=await import("fs");P(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let $=c(A,{minType:x.minTypeConfidence,minWorth:x.minWorth,minDurability:x.minDurability}),T=l(A,"seat","seat"),R=g(T,{minN:50}),j=((Date.now()-E)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:R,failures:v,elapsed:j},null,2));return}let D=P=>`${(P*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${$.n} (${$.positives} kept by absorb, ${$.negatives} passed over)`),console.log(` recall ${D($.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D($.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D($.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${$.lostPositives>0?m.yellow(`lost ${$.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in R)||!R.insufficient)&&console.log(` ECE ${R.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),$.lostPositives>0){let P=$.droppedBy;console.log(m.dim(` dropped by: type ${P.type} \xB7 worth ${P.worth} \xB7 durability ${P.durability} (a positive can fail several)`))}let q=$.positiveMeans;if(console.log(m.dim(` positives avg: worth ${q.worth.toFixed(2)} \xB7 durability ${q.durability.toFixed(2)} \xB7 typeConf ${q.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${j}s, ${v} 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 P=parseFloat(e.minRecall),{best:J,points:ae}=d(A,{minRecall:P});if(console.log(),console.log(m.bold(` threshold sweep (${ae.length} policies, recall floor ${D(P)})`)),J)console.log(` best: ${J.requireTyped?`typed & type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} durability>=${J.minDurability}`),console.log(` recall ${D(J.recall)} \xB7 filtered ${D(J.filtered)} \xB7 precision ${D(J.precision)} \xB7 lost ${J.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(P)} recall \u2014 not even keeping everything typed.`));let W=ae.slice().sort((ve,ye)=>ye.recall-ve.recall)[0];W&&console.log(m.dim(` Best recall available: ${D(W.recall)} at ${W.requireTyped?`type>=${W.minType}`:"type gate OFF"} worth>=${W.minWorth} dur>=${W.minDurability}, filtering ${D(W.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=F(process.cwd(),e);Fe(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?F(process.cwd(),o.dir):F(process.cwd(),".agentx/wiki");Fe(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Yg(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"}yc();import{Command as Kg}from"commander";import N from"chalk";import{resolve as Sn}from"path";import{existsSync as Vg}from"fs";Te();var it=new Kg().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");it.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=H();if(!o.graph?.enabled){console.log(N.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(N.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(N.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 co({baseDir:Sn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(N.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(N.bold(` Graph review \u2014 ${r.length} pending`)),console.log(N.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,d=0,g=0,u=0;for(let f=0;f<r.length;f++){let w=r[f],y=Ht(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${N.cyan(w.msgHash.slice(0,8))} ${N.dim(y)} ... `);let k=Qg(w,a,c),b=null;try{b=await Xg(n,t,k,o.dashboard?.token)}catch(v){u++,console.log(N.red(`ERR ${v.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(N.red("ERR no decision"));continue}let x=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(N.green("APPROVE")+" "+N.dim(A)),e.dryRun)l++;else try{Zg(i,w,a,c,t),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:t,reviewReason:A}),l++}catch(v){console.log(N.yellow(` (commit failed, staying pending: ${v.message?.slice(0,100)})`)),u++}else x==="reject"?(console.log(N.red("REJECT")+" "+N.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:t,reviewReason:A}),d++):(console.log(N.yellow("SKIP")+" "+N.dim(A||x)),g++)}console.log();let p=e.dryRun?"would":"did";console.log(N.dim(` Summary: ${p} approve ${l}, ${p} reject ${d}, ${g} skipped, ${u} errors.`)),e.dryRun&&(l>0||d>0)&&console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});it.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=H();if(!o.graph){console.log(N.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Sn(process.cwd(),o.graph.baseDir);if(!Vg(t)){console.log(N.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-V4WN2VVM.js"),s=new co({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(N.dim(" "),...a)});console.log(),console.log(N.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(N.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});it.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=H();if(!o.graph?.enabled){console.log(N.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 co({baseDir:Sn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map($=>$.id));console.log(),console.log(N.bold(` graph pull \u2190 ${t}`));let l,d,g;try{let $=await fetch(`${t}/graph/schema`,{headers:s});if(!$.ok)throw new Error(`schema HTTP ${$.status}`);l=(await $.json()).schema;let R=await fetch(`${t}/graph/nodes`,{headers:s});if(!R.ok)throw new Error(`nodes HTTP ${R.status}`);d=(await R.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}`);g=(await j.json()).classifications||[]}catch($){console.log(N.red(` fetch failed: ${$.message}`));return}let u=r.levels.map($=>$.id).join(","),p=l?.levels?.map($=>$.id).join(","),f=u===p;f?console.log(N.dim(` schema matches (${r.levels.length} levels)`)):(console.log(N.yellow(" \u26A0 schema levels differ:")),console.log(N.dim(` local: ${u}`)),console.log(N.dim(` peer: ${p}`)),a.length===0&&!e.dryRun?(console.log(N.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(N.yellow(" keeping local schema; node import may fail if levels disagree")));let w=f?r:l,y=new Map;w.levels.forEach(($,T)=>y.set($.id,T));let k=[...d].sort(($,T)=>(y.get($.level)??99)-(y.get(T.level)??99)),b=0,x=0,A=0;for(let $ of k){if(c.has($.id)){x++;continue}if(e.dryRun){b++,c.add($.id);continue}try{i.addNode({...$,createdBy:$.createdBy?`${$.createdBy} (sync)`:`sync:${t}`}),c.add($.id),b++}catch(T){A++,console.log(N.yellow(` skip node ${$.id}: ${T.message?.slice(0,100)}`))}}console.log(N.dim(` nodes: +${b} added \xB7 ${x} already-present \xB7 ${A} failed`));let v=0,E=0;for(let $ of g)if(!(!$.msgHash||!Array.isArray($.path))){if(i.getFingerprint($.msgHash)){E++;continue}if(e.dryRun){v++;continue}i.setFingerprint($.msgHash,{path:$.path,leaf:$.leaf||{}}),v++}console.log(N.dim(` fingerprints: +${v} cached \xB7 ${E} already-present`)),console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` \u2713 pulled from ${t}`)),console.log()});function Qg(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(`
|
|
400
|
+
`),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(`
|
|
401
|
+
`)}async function Xg(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 ri((c?.content||"").toString())}finally{clearTimeout(r)}}function Zg(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Cs(){let e=H();if(!e.graph?.baseDir)return console.log(N.red(" graph.baseDir is not configured")),null;let o=Sn(process.cwd(),e.graph.baseDir);return{store:new co({baseDir:o}),baseDir:o}}var Ts=it.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Ts.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=Cs();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-B4YE3EFK.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(N.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):N.dim("cache");console.log(` ${N.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${N.bold(Ht(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(N.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(N.dim(` ${r.length} to check (${e.strategy}).`)),console.log(N.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Ts.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(N.red(" verdict must be correct | wrong | unsure"));return}let n=Cs();if(!n)return;let{ReviewStore:s}=await import("./review-store-B4YE3EFK.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(N.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(N.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(N.green(` ${o}: ${Ht(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(N.dim(` should have been: ${t.path}`))});Ts.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=Cs();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-B4YE3EFK.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} ${N.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(N.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),d=c.n>=5&&l>.15?N.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${d}`)}}console.log(),r.calibratable<100?console.log(N.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(N.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as im}from"commander";import Y from"chalk";import{Command as Oa}from"commander";import ie from"chalk";import{existsSync as em}from"fs";import{resolve as om}from"path";import tm from"better-sqlite3";function nm(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(ie.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function sm(e){let o=om(process.cwd(),e);return em(o)||(console.log(ie.red(` No db at ${o}`)),process.exit(1)),new tm(o,{readonly:!0})}var ja=new Oa().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(bt)).option("--max <n>","max clusters distilled per run",String(Yt)).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(ie.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=sm(e.path),t=await Ri(o,{since:nm(e.since),agentId:e.agent,sessions:new gi(process.cwd()),minOccurrences:Number(e.minOccurrences)||bt,max:Number(e.max)||Yt,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(ie.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(` ${ie.cyan(n.key)} ${ie.bold(`\xD7${n.count}`)} ${ie.dim(n.status)}`),n.sampleMessage&&console.log(ie.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(ie.dim(`
|
|
402
|
+
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(ie.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(ie.green(` \u2713 draft written: ${n.id}`)+ie.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(ie.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(ie.yellow(` \u26A0 ${n}`));t.dryRun?console.log(ie.dim(`
|
|
403
|
+
dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(ie.dim(`
|
|
404
|
+
review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Ia={hourly:"0 * * * *",daily:"0 3 * * *"},Ra=new Oa().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(bt)).option("--timezone <tz>","IANA timezone","Africa/Tunis").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?Ia.hourly:e.daily?Ia.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(ie.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(ie.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||bt,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 ${Yt} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
|
|
405
|
+
`),i=await ne(a=>{ce(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&ce(a,"crons.procedure-extract.enabled",!1):o&&ce(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(ie.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(ie.green(` \u2713 ${r} procedure extraction: off`)):(console.log(ie.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(ie.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(ie.dim(" on-task counting: enabled")),console.log(ie.dim(` threshold: ${t} occurrences`))),console.log(ie.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var ze=new im().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");ze.addCommand(ja);ze.addCommand(Ra);ze.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 lo,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"}.`))});ze.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 lo,t=e.steps?String(e.steps):`## Steps
|
|
406
|
+
|
|
407
|
+
1. (fill in)
|
|
408
|
+
|
|
409
|
+
## Notes
|
|
410
|
+
|
|
411
|
+
`;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)}});ze.command("show <id>").description("show a single procedure (active or draft)").action(e=>{let o=new lo,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()});ze.command("promote <id>").description("promote a draft into the active procedure set").action(e=>{let o=new lo;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)}});ze.command("reject <id>").description("reject a draft (kept under _drafts/_rejected/ so it is never re-mined)").action(e=>{let o=new lo;try{o.rejectDraft(e),console.log(Y.green(` \u2713 rejected: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});ze.command("deprecate <id>").description("retire an active procedure (kept, but never surfaced to agents)").action(e=>{let o=new lo;try{o.deprecate(e),console.log(Y.green(` \u2713 deprecated: ${e}`))}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});ze.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 lo,n=xi(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 cm}from"commander";import S from"chalk";import{resolve as at,basename as lm}from"path";import{existsSync as Ns,readFileSync as _s,writeFileSync as En}from"fs";import Gw from"better-sqlite3";import{readFileSync as rm}from"fs";import{resolve as rt,dirname as Ca}from"path";import{fileURLToPath as am}from"url";var Mt=[{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 Ta(e){let o=Ca(am(import.meta.url)),t=process.argv[1]?Ca(process.argv[1]):"",n=[rt(o,`${e}.yaml`),rt(o,"workflows/templates",`${e}.yaml`),rt(o,"..","workflows/templates",`${e}.yaml`),rt(o,"../..","workflows/templates",`${e}.yaml`),t?rt(t,"workflows/templates",`${e}.yaml`):"",t?rt(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return rm(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
|
|
412
|
+
${n.join(`
|
|
413
|
+
`)}`)}var De=new cm().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");De.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Eo().list();if(!o.length){console.log(S.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"?S.green("dispatch: active"):S.yellow(`dispatch: ${t.state}`);console.log(` ${S.cyan(t.id)} ${S.bold(t.title)} ${S.dim(`v${t.version} \xB7`)} ${r} ${S.dim(`\xB7 review: ${t.status}`)}`),console.log(` ${S.dim("trigger:")} ${s.source??"?"}${i?` ${S.dim(i)}`:""}`),console.log(` ${S.dim("nodes: ")} ${t.nodes.length} (${t.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(S.dim(` ${o.length} workflow${o.length===1?"":"s"}.`))});De.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 Eo().get(e);n||(console.log(S.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=o.format.toLowerCase();s==="yaml"||s==="yml"?console.log(ui(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(S.red(` unknown format "${o.format}" \u2014 use json or yaml`)),process.exit(1))});De.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=at(process.cwd(),e);Ns(i)||(console.log(S.red(` file not found: ${i}`)),process.exit(1));try{let r=_s(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Yo(r,{filePath:e}):JSON.parse(r),l=Go.safeParse(c);if(!l.success){console.log(S.red(` \u2717 ${i}`));for(let g of l.error.issues)console.log(` ${g.path.join(".")||"<root>"}: ${g.message}`);process.exit(1)}let d=zt(l.data);if(d.length){console.log(S.yellow(` ! ${i} (lint)`));for(let g of d)console.log(` ${g}`);process.exit(1)}console.log(S.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof Gt?r.message:`parse error: ${r?.message??r}`;console.log(S.red(` ${a}`)),process.exit(1)}return}let t=new Eo().validateAll(),n=0,s=0;for(let i of t)if(i.isValid)console.log(S.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(S.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(S.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});De.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Mt.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");Mt.some(a=>a.name===t)||(console.log(S.red(` unknown template "${o.template}"`)),console.log(S.dim(` available: ${Mt.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(S.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Eo;!o.force&&n.get(e)&&(console.log(S.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Ta(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=Yo(s,{filePath:`${e}.yaml`}),c=Go.safeParse(a);if(!c.success){console.log(S.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(S.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let i=o.json?"json":"yaml",r=at(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Yo(s,{filePath:`${e}.yaml`}),c=Go.parse(a);En(r,JSON.stringify(c,null,2)+`
|
|
414
|
+
`)}else En(r,s);console.log(),console.log(S.green(` \u2713 scaffolded ${r}`)),console.log(S.dim(` template: ${t}`)),console.log(),console.log(S.dim(" Next:")),console.log(S.dim(` 1. edit ${r}`)),console.log(S.dim(` 2. agentx workflow validate ${r}`)),console.log(S.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});De.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Mt)console.log(` ${S.cyan(e.name.padEnd(20))} ${S.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${S.dim(e.description)}`);console.log(),console.log(S.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});De.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=at(process.cwd(),e);Ns(t)||(console.log(S.red(` file not found: ${t}`)),process.exit(1));let n=_s(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Yo(n,{filePath:e}):JSON.parse(n)}catch(u){let p=u instanceof Gt?u.message:`parse error: ${u?.message??u}`;console.log(S.red(` ${p}`)),process.exit(1)}let r=Go.safeParse(i);if(!r.success){console.log(S.red(" \u2717 schema:"));for(let u of r.error.issues)console.log(` ${u.path.join(".")||"<root>"}: ${u.message}`);process.exit(1)}let a=zt(r.data);if(a.length){console.log(S.red(" \u2717 lint:"));for(let u of a)console.log(` ${u}`);process.exit(1)}let c=new Eo,l=s?lm(e).match(/\.yml$/i)?"yml":"yaml":"json",d=at(c.baseDir,`${r.data.id}.${l}`);if(En(d,s?n:JSON.stringify(r.data,null,2)+`
|
|
415
|
+
`),console.log(S.green(` \u2713 ${r.data.id} \u2192 ${d}`)),o.reload===!1){console.log(S.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let g=`${String(o.daemon).replace(/\/$/,"")}/reload`;try{let u=await fetch(g,{method:"POST"});u.ok?console.log(S.dim(" \u2713 daemon reloaded")):console.log(S.dim(` daemon /reload returned ${u.status} \u2014 restart manually if needed`))}catch{console.log(S.dim(` daemon not reachable at ${o.daemon} \u2014 start it or restart to pick up the new workflow`))}});De.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 wt({nodeId:t}).list({workflowId:e,limit:Number(o.limit)});if(!n.length){console.log(S.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"?S.cyan:s.status==="failed"?S.red:S.green;console.log(` ${S.dim(s.id.slice(0,8))} ${S.bold(s.workflowId)} ${a(r)} ${S.dim(s.status)}`),console.log(` ${S.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${S.dim("home: ")} ${s.homeNode}`),console.log(` ${S.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${S.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(S.dim(` ${n.length} run${n.length===1?"":"s"}.`))});De.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(S.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=at(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Ns(s)){let c=_s(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),d;try{d=l?Yo(c,{filePath:e}):JSON.parse(c)}catch(b){let x=b instanceof Gt?b.message:`parse error: ${b?.message??b}`;console.log(S.red(` ${x}`)),process.exit(1)}let g=Go.safeParse(d);if(!g.success){console.log(S.red(" \u2717 schema:"));for(let b of g.error.issues)console.log(` ${b.path.join(".")||"<root>"}: ${b.message}`);process.exit(1)}let u=zt(g.data);if(u.length){console.log(S.red(" \u2717 lint:"));for(let b of u)console.log(` ${b}`);process.exit(1)}let p=new Eo,f=g.data.id.startsWith("_adhoc-")?g.data.id:`_adhoc-${g.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=at(p.baseDir,`${f}.${w}`),k=l?c.replace(new RegExp(`^id:\\s*${g.data.id}\\b`,"m"),`id: ${f}`):JSON.stringify({...g.data,id:f},null,2)+`
|
|
416
|
+
`;En(y,k),n=f,console.log(S.dim(` ad-hoc registered as "${f}" \u2192 ${y}`));try{await fetch(`${String(o.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let r=`${String(o.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t,force:!!o.force})});if(!c.ok){let d=await c.text();console.log(S.red(` run failed (${c.status}): ${d.slice(0,300)}`)),c.status===409&&console.log(S.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(S.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?S.dim(` (forced, source=${l.source})`):""}`))}catch(c){console.log(S.red(` request to daemon failed: ${c.message}`)),process.exit(1)}o.watch&&a&&await dm({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function dm(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"?S.green:a==="error"?S.red:S.cyan,l=r.totalTokens!=null?S.dim(`${r.totalTokens}t`):"",d=r.durationMs!=null?S.dim(`${r.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${S.bold(r.nodeId||r.label||"(node)")} ${l} ${d}`),r.error&&console.log(` ${S.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(` ${S.dim("run finished:")} ${c.status}`),console.log(S.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(S.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(t.values())}De.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}Na(r);return}}catch{}let n;try{let i=await fetch(`${t}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);i.ok||(console.log(S.red(` /traces returned ${i.status}`)),process.exit(1)),n=await i.json()}catch(i){console.log(S.red(` daemon request failed: ${i.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(S.yellow(` no traces for "${e}"`)),console.log(S.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(S.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let i of s)Na(i)});function Na(e){let o=e.status||"ok",t=o==="ok"?S.green:o==="error"?S.red:S.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))} ${S.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${S.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${S.dim("model:")} ${i}`),console.log(` ${S.dim("tokens:")} ${n} ${S.dim("duration:")} ${s}`),e.error&&console.log(` ${S.dim("error:")} ${S.red(String(e.error).slice(0,300))}`),console.log()}De.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 wt({nodeId:t}).setStatus(e,"paused")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 paused ${e}`))});De.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 wt({nodeId:t}).setStatus(e,"running")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 resumed ${e}`))});De.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 wt({nodeId:t}).setStatus(e,"canceled")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 canceled ${e}`))});import{Command as _a}from"commander";import ee from"chalk";import qo from"prompts";import{readFileSync as gm,existsSync as mm}from"fs";import{resolve as pm}from"path";var Lt=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Ds=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Da={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 Pa(){let e=pm(process.cwd(),"agentx.json");if(!mm(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(gm(e,"utf-8"))}function um(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ee.yellow("\u26A0 no signing secret"):ee.green("\u2713 active"):ee.dim("disabled")}function fm(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Ds.has(e.source)?ee.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ee.cyan(e.id)} ${um(e)}`),console.log(` ${ee.dim(e.source)} \u2192 ${ee.bold(e.agentId)}${n}`),console.log(` POST ${ee.dim(t)}`),e.secretEnv&&console.log(` secret: ${ee.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${ee.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},i=Object.keys(s);if(i.length){console.log(` ${ee.dim("triggers:")}`);for(let r of i)console.log(` ${r} \u2192 ${s[r]}`)}e.defaultWorkflow&&console.log(` ${ee.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var ro=new _a().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");ro.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=Pa(),t=Array.isArray(o.webhooks)?o.webhooks:[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(ee.dim(`
|
|
417
|
+
No webhooks registered. Add one with: agentx webhook add
|
|
418
|
+
`));return}console.log();for(let n of t)fm(n)});ro.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Lt.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=Pa(),n=Object.keys(t.agents||{}),s=(t.mesh?.peers||[]).map(p=>p.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(),d=String(o.description||"").trim(),g=o.prompt!==!1;if(!r&&g&&(r=((await qo({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:f=>/^[a-z0-9][a-z0-9_-]*$/.test(f)||"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&&g&&(a=(await qo({type:"select",name:"source",message:"Source",choices:Lt.map(f=>({title:`${f}${Ds.has(f)?" \u2713 wired":""}`,value:f,description:Da[f]}))})).source),!Lt.includes(a))throw new Error(`Source must be one of: ${Lt.join(", ")}`);if(!c&&g&&(i?c=((await qo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await qo({type:"select",name:"agentId",message:"Agent",choices:n.map(f=>({title:f,value:f}))})).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&&g&&a!=="custom"&&(l=((await qo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!d&&g&&(d=((await qo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await ne(p=>{if(p.webhooks=Array.isArray(p.webhooks)?p.webhooks:[],p.webhooks.find(w=>w.id===r))throw new Error(`Webhook "${r}" already exists.`);let f={id:r,source:a,agentId:c,enabled:!0};l&&(f.secretEnv=l),d&&(f.description=d),i&&(f.node=i),p.webhooks.push(f)});if(!u.success)throw new Error(u.error);console.log(ee.green(`\u2713 added webhook "${r}" (${a} \u2192 ${c}${i?` @ ${i}`:""})`)),u.reloaded&&console.log(ee.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(ee.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});ro.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await qo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await ne(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(ee.green(`\u2713 removed webhook "${e}"`))});function Ma(e){return async o=>{let t=await ne(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(ee.green(`\u2713 ${e?"enabled":"disabled"} webhook "${o}"`))}}ro.command("enable <id>").description("enable a webhook entry").action(Ma(!0));ro.command("disable <id>").description("disable a webhook entry").action(Ma(!1));var An=new _a().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");An.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await ne(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(ee.green(`\u2713 ${e}: ${o} \u2192 ${t}`))});An.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await ne(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(ee.green(`\u2713 removed trigger ${o} from "${e}"`))});An.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 ne(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(ee.green(`\u2713 ${e}: defaultWorkflow ${t?"cleared":`\u2192 ${o}`}`))});ro.addCommand(An);ro.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Lt.map(t=>({source:t,wired:Ds.has(t),hint:Da[t]}));if(e.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let t of o){let n=t.wired?ee.green("\u2713 wired"):ee.dim("inbound-only");console.log(` ${ee.cyan(t.source.padEnd(8))} ${n} ${ee.dim(t.hint)}`)}console.log(),console.log(ee.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(ee.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as hm}from"commander";import oe from"chalk";Te();function ct(e){let{summary:o,backupPath:t}=Vo(n=>e(n));console.log(oe.green(`
|
|
419
|
+
\u2713 ${o}`)),t&&console.log(oe.dim(` Backup: ${t}`)),console.log(oe.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
420
|
+
`))}function In(){try{return H().business||{}}catch{return{}}}var lt=new hm().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");lt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=In();if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o||!o.enabled){console.log(),console.log(oe.yellow(" business block not enabled (or missing).")),console.log(oe.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(oe.bold(" Org chart"));let i=Object.entries(t);if(i.length===0)console.log(oe.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?oe.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?oe.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${oe.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(oe.bold(` Projects (${n.length})`)),n.length===0)console.log(oe.dim(" (empty)"));else for(let r of n){let a=r.pm?oe.dim(` \xB7 pm=${r.pm}`):"",c=r.client?oe.dim(` \xB7 client=${r.client}`):"";console.log(` ${oe.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(oe.bold(` Contact map (${s.length})`)),s.length===0)console.log(oe.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(` ${oe.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?oe.dim(` (${r.displayName})`):""}`)}console.log()});var Ps=lt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Ps.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=In(),t=Object.entries(o.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(t),null,2));return}if(t.length===0){console.log(oe.dim(" no entries"));return}for(let[n,s]of t)console.log(` ${oe.cyan(n)} ${s.role}${s.reportsTo?oe.dim(` \u2192 ${s.reportsTo}`):""}`)});Ps.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);ct(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}`:""})`))});Ps.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{ct(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 Ms=lt.command("project").description("manage business.projects \u2014 id, pm, client");Ms.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=In().projects||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(oe.dim(" no projects"));return}for(let n of t)console.log(` ${oe.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Ms.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)=>{ct(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`})});Ms.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{ct(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 Ls=lt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Ls.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=In().contactMap||[];if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(oe.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+"/":""}${oe.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Ls.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(oe.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),ct(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`})});Ls.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=>{ct(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 ym}from"commander";import Re from"chalk";Te();var wm={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Us(e){let o=wm[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function On(){let o=H().business?.standup?.plansDir||".agentx/plans";return new zi(o)}var dt=new ym().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");dt.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=Us(e),n=On(),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(`
|
|
421
|
+
`):(console.error(Re.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(t,s);console.log(Re.green(` \u2713 ${t} plan saved \u2192 ${i.path}`));let r=Gn(s);if(r.length){console.log(Re.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(Re.dim(` \u2022 ${a}`))}});dt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=On();if(e){let n=Us(e),s=o.read(n);if(!s){console.log(Re.dim(` No ${n} plan set.`));return}La(s.tier,s.date,s.content);return}let t=o.resolve();if(!t){console.log(Re.yellow(" No plan set at any tier.")),console.log(Re.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(Re.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}La(t.tier,t.date,t.content)});dt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=On().list(parseInt(e.limit,10)||20);if(!t.length){console.log(Re.dim(" No plans yet."));return}for(let n of t)console.log(` ${Re.cyan(n.tier.padEnd(5))} ${Re.bold(n.date.padEnd(11))} ${Re.dim(n.path)}`)});dt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Us(e),n=On().read(o);if(!n){console.log(Re.dim(` No ${o} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(Re.green(` \u2713 ${o} plan cleared (${n.path})`))});function La(e,o,t){console.log(Re.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
|
|
422
|
+
`))console.log(` ${s}`);console.log();let n=Gn(t);n.length&&console.log(Re.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as bm}from"commander";import Le from"chalk";Te();function $m(){try{return H().notifications||{}}catch{return{}}}function jn(e){let{summary:o,backupPath:t}=Vo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Le.green(`
|
|
423
|
+
\u2713 ${o}`)),t&&console.log(Le.dim(` Backup: ${t}`)),console.log(Le.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
424
|
+
`))}var gt=new bm().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");gt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=$m();if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.destination){let n=o.destination.accountId?` \xB7 account=${o.destination.accountId}`:"";console.log(` destination ${Le.cyan(o.destination.channel+":"+o.destination.chatId)}${Le.dim(n)}`)}else console.log(` destination ${Le.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Le.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Le.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Le.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Le.dim("off")}`),console.log()});gt.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){jn(o=>(delete o.destination,"notifications destination cleared"));return}jn(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})`:""}`))});gt.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(Le.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(Le.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";jn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});gt.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(Le.red(" threshold must be a non-negative integer")),process.exit(1)),jn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as km}from"commander";import $o from"chalk";import{readdirSync as Fs,statSync as Ua,unlinkSync as vm,rmSync as xm,existsSync as Fa}from"fs";import{resolve as qa,join as Wa}from"path";var Ba=[{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 qs(e,o){if(!Fa(e))return[];let t=[];for(let n of Fs(e,{withFileTypes:!0})){let s=Wa(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...qs(s,!0))}return t}var Cn=new km().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Cn.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of Ba){let t=qa(process.cwd(),o.dir),n=qs(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=Ua(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(` ${$o.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Rn(s).padStart(10)} oldest=${r}`)}console.log($o.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Rn(e).padStart(10)} total`)),console.log(),console.log($o.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Cn.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($o.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($o.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?$o.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Ba){if(n&&r.dir!==n)continue;let a=qa(process.cwd(),r.dir),c=qs(a,!!r.recursive),l=0,d=0;for(let u of c)try{let p=Ua(u);if(p.mtimeMs<t&&(d+=p.size,l++,!e.dryRun))try{vm(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Ja(a)}catch{}let g=e.dryRun?"would remove":"removed";console.log(` ${$o.cyan(r.dir.padEnd(22))} ${g} ${String(l).padStart(5)} files (${Rn(d)})`),s+=l,i+=d}console.log(),console.log($o.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Rn(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Ja(e){if(Fa(e))for(let o of Fs(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=Wa(e,o.name);Ja(t);try{Fs(t).length===0&&xm(t,{recursive:!1})}catch{}}}function Rn(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 Sm}from"commander";import L from"chalk";var ko=new Sm().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");ko.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new Ko().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(L.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?L.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(` ${L.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${L.dim(i)}`)}console.log()});ko.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new Ko().get(e);if(n||(console.log(L.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(L.bold(` ${n.title}`)),n.description&&console.log(L.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(L.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?L.red("*"):" ",r=s.defaultValue!==void 0?L.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?L.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${L.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});ko.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=Em(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(L.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(L.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(L.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(L.red(" --kind must be shell|http")),process.exit(1);let s=fi.safeParse(n);if(!s.success){console.log(L.red(" validation failed:"));for(let a of s.error.issues)console.log(L.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new Ko().save(s.data);console.log(L.green(`
|
|
425
|
+
\u2713 action "${r.id}" saved (${r.kind}).`)),console.log(L.dim(` Test: agentx actions run ${r.id}
|
|
426
|
+
`))});ko.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Ko().delete(e)||(console.log(L.red(` no action "${e}"`)),process.exit(1)),console.log(L.green(` \u2713 action "${e}" removed`))});ko.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 Ko().get(e);n||(console.log(L.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(L.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await hi(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?L.green("\u2713 ok"):L.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(L.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(L.dim(" --- errors ---")),console.log(L.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(L.red(` ${i.message}`)),process.exit(1)}});ko.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(L.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(L.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(L.bold(" Built-in typed actions")),console.log(L.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?L.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${L.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(L.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(L.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(L.bold(` ${r.name}`)),r.description&&console.log(L.dim(` ${r.description}`)),console.log(),console.log(L.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(L.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(L.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(L.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(L.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(L.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function Em(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}Te();import{Command as Am}from"commander";import Q from"chalk";var Ha=new Am().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=H(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(Q.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(Q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(Q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:d,value:g}=await a.read();if(d)break;l+=c.decode(g,{stream:!0});let u;for(;(u=l.indexOf(`
|
|
427
|
+
|
|
428
|
+
`))>=0;){let p=l.slice(0,u);l=l.slice(u+2),Im(p)}}}catch(r){console.error(Q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Im(e){let o="message",t="";for(let i of e.split(`
|
|
429
|
+
`))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?Q.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=Q.cyan(n.phase?.padEnd(9)??"run"),r=Q.bold(n.workflowId??""),a=Q.dim((n.runId??"").slice(0,8)),c=n.nodeId?Q.yellow(n.nodeId):"",l=n.note?Q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=Q.magenta(`task.${n.phase}`.padEnd(14)),r=Q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?Q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${Q.cyan(a)} ${c}`);break}case"signal":{let i=Q.green("signal".padEnd(9)),r=Q.bold(n.name),a=Q.dim(`(${n.scope})`),c=n.workflowId?Q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=Q.blue("mesh".padEnd(9)),r=Q.bold(n.peer),a=n.healthy?Q.green("\u2713 healthy"):Q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${Q.dim(n.delta??"")}`);break}case"channel":{let i=Q.yellow("channel".padEnd(9)),r=n.direction==="in"?Q.cyan("\u2190"):Q.magenta("\u2192"),a=Q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?Q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(Q.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)}`)}}import{Command as Om}from"commander";import jm from"chalk";import Tn from"chalk";function Nn(e){console.error(),console.error(Tn.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Tn.dim(` ${e.why}`)),console.error(),console.error(` Use ${Tn.cyan(e.instead)} instead.`),e.note&&console.error(Tn.dim(` ${e.note}`)),console.error()}var _n={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 za=new Om().name("tui").description("[deprecated \u2014 see agentx attach] interactive terminal mission control").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("--poll <ms>","snapshot poll interval in ms","3000").action(async e=>{Nn({what:"agentx tui",..._n}),process.stdout.isTTY||(console.error(jm.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-PX25MD47.js"),{App:t}=await import("./App-U52IPUK2.js"),{render:n}=await import("ink"),s=(await import("react")).default,i=o({node:e.node,token:e.token,config:e.config}),r=Math.max(500,Number(e.poll)||3e3);await n(s.createElement(t,{conn:i,pollMs:r})).waitUntilExit()});import{Command as Rm}from"commander";import K from"chalk";import{randomUUID as Ga}from"crypto";import{createInterface as Cm}from"node:readline/promises";import Tm from"ora";var Ya=new Rm().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)=>{Nn({what:"agentx chat",..._n});let t=or({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${Ga().slice(0,12)}`,r=[];try{r=await Vt(t)}catch(d){console.error(K.red(` cannot reach daemon at ${t.baseUrl}: ${d?.message||d}`)),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(d=>d.id===n)||(console.error(K.red(` unknown agent: @${n}`)),console.error(K.dim(` registered: ${r.map(d=>`@${d.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:d}=await import("ink"),{ChatApp:g}=await import("./ChatApp-XP4OMHPL.js"),u=(await import("react")).default;await d(u.createElement(g,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}_m(t.baseUrl,n,i,s);let a=Cm({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
|
|
430
|
+
bye`)),process.exit(0)});;){let d;try{d=(await a.question(K.cyan("you \u203A "))).trim()}catch{a.close();return}if(!d)continue;if(d==="/exit"||d==="/quit"){a.close();return}if(d==="/who"){console.log(K.dim(` @${n} chatId=${i} channel=${s}`));continue}if(d==="/clear"){i=`chat-cli:${Ga().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(d==="/agents"){try{let f=await Vt(t);for(let w of f){let y=w.id===n?K.green("\u25CF"):K.dim("\u25CB");console.log(` ${y} @${w.id} ${K.dim(w.tier)} ${w.model??""}`)}}catch(f){console.error(K.red(` failed to list agents: ${f?.message||f}`))}continue}if(d.startsWith("/agent ")){let f=d.slice(7).replace(/^@/,"").trim();if(!f){console.log(K.red(" usage: /agent <id>"));continue}try{if(!(await Vt(t)).find(y=>y.id===f)){console.log(K.red(` unknown agent: @${f}`));continue}n=f,console.log(K.dim(` now talking to @${n}`))}catch(w){console.error(K.red(` failed to switch agent: ${w?.message||w}`))}continue}if(d.startsWith("/")){console.log(K.red(` unknown command: ${d.split(/\s+/)[0]}`)),console.log(K.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let g=Tm({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),p=Nm(n);try{let f=await tr(t,n,d,{channel:s,chatId:i,onText:y=>{g.stop(),p.text(y)},onThinking:()=>{},onTool:y=>{g.stop(),p.tool(y)}});g.stop();let w=Math.round((Date.now()-u)/100)/10;f.error?p.finishError(f.error):p.finish(w,f.usage)}catch(f){g.stop(),p.finishError(f?.message||String(f))}finally{c=!1}if(l){console.log(K.dim(" bye"));return}}});function Nm(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
|
|
431
|
+
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
432
|
+
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
433
|
+
`&&(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(`
|
|
434
|
+
`),t=!0);let c=r.arg?K.dim(`(${r.arg})`):"";process.stdout.write(` ${K.green("\u25CF")} ${K.bold(r.name)}${c}
|
|
435
|
+
`)}else r.status==="result"&&r.error&&(t||(process.stdout.write(`
|
|
436
|
+
`),t=!0),process.stdout.write(` ${K.red("\u25CF")} ${K.dim(`${r.name??"tool"} failed`)}
|
|
437
|
+
`))},finish(r,a){if(!o){process.stdout.write(`${K.green(`@${e}`)} ${K.dim("\xB7 (empty reply)")}
|
|
438
|
+
|
|
439
|
+
`);return}t||process.stdout.write(`
|
|
440
|
+
`);let c=a?.outputTokens!=null?`, ${a.outputTokens} tok`:"";process.stdout.write(K.dim(` \xB7 ${r}s${c}
|
|
441
|
+
|
|
442
|
+
`))},finishError(r){o&&!t&&process.stdout.write(`
|
|
443
|
+
`),process.stdout.write(K.red(` \u2717 ${r}
|
|
444
|
+
|
|
445
|
+
`))}}}function _m(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 Dm}from"commander";import Ce from"chalk";import{readFileSync as Pm}from"fs";var Dn=["user","feedback","project","reference"],Wo=new Dm().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Wo.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(!Dn.includes(e.type)){console.error(Ce.red(` --type must be one of: ${Dn.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await Mm();else try{o=Pm(e.file,"utf-8")}catch(s){console.error(Ce.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Ce.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new zo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Ce.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Wo.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 zo().list(e.agent);if(e.type){if(!Dn.includes(e.type)){console.error(Ce.red(` --type must be one of: ${Dn.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Ce.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(Ce.bold(` ${s.type}`)),n=s.type),console.log(` ${Ce.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Ce.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Wo.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 zo().get(o.agent,e);if(!n){console.error(Ce.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Ce.bold(`${n.type}/${n.name}`)+Ce.dim(` (${n.description})`)),console.log(Ce.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Wo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new zo().remove(o.agent,e)){console.error(Ce.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Ce.green(` \u2713 memory "${e}" removed`))});Wo.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 zo().indexMarkdown(e.agent);if(!t){console.log(Ce.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function Mm(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}mc();import Ws from"chalk";import{Command as Lm}from"commander";import{resolve as Um}from"path";var Ka=new Lm().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(Um(e.cwd)),e.stdio!==!1?await Si():(oo.error("Only stdio transport is currently supported."),oo.info(`Usage: ${Ws.green("agentx serve --stdio")} or configure in your MCP client.`),oo.break(),oo.info("Add to Claude Code:"),oo.info(Ws.dim(" claude mcp add agentx -- npx agentx serve --stdio")),oo.break(),oo.info("Add to Cursor/MCP config:"),oo.info(Ws.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){Gi(o)}});import{Command as Fm}from"commander";import ge from"chalk";import{spawn as Bs}from"child_process";import{mkdirSync as qm,writeFileSync as Js,rmSync as Va,openSync as Qa,existsSync as Xa}from"fs";import{resolve as Wm,join as Ue}from"path";import{randomBytes as Bm}from"crypto";var Za="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",Jm="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function Hm(e,o){return[{dir:Ue(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:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:Ue(e,"node-b"),id:"demo-vps",name:"vps-nyc",port: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:Ue(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 zm(e,o,t){let n=Ue(e.dir,"workspaces",e.agentId);qm(n,{recursive:!0}),Js(Ue(n,"CLAUDE.md"),`# ${e.agentName}
|
|
446
|
+
|
|
447
|
+
${e.persona}
|
|
448
|
+
`),Js(Ue(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}}};Js(Ue(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function Hs(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function zs(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 Pn(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
|
|
449
|
+
`).join(`
|
|
450
|
+
`)}`)}var ec=new Fm().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").action(async e=>{let o=parseInt(e.basePort,10),t=Wm(process.cwd(),".agentx-demo"),n=Hm(t,o),s=Bm(24).toString("hex"),i=[],r=process.argv[1];(!r||!Xa(r))&&(console.error(ge.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),Xa(t)&&Va(t,{recursive:!0,force:!0});for(let d of n)zm(d,n,s);console.log(),console.log(ge.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ge.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ge.dim(" Run `agentx setup` to wire real agents.\n"));let a=!1,c=d=>{if(!a){a=!0;for(let g of i)try{g.kill("SIGTERM")}catch{}setTimeout(()=>{if(!e.keep)try{Va(t,{recursive:!0,force:!0})}catch{}process.exit(d)},800)}};process.on("SIGINT",()=>c(0)),process.on("SIGTERM",()=>c(0));let l={...process.env};delete l.ANTHROPIC_API_KEY,delete l.ANTHROPIC_API_KEY_OLD,delete l.OPENAI_API_KEY,delete l.DEEPSEEK_API_KEY;try{for(let p of n){let f=Qa(Ue(p.dir,"daemon.log"),"a"),w=Bs(process.execPath,[r,"daemon","start","-c",Ue(p.dir,"agentx.json")],{cwd:p.dir,env:{...l,MESH_TOKEN:s,AGENTX_DEMO_SCRIPT:Ue(p.dir,"demo-script.json")},stdio:["ignore",f,f]});i.push(w),console.log(ge.dim(` \u25B8 ${p.name} starting on 127.0.0.1:${p.port} (log: ${Ue(p.dir,"daemon.log")})`))}for(let p of n)await Hs(`${p.name} /health`,async()=>(await fetch(`http://127.0.0.1:${p.port}/health`)).ok,3e4);console.log(ge.green(" \u2713 three daemons up"));let d=n[0].port+10;{let p=Qa(Ue(n[0].dir,"board.log"),"a"),f=Bs(process.execPath,[r,"board","serve"],{cwd:n[0].dir,env:{...l,MESH_TOKEN:s},stdio:["ignore",p,p]});i.push(f)}await Hs("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${d}/live`)).ok,3e4),console.log(ge.green(" \u2713 dashboard up")),await Hs("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(y=>y.healthy&&y.skills?.length).length>=2,3e4),console.log(ge.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let g=`http://127.0.0.1:${d}/live`;if(console.log(),console.log(` Dashboard: ${ge.cyan(g)} (all three nodes via the mesh)`),console.log(ge.dim(` Daemon APIs: ${n.map(p=>`127.0.0.1:${p.port}`).join(" \xB7 ")}`)),e.open!==!1){let p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Bs(p,[g],{stdio:"ignore",detached:!0}).unref()}catch{}}let u=async()=>{console.log(),console.log(ge.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Pn("You \u2192 @cx (laptop-paris)",Za,ge.cyan);let p=await zs(n[0].port,"/task",{agent:"cx",message:Za});Pn("@cx (laptop-paris)",p.content||"(no content)",ge.green),console.log(),console.log(ge.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let f=await zs(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:Jm}),w=typeof f.messageId=="string"?f.messageId:f.content||"(no reply)";Pn("@builder (vps-nyc)",w,ge.yellow);let y=await zs(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${w}`});Pn("@cx (laptop-paris)",y.content||"(no content)",ge.green),console.log(),console.log(ge.dim(` Inspect the run: ${g} \xB7 ledger rows on each node record every dispatch`)),console.log(ge.dim(` Worth your time? A star helps others find it: ${ge.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(await u(),e.once){console.log(),console.log(ge.dim(" --once: shutting down.")),c(0);return}console.log(),console.log(ge.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{u().catch(p=>console.error(ge.red(` Replay failed: ${p.message}`)))}),process.stdin.resume()}catch(d){console.error(),console.error(ge.red(` Demo failed: ${d.message}`)),console.error(ge.dim(` Node logs: ${n.map(g=>Ue(g.dir,"daemon.log")).join(", ")}`)),c(1)}});Te();import{Command as Gm}from"commander";import Ee from"chalk";var vo=new Gm().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");vo.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 Ut("/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(Ee.dim(" no chats cached yet"));return}console.log(),console.log(Ee.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Ee.cyan("group"):Ee.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Ee.dim(n.jid.padEnd(40))} ${Ee.dim(i)}`)}console.log()}catch(o){mt(o)}});vo.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 Ut("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Ee.dim(" no contacts cached yet"));return}console.log(),console.log(Ee.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} ${Ee.dim(i)} ${Ee.dim(n.jid)}`)}console.log()}catch(o){mt(o)}});vo.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 Ys("/whatsapp/ingest",o);Gs(t,!!e.dryRun)}catch(o){mt(o)}});vo.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 Ys("/whatsapp/ingest",t);Gs(n,!!o.dryRun)}catch(t){mt(t)}});vo.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 Ys("/whatsapp/ingest",t);Gs(n,!!o.dryRun)}catch(t){mt(t)}});vo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Ut("/whatsapp/state"),o=await Ut("/whatsapp/chats"),t=await Ut("/whatsapp/contacts");console.log(),console.log(Ee.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){mt(e)}});function Gs(e,o){if(console.log(),console.log(Ee.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(Ee.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Ee.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Ee.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Ee.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Ee.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function oc(){try{let e=H(),[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 Ut(e){let o=await fetch(`${oc()}${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 Ys(e,o){let t=await fetch(`${oc()}${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 mt(e){console.error(Ee.red(` ${e.message||e}`)),process.exit(1)}Te();import{Command as Ym}from"commander";import re from"chalk";import{existsSync as Km,mkdirSync as tc,writeFileSync as Ft}from"fs";import{join as pt,resolve as Vm}from"path";var qt=new Ym().name("plugin").description("manage agentx plugins (Move B)");qt.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=H().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured.")),console.log(re.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(re.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${re.cyan(t)}`);console.log(),console.log(re.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});qt.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(re.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=Vm(o.cwd,t);Km(n)&&!o.force&&(console.log(re.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),tc(n,{recursive:!0}),tc(pt(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Ft(pt(n,"package.json"),ep(e,s)),Ft(pt(n,"tsconfig.json"),op()),Ft(pt(n,"src/index.ts"),tp(e)),Ft(pt(n,"README.md"),np(e,s)),Ft(pt(n,".gitignore"),sp()),console.log(),console.log(re.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(re.bold(" Next steps:")),console.log(re.dim(` cd ${t}`)),console.log(re.dim(" pnpm install")),console.log(re.dim(" pnpm build")),console.log(re.dim(" pnpm link --global # for local testing")),console.log(re.dim(" # then in your agentx project:")),console.log(re.dim(` pnpm link --global ${e}`)),console.log(re.dim(` agentx config set plugins[0] "${e}"`)),console.log(re.dim(" agentx plugin doctor")),console.log()});qt.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=H().plugins??[];if(console.log(),o.length===0){console.log(re.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Qm(n);s.kind==="ok"?console.log(` ${re.green("\u2713")} ${re.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${re.red("\u2717")} ${re.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(re.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(re.red(` ${e.message}`)),process.exitCode=1}});async function Qm(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Xm(o);if(!Zm(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Mi.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 Xm(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 Zm(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function ep(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)+`
|
|
451
|
+
`}function op(){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)+`
|
|
452
|
+
`}function tp(e){return`// ${e} \u2014 AgentX plugin
|
|
453
|
+
//
|
|
454
|
+
// A plugin's default export is { manifest, setup }. The daemon calls
|
|
455
|
+
// setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
|
|
456
|
+
// registers a custom channel adapter; ctx.log() namespaces output.
|
|
457
|
+
|
|
458
|
+
const plugin = {
|
|
459
|
+
manifest: {
|
|
460
|
+
name: ${JSON.stringify(e)},
|
|
461
|
+
version: "0.1.0",
|
|
462
|
+
// agentxRange: "0.x", // optional \u2014 gate against the daemon's major.minor
|
|
463
|
+
},
|
|
464
|
+
|
|
465
|
+
setup(ctx: any) {
|
|
466
|
+
ctx.log("hello from", ${JSON.stringify(e)})
|
|
467
|
+
|
|
468
|
+
// Example: log every completed task.
|
|
469
|
+
ctx.on("task:completed", (payload: any) => {
|
|
470
|
+
ctx.log("task done:", payload.agentId, payload.durationMs + "ms")
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
// Example: register a no-op channel adapter.
|
|
474
|
+
// ctx.addChannel({
|
|
475
|
+
// name: "my-channel",
|
|
476
|
+
// start: async () => {},
|
|
477
|
+
// stop: async () => {},
|
|
478
|
+
// send: async (out) => { ctx.log("send:", out) },
|
|
479
|
+
// })
|
|
480
|
+
},
|
|
481
|
+
|
|
482
|
+
// Optional \u2014 only needed for resources you own (timers, sockets).
|
|
483
|
+
// Bus subscriptions are removed automatically.
|
|
484
|
+
// teardown() {},
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export default plugin
|
|
488
|
+
`}function np(e,o){return`# ${e}
|
|
489
|
+
|
|
490
|
+
${o}
|
|
491
|
+
|
|
492
|
+
## Install
|
|
493
|
+
|
|
494
|
+
\`\`\`bash
|
|
495
|
+
pnpm install ${e}
|
|
496
|
+
\`\`\`
|
|
497
|
+
|
|
498
|
+
## Use
|
|
499
|
+
|
|
500
|
+
Add to \`agentx.json\`:
|
|
501
|
+
|
|
502
|
+
\`\`\`json
|
|
503
|
+
{
|
|
504
|
+
"plugins": ["${e}"]
|
|
505
|
+
}
|
|
506
|
+
\`\`\`
|
|
507
|
+
|
|
508
|
+
Then verify the load:
|
|
509
|
+
|
|
510
|
+
\`\`\`bash
|
|
511
|
+
agentx plugin doctor
|
|
512
|
+
\`\`\`
|
|
513
|
+
|
|
514
|
+
Restart the daemon to activate.
|
|
515
|
+
`}function sp(){return`node_modules/
|
|
516
|
+
dist/
|
|
517
|
+
*.log
|
|
518
|
+
.env
|
|
519
|
+
`}import{Command as ip}from"commander";import Ae from"chalk";import{writeFileSync as rp,mkdirSync as ap,existsSync as Mn,readFileSync as nc,appendFileSync as sc}from"fs";import{resolve as ut,dirname as ac}from"path";import{homedir as Vs}from"os";var cc=new ip().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-YGXVCV2Y.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=dp(t);break;case"bash":s=fp(t);break;case"fish":s=hp(t);break;default:console.error(Ae.red(`unsupported shell: ${n}`)),console.error(Ae.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?ut(String(e.output)):cp(n);ap(ac(i),{recursive:!0}),rp(i,s),console.log(Ae.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),lp(n,i,!!e.yes)});function cp(e){let o=Vs();switch(e){case"zsh":return ut(o,".zsh","completions","_agentx");case"bash":return ut(o,".bash_completion.d","agentx.bash");case"fish":return ut(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function lp(e,o,t){if(e==="zsh"){let n=ut(Vs(),".zshrc"),s=ac(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Mn(n)?nc(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ae.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Mn(n)){let d=["","# agentx completion"];c&&d.push(i),l&&d.push(r),sc(n,d.join(`
|
|
520
|
+
`)+`
|
|
521
|
+
`),console.log(Ae.green("\u2713 Patched ~/.zshrc")),console.log(Ae.dim("Reload your shell: exec zsh"));return}console.log(Ae.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ae.cyan(` ${i}`)),l&&console.log(Ae.cyan(` ${r}`)),console.log(),console.log(Ae.dim("Then reload: exec zsh")),console.log(Ae.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=ut(Vs(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Mn(n)?nc(n,"utf-8"):"").includes(o)){console.log(Ae.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Mn(n)){sc(n,`
|
|
522
|
+
# agentx completion
|
|
523
|
+
${s}
|
|
524
|
+
`),console.log(Ae.green("\u2713 Patched ~/.bashrc")),console.log(Ae.dim("Reload your shell: exec bash"));return}console.log(Ae.dim("Add this to ~/.bashrc:")),console.log(Ae.cyan(` ${s}`)),console.log(),console.log(Ae.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ae.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Pe(e){return e._name||e.name()||""}function xo(e){return e.commands.filter(o=>{let t=Pe(o);return!(!t||t==="help")})}function Wt(e){return e.options.filter(o=>!o.hidden)}function dp(e){let o=[];return o.push("#compdef agentx"),o.push(""),lc(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
|
|
525
|
+
`)}function ic(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function lc(e,o,t){let n=xo(e),i=Wt(e).map(pp).filter(c=>!!c),r=ic(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(up).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=ic([...o,Pe(c)]);t.push(` (${Pe(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)lc(c,[...o,Pe(c)],t)}function gp(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function mp(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function pp(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=gp(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function up(e){let o=mp(e.description()||"");return`'${Pe(e)}[${o}]'`}function fp(e){let o=xo(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(Pe).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=xo(n).map(Pe),i=rc(n);if(t.push(` ${Pe(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 xo(n)){let a=rc(r);t.push(` ${Pe(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(`
|
|
526
|
+
`)}function rc(e){let o=[];for(let t of Wt(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function hp(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 xo(e)){let n=Qs(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Pe(t)}" -d "${n}"`)}o.push("");for(let t of Wt(e)){let n=Ks(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of xo(e)){let n=Pe(t);o.push(`# ${n}`);for(let s of Wt(t)){let i=Ks(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of xo(t)){let i=Qs(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${xo(t).map(Pe).join(" ")}" -a "${Pe(s)}" -d "${i}"`);for(let r of Wt(s)){let a=Ks(r,[`__fish_seen_subcommand_from ${Pe(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
|
|
527
|
+
`)}function Qs(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ks(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Qs(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function Ek(){let e=await Yi(),o=new yp().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=Xi(n);Zi(s)&&Qi("cli",s)});for(let t of[hr,pr,Lo,Ye,Vi,Oo,nn,wo,_o,tn,yo,jr,Lr,Yr,Qr,Xr,oa,Nt,Ka,xt,po,cc])o.addCommand(t);for(let t of dc)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=dc.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,wp(t,74," "),""].join(`
|
|
528
|
+
`)}),o}var dc=[Z,it,Wo,ze,Et,nt,De,ro,bo,Do,lt,dt,ho,Ne,At,wn,Ha,no,et,jo,qt,es,ko,Zo,os,Cn,gt,vo,ec,Ya,za];function wp(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(`
|
|
529
|
+
`)}export{Ek as a};
|
|
530
|
+
//# sourceMappingURL=chunk-LNRB5MCU.js.map
|