agentix-cli 0.26.0 → 0.28.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 +67 -118
- package/apps/mac-helper/Sources/AgentXHelper/AXTree.swift +159 -0
- package/apps/mac-helper/Sources/AgentXHelper/Brand.swift +63 -0
- package/apps/mac-helper/Sources/AgentXHelper/Focus.swift +97 -0
- package/apps/mac-helper/Sources/AgentXHelper/HUD.swift +179 -0
- package/apps/mac-helper/Sources/AgentXHelper/OCR.swift +117 -0
- package/apps/mac-helper/Sources/AgentXHelper/Pointer.swift +309 -0
- package/apps/mac-helper/Sources/AgentXHelper/Screens.swift +67 -0
- package/apps/mac-helper/Sources/AgentXHelper/Typer.swift +185 -0
- package/apps/mac-helper/Sources/AgentXHelper/Vision.swift +201 -0
- package/apps/mac-helper/Sources/AgentXHelper/main.swift +265 -0
- package/apps/mac-helper/build.sh +39 -0
- package/apps/mac-voice/Resources/Info.plist +18 -0
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +108 -0
- package/apps/mac-voice/Sources/AgentXVoice/Brand.swift +123 -0
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +68 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hold.swift +74 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hotkey.swift +76 -0
- package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +140 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +275 -0
- package/apps/mac-voice/Sources/AgentXVoice/Progress.swift +147 -0
- package/apps/mac-voice/Sources/AgentXVoice/Recorder.swift +139 -0
- package/apps/mac-voice/Sources/AgentXVoice/ResultCard.swift +162 -0
- package/apps/mac-voice/Sources/AgentXVoice/SmartPaste.swift +72 -0
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +192 -0
- package/apps/mac-voice/Sources/AgentXVoice/StepLabel.swift +159 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +380 -0
- package/apps/mac-voice/build.sh +32 -0
- package/dist/{App-BPNHIGUX.js → App-CKPH3HHF.js} +2 -2
- package/dist/{ChatApp-6XSSZB4U.js → ChatApp-MX7IG4K2.js} +2 -2
- package/dist/agent-2U574KBZ.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-M3372FLO.js → board-dashboard-QR7CVTKA.js} +1411 -453
- package/dist/board-dashboard-QR7CVTKA.js.map +1 -0
- package/dist/{builtin-FRKAQMFS.js → builtin-B67DMJ3M.js} +2 -2
- package/dist/calibration-ILS5OI44.js +2 -0
- package/dist/{chunk-V3U4OF7L.js → chunk-3LYM22IV.js} +46 -48
- package/dist/chunk-3LYM22IV.js.map +1 -0
- 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-5IA2CYHN.js +5 -0
- package/dist/{chunk-O6YPEOQF.js.map → chunk-5IA2CYHN.js.map} +1 -1
- package/dist/chunk-64CAIB3C.js +9 -0
- package/dist/chunk-64CAIB3C.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-BH3GTCZ6.js +2 -0
- package/dist/chunk-BH3GTCZ6.js.map +1 -0
- package/dist/chunk-E3UJHQGN.js +1189 -0
- package/dist/chunk-E3UJHQGN.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-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-BVGJSPW4.js → chunk-G2HMRDUQ.js} +7 -7
- package/dist/chunk-G2HMRDUQ.js.map +1 -0
- package/dist/chunk-H2QQU2XV.js +109 -0
- package/dist/chunk-H2QQU2XV.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-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-MHIMGM4G.js +126 -0
- package/dist/chunk-MHIMGM4G.js.map +1 -0
- package/dist/chunk-P5ZBBEPL.js +13 -0
- package/dist/chunk-P5ZBBEPL.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-QHTQPBHU.js +45 -0
- package/dist/chunk-QHTQPBHU.js.map +1 -0
- package/dist/chunk-S2MNL5V6.js +2 -0
- package/dist/chunk-S2MNL5V6.js.map +1 -0
- package/dist/chunk-SCTIUFL4.js +5 -0
- package/dist/{chunk-K2CAPYES.js.map → chunk-SCTIUFL4.js.map} +1 -1
- package/dist/chunk-ULLAE6LE.js +157 -0
- package/dist/chunk-ULLAE6LE.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-VIH7ARPF.js +547 -0
- package/dist/chunk-VIH7ARPF.js.map +1 -0
- 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-YLBERT7N.js +24 -0
- package/dist/chunk-YLBERT7N.js.map +1 -0
- package/dist/chunk-YLGIZRHV.js +114 -0
- package/dist/chunk-YLGIZRHV.js.map +1 -0
- package/dist/chunk-ZMYGXHPT.js +121 -0
- package/dist/chunk-ZMYGXHPT.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-ZLSXGPTV.js +2 -0
- package/dist/{compaction-NWEMOSHA.js → compaction-FD4R23HZ.js} +4 -4
- package/dist/config-HMW3EBZL.js +2 -0
- package/dist/config-mutator-4SZ5YEVD.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-LRYV3QLK.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 +1040 -64
- package/dist/index.js +12 -19
- 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-GSZ5AYAM.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-SQDHE4HV.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-LE6FWYZC.js +2 -0
- package/dist/review-candidates-RQU5KNZM.js +4 -0
- package/dist/review-candidates-RQU5KNZM.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-ILERJXB6.js +2 -0
- package/dist/runner-YRBVNYTY.js +2 -0
- package/dist/scheduler-BFM3EINS.js +2 -0
- package/dist/seat-7WM7II2B.js +2 -0
- package/dist/select-X4KVMOP5.js +2 -0
- package/dist/select-X4KVMOP5.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/types-OIFU3KSQ.js.map +1 -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-2AUFSIKO.js +2 -0
- package/dist/wiki-2AUFSIKO.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 +14 -3
- package/scripts/postinstall.mjs +80 -0
- package/dist/agent-5QMITZT6.js +0 -2
- package/dist/architect-SEPWMWS4.js +0 -2
- package/dist/board-dashboard-M3372FLO.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-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-BTHHSY7D.js +0 -13
- package/dist/chunk-BTHHSY7D.js.map +0 -1
- package/dist/chunk-BVGJSPW4.js.map +0 -1
- package/dist/chunk-D46VZ7K7.js +0 -116
- package/dist/chunk-D46VZ7K7.js.map +0 -1
- package/dist/chunk-DJEZ2HVU.js.map +0 -1
- package/dist/chunk-E5CXCI33.js +0 -155
- package/dist/chunk-E5CXCI33.js.map +0 -1
- package/dist/chunk-FDWOECJY.js +0 -54
- package/dist/chunk-FDWOECJY.js.map +0 -1
- package/dist/chunk-H5D7ATXS.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-K2CAPYES.js +0 -5
- package/dist/chunk-LDHPMJ7M.js.map +0 -1
- package/dist/chunk-METYYZKQ.js +0 -1115
- package/dist/chunk-METYYZKQ.js.map +0 -1
- package/dist/chunk-MTAPOCGA.js +0 -47
- package/dist/chunk-MTAPOCGA.js.map +0 -1
- package/dist/chunk-O6YPEOQF.js +0 -5
- package/dist/chunk-P4VWIVKN.js.map +0 -1
- package/dist/chunk-SR3X25TN.js +0 -3
- package/dist/chunk-SR3X25TN.js.map +0 -1
- package/dist/chunk-UHE5FCPB.js +0 -431
- package/dist/chunk-UHE5FCPB.js.map +0 -1
- package/dist/chunk-V3U4OF7L.js.map +0 -1
- package/dist/chunk-VJUTQAPJ.js +0 -2
- package/dist/chunk-VJUTQAPJ.js.map +0 -1
- package/dist/chunk-VT5XYFDD.js +0 -126
- package/dist/chunk-VT5XYFDD.js.map +0 -1
- package/dist/client-HGKAC6VP.js +0 -2
- package/dist/config-A4RWEJHV.js +0 -2
- package/dist/config-mutator-MNSFUN7D.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-3Q36ZFE6.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-SAUNRCCD.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-HK3WQ7BS.js +0 -2
- package/dist/runner-BFYDWPUO.js +0 -2
- package/dist/scheduler-6T2SU5ST.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-BPNHIGUX.js.map → App-CKPH3HHF.js.map} +0 -0
- /package/dist/{ChatApp-6XSSZB4U.js.map → ChatApp-MX7IG4K2.js.map} +0 -0
- /package/dist/{agent-5QMITZT6.js.map → agent-2U574KBZ.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-HGKAC6VP.js.map → chunk-FIOB3MEX.js.map} +0 -0
- /package/dist/{config-A4RWEJHV.js.map → client-ZLSXGPTV.js.map} +0 -0
- /package/dist/{compaction-NWEMOSHA.js.map → compaction-FD4R23HZ.js.map} +0 -0
- /package/dist/{config-mutator-MNSFUN7D.js.map → config-HMW3EBZL.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → config-mutator-4SZ5YEVD.js.map} +0 -0
- /package/dist/{doctor-3Q36ZFE6.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{heal-HZ3EQD52.js.map → doctor-LRYV3QLK.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-SAUNRCCD.js.map → processes-WU23U2OJ.js.map} +0 -0
- /package/dist/{providers-L27BJ5A6.js.map → program-GSZ5AYAM.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-SQDHE4HV.js.map} +0 -0
- /package/dist/{registry-HK3WQ7BS.js.map → recipes-7S4MC5OJ.js.map} +0 -0
- /package/dist/{runner-BFYDWPUO.js.map → registry-LE6FWYZC.js.map} +0 -0
- /package/dist/{rotation-memo-B3EXXSEH.js.map → rotation-memo-7T75BLEX.js.map} +0 -0
- /package/dist/{scheduler-6T2SU5ST.js.map → routing-ILERJXB6.js.map} +0 -0
- /package/dist/{store-I3HEWVLQ.js.map → runner-YRBVNYTY.js.map} +0 -0
- /package/dist/{surface-usage-PRL6Z4U3.js.map → scheduler-BFM3EINS.js.map} +0 -0
- /package/dist/{timers-5LPZN55J.js.map → seat-7WM7II2B.js.map} +0 -0
- /package/dist/{types-VECTMYTO.js.map → store-MCOA6N4F.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
- /package/dist/{types-Y6ZCZ52Z.js.map → surface-usage-NS74AXSE.js.map} +0 -0
- /package/dist/{wiki-M6YNRFC4.js.map → timers-PCB4ZIBD.js.map} +0 -0
- /package/dist/{workspace-setup-TBQAHYHJ.js.map → types-H5ENIUIT.js.map} +0 -0
- /package/dist/{whatsapp-state-XMTCSRXU.js.map → whatsapp-state-6D6FHHD2.js.map} +0 -0
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
import{a as mr,b as on,g as pr}from"./chunk-5IA2CYHN.js";import{a as Yo,b as rr,f as en,j as gr}from"./chunk-3LYM22IV.js";import{a as cr,c as lr,d as dr}from"./chunk-UCQ2N3KO.js";import{b as ar}from"./chunk-G2HMRDUQ.js";import{a as zo}from"./chunk-GV7S5BAX.js";import{e as Ei}from"./chunk-GSX4NK2N.js";import{c as Ai}from"./chunk-SZDACK6O.js";import{A as Zn,B as es,C as sr,D as ir,a as _i,b as Di,h as Ui,i as Fi,j as kt,k as Zt,l as qi,m as Wi,n as Bi,o as Ji,p as Hi,q as Gi,r as zi,s as Yi,t as Ki,u as Vi,v as Xi,w as Qi,x as Zi,y as er,z as nr}from"./chunk-E3UJHQGN.js";import{i as or,j as Xn,k as tr,l as Qn}from"./chunk-F6CNF7V3.js";import{a as Pi,d as Li,e as Mi}from"./chunk-YLBERT7N.js";import{i as ki,k as Jo,m as Yn,n as xi,p as go,v as Ni}from"./chunk-ULLAE6LE.js";import{b as Ho,c as Xt,d as Qt,e as Go,f as Si,g as Ao,h as $t}from"./chunk-64CAIB3C.js";import{a as ji}from"./chunk-M4AMWP3H.js";import{d as Vn,f as Ri}from"./chunk-4BR7D2OU.js";import{f as Oi,g as Ii,h as Kn}from"./chunk-76Z4VHDX.js";import{a as vi,e as Ci}from"./chunk-ZMYGXHPT.js";import{a as de,b as we,c as Oo,d as Ti}from"./chunk-SCTIUFL4.js";import{b as lo,d as Vt,f as zn}from"./chunk-H2QQU2XV.js";import{b as Bo,c as $i}from"./chunk-EVWEG3VD.js";import{a as Gn,b as ci,c as Pc,d as Yt,e as li,f as ui,g as Mc,h as fi,i as Uc,m as Wo,n as yi,o as wi,s as bi,v as Ye,w as bt}from"./chunk-YLGIZRHV.js";import{a as hi,b as Fc}from"./chunk-AJONZWLT.js";import{a as to,b as qo,e as gi,f as wt}from"./chunk-F4HZTZHW.js";import{a as oo,b as Dc}from"./chunk-L2WSPY6S.js";import{f as di,g as W,h as Kt,j as Oe}from"./chunk-P5ZBBEPL.js";import{g as mi,k as pi,l as Lc}from"./chunk-BH3GTCZ6.js";import{a as _c}from"./chunk-FIOB3MEX.js";import{Command as qc}from"commander";var ur=new qc().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Di({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Oe();import{Command as Bc}from"commander";import{execFileSync as no}from"node:child_process";import{cpSync as $r,existsSync as is,mkdirSync as ns,mkdtempSync as Jc,readFileSync as Hc,rmSync as Gc,writeFileSync as kr}from"node:fs";import{dirname as ss,join as Ie,resolve as vr}from"node:path";import{homedir as sn,release as zc,tmpdir as Yc}from"node:os";import{fileURLToPath as Kc}from"node:url";import{setTimeout as Vc}from"node:timers/promises";import{existsSync as Wc}from"node:fs";import{join as fr}from"node:path";var tn="tn.acme.agentx.voice",nn="AgentX Desktop.app",vt="AgentX Helper.app";function hr(e,o,t){return e!=="darwin"||o!=="arm64"||Number(t.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function yr(e,o){if(o&&!Object.hasOwn(e,o))throw new Error(`Unknown agent: ${o}. Run agentx agent list.`);let t=o||Object.keys(e)[0];if(!t)throw new Error("No agents configured. Run agentx setup first.");return t}function os(e){return`'${e.replace(/'/g,"'\\''")}'`}function wr(e){let o=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),t={AGENTX_VOICE_AGENT:e.agent,AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${os(e.cwd)} && ${os(e.node)} ${os(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
|
+
<plist version="1.0"><dict>
|
|
4
|
+
<key>Label</key><string>${tn}</string>
|
|
5
|
+
<key>ProgramArguments</key><array><string>${o(e.executable)}</string></array>
|
|
6
|
+
<key>WorkingDirectory</key><string>${o(e.cwd)}</string>
|
|
7
|
+
<key>EnvironmentVariables</key><dict>${Object.entries(t).map(([n,s])=>`<key>${n}</key><string>${o(s)}</string>`).join("")}</dict>
|
|
8
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
|
|
9
|
+
<key>ProcessType</key><string>Interactive</string>
|
|
10
|
+
<key>StandardErrorPath</key><string>${o(e.log)}</string>
|
|
11
|
+
</dict></plist>
|
|
12
|
+
`}function ts(e){return fr(e,"Applications",vt,"Contents/MacOS/agentx-mac-helper")}function br(e,o,t){if(t)return t;let n=ts(o);return Wc(n)?n:fr(e,"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper")}function rn(){let e=hr(process.platform,process.arch,zc());if(e)throw new Error(e)}function xt(){return`gui/${process.getuid()}/${tn}`}function Ko(){return Ie(sn(),"Library/LaunchAgents",`${tn}.plist`)}async function xr(){try{no("launchctl",["bootout",xt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{no("launchctl",["print",xt()],{stdio:"pipe"})}catch{return}await Vc(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Sr(){if(!is(Ko()))throw new Error("Run agentx desktop install first.");let e=!0;try{no("launchctl",["print",xt()],{stdio:"pipe"})}catch{e=!1}e||no("launchctl",["bootstrap",`gui/${process.getuid()}`,Ko()],{stdio:"pipe"}),no("launchctl",["kickstart",xt()],{stdio:"pipe"})}function Xc(){let e=ss(Kc(import.meta.url));for(let o of[vr(e,".."),vr(e,"../.."),process.cwd()])try{if(JSON.parse(Hc(Ie(o,"package.json"),"utf8")).name==="agentix-cli"&&is(Ie(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Vo=new Bc("desktop").description("install and control the macOS desktop assistant");Vo.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{rn();let o=W(),t=yr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=Xc(),i=Ie(sn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ie(i,nn)}
|
|
13
|
+
Computer-use helper \u2192 ${Ie(i,vt)}
|
|
14
|
+
Agent \u2192 ${t}
|
|
15
|
+
Daemon \u2192 ${n}
|
|
16
|
+
Starts at login \u2192 ${Ko()}`),e.dryRun)return;try{no("xcrun",["--find","swiftc"],{stdio:"pipe"})}catch{throw new Error("Apple command-line tools are required. Run xcode-select --install, finish installation, then retry.")}let r=Jc(Ie(Yc(),"agentx-desktop-"));try{for(let d of["mac-helper","mac-voice"])$r(Ie(s,"apps",d),Ie(r,d),{recursive:!0,filter:g=>!g.split("/").includes("build")}),no("/bin/bash",[Ie(r,d,"build.sh")],{stdio:"inherit"});let a=Ie(sn(),"Library/Logs/agentx-desktop.err.log"),c=wr({executable:Ie(i,nn,"Contents/MacOS/AgentXVoice"),cwd:process.cwd(),agent:t,url:n,helper:ts(sn()),cli:Ie(s,"dist/cli.js"),node:process.execPath,log:a}),l=Ie(r,"desktop.plist");kr(l,c,{mode:384}),no("plutil",["-lint",l],{stdio:"pipe"}),await xr(),ns(i,{recursive:!0});for(let[d,g,u]of[["mac-voice","AgentX Voice.app",nn],["mac-helper",vt,vt]])$r(Ie(r,d,"build",g),Ie(i,u),{recursive:!0});ns(ss(Ko()),{recursive:!0}),ns(ss(a),{recursive:!0}),kr(Ko(),c,{mode:384}),Sr(),console.log(`Desktop assistant is running. Hold Option\u2013Space to speak; Command\u2013Option\u2013V for smart paste.
|
|
17
|
+
Allow Microphone for the app and Accessibility / Screen Recording for the helper when macOS asks.
|
|
18
|
+
The AgentX daemon and a speech transcription backend must also be available. Run agentx desktop status to inspect the login service.`)}finally{Gc(r,{recursive:!0,force:!0})}});Vo.command("start").description("start the installed desktop assistant").action(()=>{rn(),Sr(),console.log("Desktop assistant started.")});Vo.command("stop").description("stop the desktop assistant until started again or next login").action(async()=>{rn(),await xr(),console.log("Desktop assistant stopped.")});Vo.command("status").description("show the desktop login service status").action(()=>{rn();try{console.log(no("launchctl",["print",xt()],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}))}catch{console.log(is(Ko())?"Installed, but not running. Run agentx desktop start.":"Not installed. Run agentx desktop install.")}});import{Command as nl}from"commander";import{open as sl}from"fs/promises";import{existsSync as ln,mkdirSync as Qc,readFileSync as dn,writeFileSync as Er}from"fs";import{homedir as Zc}from"os";import{dirname as el,resolve as rs}from"path";var as="/attach/",Ar="/guard/check";function Or(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 an(e,o,t){let n={hooks:[{type:"command",command:Or(e,o),timeout:10}]};return t!==void 0&&(n.matcher=t),n}function ol(e){return{SessionStart:[an("/attach/session-start",e,"")],UserPromptSubmit:[an("/attach/prompt",e)],Stop:[an("/attach/stop",e)],SessionEnd:[an("/attach/session-end",e)]}}function tl(e){let o=Or("/guard/check",e);return[{matcher:"Bash",hooks:[{type:"command",command:o,timeout:10}]},{matcher:"Write|Edit",hooks:[{type:"command",command:o,timeout:10}]}]}function cn(e,o){return Array.isArray(e?.hooks)&&e.hooks.some(t=>typeof t?.command=="string"&&t.command.includes(o))}function St(){return rs(Zc(),".claude/settings.json")}function Et(e=process.cwd()){for(let o of[e,rs(e,"..")]){let t=rs(o,"agentx.json");if(ln(t))try{let n=JSON.parse(dn(t,"utf-8"))?.node?.bind,s=String(n??"").split(":")[1];if(s)return s}catch{}}return"19900"}function Ir(e,o={}){let t=o.path??St(),n=o.withGuard!==!1,s={};if(ln(t))try{s=JSON.parse(dn(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(ol(e))){let u=Array.isArray(r[d])?r[d].filter(p=>!cn(p,as)):[];r[d]=[...u,...g],a.push(d)}let c=!1;if(n){let d=Array.isArray(r.PreToolUse)?r.PreToolUse.filter(g=>!cn(g,Ar)):[];r.PreToolUse=[...d,...tl(e)],c=!0}let l=JSON.stringify(s)!==i;return l&&(Qc(el(t),{recursive:!0}),Er(t,`${JSON.stringify(s,null,2)}
|
|
19
|
+
`)),{path:t,changed:l,events:a,guardInstalled:c}}function Cr(e={}){let o=e.path??St();if(!ln(o))return{path:o,changed:!1,events:[],guardInstalled:!1};let t;try{t=JSON.parse(dn(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"?Ar:as;if(a==="PreToolUse"&&e.keepGuard!==!1)continue;let l=s[a].filter(d=>!cn(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&&Er(o,`${JSON.stringify(t,null,2)}
|
|
20
|
+
`),{path:o,changed:r,events:i,guardInstalled:!1}}function gn(e=St()){if(!ln(e))return!1;try{return!!JSON.parse(dn(e,"utf-8"))?.hooks?.Stop?.some?.(t=>cn(t,as))}catch{return!1}}var mn=new nl("monitor").description("Register external CLI sessions and report ended runs to the briefing"),jr=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Et()}`;async function Rr(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)}`)}mn.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",jr).action(async e=>{try{await Rr(e.url,"register",Li.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}});mn.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",jr).action(async e=>{try{let o=await sl(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]
|
|
21
|
+
`:"")+i.subarray(0,r).toString("utf8")}finally{await o.close()}await Rr(e.url,"ended",Mi.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 zp}from"commander";import{Command as il}from"commander";Oe();import O from"chalk";import{existsSync as rl,readFileSync as al}from"fs";async function cl(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 Ke=new il().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ke.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(O.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${p||"?"}).`)),console.error(O.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(O.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(O.green(`Daemon started in background (PID: ${k.pid})`)),console.log(O.dim(` Logs: tail -f ${w}`)),console.log(O.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(k.pid,0)}catch{console.log(),console.log(O.yellow(` Daemon exited within 1s \u2014 check ${w} for the error:`)),console.log(O.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 cl(l)&&(console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{ll(i(process.cwd(),".env"))}catch{}await new es(e.config).start()});function ll(e){if(!rl(e))return;let o=al(e,"utf-8");for(let t of o.split(`
|
|
22
|
+
`)){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}}Ke.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(O.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(O.green("Daemon stopped"))}catch{console.log(O.yellow("No daemon process found"))}});Ke.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=W(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(O.bold(` ${r.node.name}`)+O.dim(` (${r.node.id})`)),console.log(O.green(" Status: running")+O.dim(` \u2014 uptime ${dl(r.uptime)}`)),console.log(),console.log(O.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?O.yellow(` [${c.active} active]`):"",d=c.errors>0?O.red(` (${c.errors} errors)`):"";console.log(` ${O.cyan(c.name)} ${O.dim(`(${c.tier})`)}${l}${d}`),console.log(O.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(O.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?O.green("\u25CF"):O.dim("\u25CB"),d=c.nextRun?O.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${d}`)}}if(r.mesh?.length){console.log(),console.log(O.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?O.green("\u25CF"):O.red("\u25CF"),d=c.skills?.length?O.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${O.dim(c.peerUrl)}${d}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(O.red(" Daemon is not running")),console.log(O.dim(" Start with: agentx daemon start"));else try{let t=W(e.config),n=Kt(t);if(console.log(),console.log(O.bold(` ${t.node.name}`)+O.dim(` (${t.node.id})`)),console.log(O.yellow(" Status: stopped")),console.log(O.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(O.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(O.red(` ${t.message}`))}}});Ke.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(O.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"})});Ke.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(W(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(O.dim(` Connecting to ${n}...`)),console.log(O.dim(` Press Ctrl+C to stop
|
|
23
|
+
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(O.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(`
|
|
24
|
+
`);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(`${O.dim(p)} ${O.cyan("\u25B6")} ${f}`):f.includes("completed")?console.log(`${O.dim(p)} ${O.green("\u2713")} ${f}`):f.includes("error")||f.includes("Error")?console.log(`${O.dim(p)} ${O.red("\u2717")} ${f}`):f.includes("Routing")?console.log(`${O.dim(p)} ${O.yellow("\u2192")} ${f}`):f.includes("mention")?console.log(`${O.dim(p)} ${O.magenta("@")} ${f}`):f.includes("Skipping")?console.log(`${O.dim(p)} ${O.dim("\u2298")} ${O.dim(f)}`):console.log(`${O.dim(p)} ${f}`)}catch{}else g.startsWith("event: status")}}catch(s){console.log(O.red(` Connection failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Diagnostic order:")),console.log(O.dim(" 1) agentx daemon status # is the daemon up?")),console.log(O.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(O.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(O.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(O.dim(" to see the error in the foreground."))}});Ke.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=W(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(O.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(O.red(` Error: ${g.error}`)):(console.log(),console.log(g.content||g.response||"No response"),g.duration&&console.log(O.dim(`
|
|
25
|
+
(${(g.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(O.red(` Failed: ${s.message}`)),console.log(O.dim(" Is the daemon running? Try: agentx daemon status"))}});Ke.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(O.dim(" Running tests...")),t("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Tests passed"))}catch{console.log(O.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(O.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(O.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(O.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),t("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(O.green(" \u2713 Build complete")))}console.log(O.dim(` Deploying to ${o.user}@${e}:${o.path}...`));try{if(t(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(O.green(" \u2713 Deploy complete")),o.restart){console.log(O.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(O.green(" Remote daemon restarted"))}}catch(i){console.log(O.red(` Deploy failed: ${i.message}`))}});Ke.action(async e=>{await new es(e.config).start()});function dl(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 gl}from"commander";import Be from"chalk";import{existsSync as At,readFileSync as ml,writeFileSync as Tr,mkdirSync as Nr}from"fs";import{hostname as _r}from"os";import{resolve as Xo}from"path";var Dr=new gl().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let o=process.cwd(),t=Xo(o,"agentx.json"),n=Xo(o,".env"),s=Xo(o,".agentx/sessions");if(console.log(),console.log(Be.bold(" agentx init")),console.log(),At(t)&&!e.force){console.log(Be.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[Xo(o,"agentx.example.json"),Xo(o,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(At(c)){r=ml(c,"utf-8");break}r||(r=JSON.stringify({node:{id:_r().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:_r(),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)),Tr(t,r),console.log(Be.green(" \u2713 Created agentx.json")),At(n)||(Tr(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
26
|
+
`)),console.log(Be.green(" \u2713 Created .env template"))),At(s)||(Nr(s,{recursive:!0}),console.log(Be.green(" \u2713 Created .agentx/sessions/")));let a=Xo(o,".claude");At(a)||(Nr(a,{recursive:!0}),console.log(Be.green(" \u2713 Created .claude/"))),console.log(),console.log(Be.bold(" Next steps:")),console.log(` 1. Edit ${Be.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${Be.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${Be.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${Be.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as pl}from"commander";import Io from"chalk";import{spawn as Lr}from"child_process";import{existsSync as ul}from"fs";import{dirname as fl,resolve as hl}from"path";import{fileURLToPath as yl}from"url";Oe();var Mr=new pl().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=rr(),t=e.port?parseInt(e.port,10):wl(),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 $l(n).catch(()=>!1))console.log(Io.dim(" Dashboard is already running.")),e.open!==!1&&Pr(n);else{console.log(Io.dim(` Starting dashboard server on port ${t} (Ctrl-C to quit)\u2026`));let i=bl(),r=Lr(process.execPath,[i,"board","serve","--port",String(t)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Pr(n),await new Promise(a=>r.on("exit",()=>a()))}});function wl(){try{return W().dashboard.port||4202}catch{return 4202}}function bl(){let e=hl(fl(yl(import.meta.url)),"cli.js");return ul(e)?e:process.argv[1]||e}async function $l(e){try{let o=await fetch(e,{method:"GET"});return o.ok||o.status===302}catch{return!1}}function Pr(e){let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let t=Lr(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 kl}from"commander";import ve from"chalk";var Ot=new kl().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Ot.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 en,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(ve.bold(" Token created.")),console.log(),console.log(` id: ${ve.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||ve.dim("never")}`),console.log(),console.log(ve.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${ve.green.bold(s)}`),console.log(),console.log(ve.dim(" Use it via the Authorization header:")),console.log(ve.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});Ot.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new en().list();if(e.length===0){console.log(ve.dim(`
|
|
27
|
+
No tokens issued.
|
|
28
|
+
`));return}console.log();for(let o of e){let t=o.revokedAt?ve.red("revoked"):o.expiresAt&&Date.parse(o.expiresAt)<Date.now()?ve.red("expired"):ve.green("active");console.log(` ${ve.cyan(o.id)} ${t} ${o.name}`),console.log(ve.dim(` prefix: ${o.prefix}\u2026 scopes: ${o.scopes.join(", ")}`)),console.log(ve.dim(` created: ${o.createdAt}${o.expiresAt?` expires: ${o.expiresAt}`:""}${o.lastUsedAt?` last used: ${o.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(ve.red(` ${e.message}`)),process.exit(1)}});Ot.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let o=new en().revoke(e);o||(console.log(ve.red(` Token ${e} not found.`)),process.exit(1)),console.log(ve.green(`
|
|
29
|
+
\u2713 Revoked ${e} (${o.name})
|
|
30
|
+
`))}catch(o){console.log(ve.red(` ${o.message}`)),process.exit(1)}});Oe();import{Command as Xe}from"commander";import h from"chalk";import Ae from"prompts";import{readFileSync as po,writeFileSync as Qo,existsSync as ge,mkdirSync as Ve,cpSync as cs,readdirSync as ds}from"fs";import{resolve as J,join as mo,dirname as vl}from"path";import{fileURLToPath as xl}from"url";function ne(){let e=J(process.cwd(),"agentx.json");if(!ge(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(po(e,"utf-8"))}function Ne(e){return de(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 Co=new Xe().name("agent").description("manage agents \u2014 add, list, remove");Co.command("list").alias("ls").description("list configured agents").action(()=>{let e=ne();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()});Co.command("add").description("add a new agent interactively").action(async()=>{let e=ne(),o=await Ae([{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:J(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:mo(o.workspace,o.id);Ve(J(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=J(process.cwd(),"src/wiki/SKILL.md"),a=J(vl(xl(import.meta.url)),"../wiki/SKILL.md"),c=ge(r)?r:a;ge(c)&&(Ve(J(t,".claude/skills/wiki"),{recursive:!0}),cs(c,J(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Ne(e),console.log(h.green(`
|
|
31
|
+
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()});Co.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=ne();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Ne(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});Co.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=ne(),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 Ne(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 It=new Xe().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");It.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=ne().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(`
|
|
32
|
+
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
33
|
+
`));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()});It.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=ne();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-HMW3EBZL.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Ae({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 Ae({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 Ae({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 Ae({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 Ae({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 Ae({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 Ne(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`))});It.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=ne(),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 Ne(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});It.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=ne().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)});Co.addCommand(It);var pn=new Xe().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");pn.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=ne();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});pn.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=ne(),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 Ae({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await Ae([{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 Ne(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Ae([{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 Ae([{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 Ne(e),Ve(J(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Ae([{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 Ae([{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 Ne(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 Xe().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Zo.command("list").alias("ls").description("list cron jobs").action(()=>{let e=ne();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=ne(),o=Object.keys(e.agents||{}),t=await Ae([{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 Ne(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=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await Ne(o),console.log(h.green(` Cron "${e}" enabled`))});Zo.command("disable <id>").description("disable a cron job").action(async e=>{let o=ne();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Ne(o),console.log(h.green(` Cron "${e}" disabled`))});var et=new Xe().name("mesh").description("manage mesh peers \u2014 add, list, remove");et.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=ne();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=ne(),o=await Ae([{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 Ne(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=ne();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Ne(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=ne();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 Ne(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 Xe().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=ne(),n=J(e);if(!ge(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ge(mo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Ae({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=J(a.workspace,".claude/skills",s);Ve(c,{recursive:!0}),ge(mo(n,"SKILL.md"))?cs(n,c,{recursive:!0}):n.endsWith(".md")&&cs(n,mo(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=ne();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=J(t.workspace,".claude/skills"),s=ge(n)?ds(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]:[J(n,"src",e,"SKILL.md"),J(n,"skills",e,"SKILL.md")],i=s.find(k=>ge(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=po(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=W()}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||!ge(x)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+(x||"undefined")+")")}`),w++;continue}let A=J(x,".claude/skills",e),v=J(A,"SKILL.md");if(!ge(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||(Ve(A,{recursive:!0}),Qo(v,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let E=po(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||Qo(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=ne().agents?.[e.workspace];p||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(J(p.workspace))}else if(e.allWorkspaces){let u=ne();for(let p of Object.values(u.agents||{}))p?.workspace&&i.push(J(p.workspace))}else i.push(J(e.cwd));let r=J(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=ne(),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-X4KVMOP5.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(`
|
|
34
|
+
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(`
|
|
35
|
+
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Ct=new Xe().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Ct.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=J(o.cwd),n=J(t,"references/example"),s=J(t,"references/recipes/example.yaml");ge(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=J(t,".agentx/references",e),r=J(t,".agentx/references/recipes");Ve(i,{recursive:!0}),Ve(r,{recursive:!0});let a=ds(n).filter(g=>g.endsWith(".yaml")||g.endsWith(".yml")),c=0,l=0;for(let g of a){let u=mo(i,g);if(ge(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let f=po(mo(n,g),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Qo(u,f),console.log(h.green(` + ${u}`)),c++}let d=mo(r,`${e}.yaml`);if(ge(d)&&!o.force)console.log(h.dim(` skip ${d} (exists; --force to overwrite)`)),l++;else if(ge(s)){let g=po(s,"utf-8").replaceAll("example.",`${e}.`);Qo(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()});Ct.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=J(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=J(o.referencesCwd||o.cwd),u=J(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(`
|
|
36
|
+
--- ${w} ---`)),console.log(y.split(`
|
|
37
|
+
`).slice(0,30).map(k=>` ${k}`).join(`
|
|
38
|
+
`)),y.split(`
|
|
39
|
+
`).length>30&&console.log(h.dim(` \u2026 (${y.split(`
|
|
40
|
+
`).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}Ve(u,{recursive:!0});let p=0,f=0;for(let[w,y]of Object.entries(d)){let k=mo(u,w);if(ge(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),f++;continue}Qo(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()});Ct.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(J(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 gs=new Xe().name("hook").description("manage hooks \u2014 add to agent workspace");gs.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=ne().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=J(t.workspace,".claude/settings.json"),s=ge(n)?JSON.parse(po(n,"utf-8")):{},i=await Ae([{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),Ve(J(t.workspace,".claude"),{recursive:!0}),Qo(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var ms=new Xe().name("migrate").description("import configuration from OpenClaw or other tools");ms.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,J(process.env.HOME||"",".openclaw/openclaw.json"),J(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let p of t)if(p&&ge(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(po(n,"utf-8")),i=ge(J(process.cwd(),"agentx.json"))?ne():{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){Ve(J(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=J(n,"../cron/jobs.json");if(ge(u)){let p=JSON.parse(po(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(`
|
|
41
|
+
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Ne(i),console.log(h.green(`
|
|
42
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var uo=new Xe().name("config").description("validate and inspect configuration");uo.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=W(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=Kt(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=ge(J(r,".claude")),c=ge(J(r,"CLAUDE.md")),l=ge(J(r,".claude/settings.json")),d=ge(J(r,".claude/skills"))?ds(J(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()});uo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=W(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Sl(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 ls(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}uo.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-4SZ5YEVD.js"),{expandEnvVars:r}=await import("./config-HMW3EBZL.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(ls(d))});uo.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-4SZ5YEVD.js"),r=Sl(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: ${ls(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${ls(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})`)))});uo.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-4SZ5YEVD.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.")))});uo.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=W(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 El}from"commander";import fo from"chalk";import{resolve as ho}from"path";import{existsSync as Al}from"fs";var so=new El().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ro(e){let o=ho(e,".agentx/db.sqlite");Al(o)||(console.log(fo.red(` No SQLite at ${o}`)),console.log(fo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=ji({path:o});return t||(console.log(fo.red(` Could not open ${o}`)),console.log(fo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function To(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(fo.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])))}so.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(ho(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=`
|
|
43
|
+
SELECT agent_id, channel, status, duration_ms,
|
|
44
|
+
input_tokens, output_tokens,
|
|
45
|
+
substr(message_preview, 1, 60) AS message,
|
|
46
|
+
started_at
|
|
47
|
+
FROM task_history
|
|
48
|
+
${t.length?"WHERE "+t.join(" AND "):""}
|
|
49
|
+
ORDER BY started_at DESC
|
|
50
|
+
LIMIT @limit
|
|
51
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});To(i,!!e.json)});so.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(ho(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?`
|
|
52
|
+
SELECT agent_id, reason, COUNT(*) AS n,
|
|
53
|
+
ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
|
|
54
|
+
MAX(last_turn_input_tokens) AS max_input_tokens
|
|
55
|
+
FROM rotations
|
|
56
|
+
${s}
|
|
57
|
+
GROUP BY agent_id, reason
|
|
58
|
+
ORDER BY n DESC
|
|
59
|
+
`:`
|
|
60
|
+
SELECT agent_id, channel, reason, last_turn_input_tokens, rotated_at
|
|
61
|
+
FROM rotations
|
|
62
|
+
${s}
|
|
63
|
+
ORDER BY rotated_at DESC
|
|
64
|
+
LIMIT @limit
|
|
65
|
+
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});To(r,!!e.json)});so.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(ho(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=`
|
|
66
|
+
SELECT day, agent_id, model, tasks,
|
|
67
|
+
input_tokens AS in_tok, output_tokens AS out_tok,
|
|
68
|
+
cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
|
|
69
|
+
FROM usage_daily
|
|
70
|
+
${t.length?"WHERE "+t.join(" AND "):""}
|
|
71
|
+
ORDER BY day DESC, agent_id
|
|
72
|
+
`,i=o.prepare(s).all(n);To(i,!!e.json)});so.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(ho(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?`
|
|
73
|
+
SELECT channel, kind, deciding_stage, COUNT(*) AS n
|
|
74
|
+
FROM route_traces
|
|
75
|
+
${s}
|
|
76
|
+
GROUP BY channel, kind, deciding_stage
|
|
77
|
+
ORDER BY n DESC
|
|
78
|
+
`:`
|
|
79
|
+
SELECT channel, chat_id, kind, deciding_stage, agent_id,
|
|
80
|
+
substr(reason, 1, 60) AS reason, at
|
|
81
|
+
FROM route_traces
|
|
82
|
+
${s}
|
|
83
|
+
ORDER BY at DESC
|
|
84
|
+
LIMIT @limit
|
|
85
|
+
`,r=o.prepare(i).all({...n,limit:Number(e.limit)});To(r,!!e.json)});so.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(ho(e.cwd)),t=["status = 'error'"],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent);let s=`
|
|
86
|
+
SELECT agent_id, channel, duration_ms,
|
|
87
|
+
substr(error, 1, 120) AS error,
|
|
88
|
+
started_at
|
|
89
|
+
FROM task_history
|
|
90
|
+
WHERE ${t.join(" AND ")}
|
|
91
|
+
ORDER BY started_at DESC
|
|
92
|
+
LIMIT @limit
|
|
93
|
+
`,i=o.prepare(s).all({...n,limit:Number(e.limit)});To(i,!!e.json)});so.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let o=Ro(ho(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}));To(n,!!e.json)});so.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(ho(o.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(fo.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(fo.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=t.prepare(e).all();To(n,!!o.json)}catch(n){console.log(fo.red(` ${n.message}`)),process.exit(1)}});import{Command as Cl}from"commander";import G from"chalk";import{mkdtempSync as jl}from"fs";import{tmpdir as Rl}from"os";import{resolve as Fr,join as qr}from"path";import{existsSync as Tl}from"fs";import Nl from"better-sqlite3";function Ur(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=Ol(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=Ci(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:Il(l,p)})}return{eventsCount:o.length,decisionsCount:a,divergences:r,skipped:[]}}function Ol(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Il(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 yo=new Cl().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function ot(e){let o=Fr(e.cwd??process.cwd()),t=Fr(o,e.path??".agentx/intent/ledger.sqlite");Tl(t)||(console.log(G.red(` No ledger at ${t}`)),console.log(G.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 Nl(t,{readonly:!0})}catch(n){console.log(G.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(G.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function No(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(G.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 _l(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 un(e){if(!e)return;let o=_l(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(G.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}yo.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=un(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(`
|
|
94
|
+
SELECT COUNT(*) as n FROM intent_decisions d
|
|
95
|
+
LEFT JOIN intent_resolutions r
|
|
96
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
97
|
+
WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
|
|
98
|
+
`).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(G.bold("Events by source")),No(r,!1),console.log(),console.log(G.bold(`Decisions: ${a}`)),No(c,!1),console.log(),console.log(G.bold(`Divergences: ${l}`)),No(d,!1),console.log(),console.log(G.bold(`In-flight (dispatched, no resolution): ${g}`))});yo.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=un(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(`
|
|
99
|
+
SELECT
|
|
100
|
+
datetime(ts/1000, 'unixepoch') AS at,
|
|
101
|
+
source,
|
|
102
|
+
decided_by,
|
|
103
|
+
ledger_outcome AS L_outcome,
|
|
104
|
+
COALESCE(ledger_agent_id, '-') AS L_agent,
|
|
105
|
+
legacy_outcome AS X_outcome,
|
|
106
|
+
COALESCE(legacy_agent_id, '-') AS X_agent,
|
|
107
|
+
substr(COALESCE(legacy_reason, ledger_reason, ''), 1, 60) AS reason
|
|
108
|
+
FROM intent_divergences
|
|
109
|
+
${i}
|
|
110
|
+
ORDER BY ts DESC
|
|
111
|
+
LIMIT @limit
|
|
112
|
+
`).all(s);No(r,!!e.json)});yo.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(`
|
|
113
|
+
SELECT
|
|
114
|
+
datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
|
|
115
|
+
e.source,
|
|
116
|
+
d.decided_by,
|
|
117
|
+
COALESCE(d.agent_id, '-') AS agent,
|
|
118
|
+
COALESCE(e.project, '-') AS project,
|
|
119
|
+
COALESCE(e.subject, '-') AS subject,
|
|
120
|
+
ROUND((strftime('%s', 'now')*1000 - d.decided_at) / 1000.0) AS age_s
|
|
121
|
+
FROM intent_decisions d
|
|
122
|
+
JOIN intent_events e ON e.id = d.event_id
|
|
123
|
+
LEFT JOIN intent_resolutions r
|
|
124
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
125
|
+
WHERE ${t.join(" AND ")}
|
|
126
|
+
ORDER BY d.decided_at DESC
|
|
127
|
+
LIMIT @limit
|
|
128
|
+
`).all(n);No(s,!!e.json)});yo.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=un(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(`
|
|
129
|
+
SELECT
|
|
130
|
+
datetime(ts/1000, 'unixepoch') AS at,
|
|
131
|
+
source,
|
|
132
|
+
COALESCE(project, '-') AS project,
|
|
133
|
+
COALESCE(subject, '-') AS subject,
|
|
134
|
+
COALESCE(intent, '-') AS intent
|
|
135
|
+
FROM intent_events
|
|
136
|
+
${i}
|
|
137
|
+
ORDER BY ts DESC
|
|
138
|
+
LIMIT @limit
|
|
139
|
+
`).all(s);No(r,!!e.json)});yo.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(G.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(G.red(` no event with id ${e}`)),process.exit(1)),n=g.project,s=g.subject,(n===null||s===null)&&(console.log(G.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(G.dim(` project: ${n}`)),s&&console.log(G.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
|
|
140
|
+
FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(G.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(`
|
|
141
|
+
SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
|
|
142
|
+
r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
|
|
143
|
+
FROM intent_decisions d
|
|
144
|
+
LEFT JOIN intent_resolutions r
|
|
145
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
146
|
+
WHERE d.event_id IN (${a})
|
|
147
|
+
ORDER BY d.decided_at ASC
|
|
148
|
+
`).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(G.bold(` Lineage for ${G.cyan(n+":"+s)}`)),console.log(G.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(` ${G.dim(u)} ${G.bold(g.id)} ${G.dim(`(${g.source}/${g.intent})`)}`);let p=l.filter(f=>f.event_id===g.id);if(p.length===0){console.log(G.dim(" (no decisions yet)"));continue}for(let f of p){let w=f.outcome==="dispatched"?G.green(f.outcome):f.outcome==="dropped"?G.dim(f.outcome):G.yellow(f.outcome),y=f.agent_id?G.cyan(f.agent_id):G.dim("-"),k=f.reason?G.dim(` \u2014 ${f.reason.slice(0,60)}`):"";if(console.log(` ${G.dim(f.decided_by)} \u2192 ${w} ${y}${k}`),f.resolution_status){let b=f.resolution_status==="ok"?G.green(f.resolution_status):G.red(f.resolution_status),x=f.duration_ms?`${(f.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${G.dim("resolved")} ${b} ${G.dim(x)}`)}else f.outcome==="dispatched"&&console.log(` ${G.yellow("(in-flight, no resolution)")}`)}}console.log()});yo.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=un(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(`
|
|
149
|
+
SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
150
|
+
FROM intent_events
|
|
151
|
+
${n.length?"WHERE "+n.join(" AND "):""}
|
|
152
|
+
ORDER BY ts ASC
|
|
153
|
+
${i}
|
|
154
|
+
`).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(G.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(`
|
|
155
|
+
SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
|
|
156
|
+
FROM intent_decisions
|
|
157
|
+
WHERE event_id IN (${c})
|
|
158
|
+
`).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(`
|
|
159
|
+
SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
|
|
160
|
+
FROM intent_resolutions
|
|
161
|
+
WHERE decision_event_id IN (${c})
|
|
162
|
+
`).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=jl(qr(Rl(),"agentx-ledger-replay-")),p=new vi({path:qr(u,"target.sqlite")});try{let f=Ur(p,r,d,g);if(e.json){console.log(JSON.stringify(f,null,2));return}console.log(G.bold(`Replayed ${f.eventsCount} events, ${f.decisionsCount} decisions, ${g.length} resolutions`)),f.divergences.length===0?console.log(G.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(G.red(` \u2717 ${f.divergences.length} divergences`)),No(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()}});li();Lc();Mc();Uc();Pc();yi();wt();import{Command as Dl}from"commander";import U from"chalk";import{existsSync as Wr}from"fs";import{resolve as ps}from"path";import Pl from"better-sqlite3";var _e=new Dl().name("decisions").description("inspect the typed-decision shadow store (.agentx/decisions/decisions.sqlite)"),Je=".agentx/decisions/decisions.sqlite";function Ll(e){return ps(ps(e.cwd??process.cwd()),e.path??Je)}function Ze(e,o=!1){let t=Ll(e);Wr(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 Yt({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 us(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 fs(e){return{seat:e.seat,question:e.question,backend:e.backend,model:e.model,structureMode:e.structureMode,since:us(e.since),labeledOnly:!!e.labeled,exploredOnly:!!e.explored,limit:e.limit?Number(e.limit):void 0}}_e.command("stats").description("per-seat call counts, failure rate, repair rate and latency").option("--path <file>","store path",Je).option("--since <window>","e.g. 7d, 12h, or an ISO date").option("--json","raw JSON").action(e=>{let o=Ze(e),t=us(e.since)??0,n=o.db.prepare(`SELECT seat, mode, backend, model, structure_mode AS structureMode,
|
|
163
|
+
COUNT(*) AS calls,
|
|
164
|
+
SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) AS failed,
|
|
165
|
+
SUM(retries) AS retries,
|
|
166
|
+
SUM(truncated) AS truncated,
|
|
167
|
+
ROUND(AVG(latency_ms)) AS avgMs,
|
|
168
|
+
SUM(input_tokens) AS inTokens
|
|
169
|
+
FROM decision_calls
|
|
170
|
+
WHERE ts >= ?
|
|
171
|
+
GROUP BY seat, mode, backend, model, structure_mode
|
|
172
|
+
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
|
|
173
|
+
FROM decision_calls WHERE ts >= ? GROUP BY seat, mode, action, explored
|
|
174
|
+
ORDER BY calls DESC`).all(t);!e.json&&s.length>0&&(console.log(U.bold(`
|
|
175
|
+
policy`)),Qe(s,!1),console.log(U.dim(`
|
|
176
|
+
explored=1 means the policy wanted to skip and the expensive path ran anyway.
|
|
177
|
+
Those are the only rows in the skip region that can ever be graded.`))),o.close()});_e.command("calls").description("recent calls").option("--path <file>","store path",Je).option("--seat <seat>").option("--since <window>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Ze(e),t=["ts >= ?"],n=[us(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,
|
|
178
|
+
structure_mode AS structure, latency_ms AS ms, retries, truncated, error
|
|
179
|
+
FROM decision_calls WHERE ${t.join(" AND ")}
|
|
180
|
+
ORDER BY ts DESC LIMIT ?`).all(...n,Number(e.limit));Qe(s,e.json),o.close()});_e.command("answers <callId>").description("every answer on one call, with its incumbent and label").option("--path <file>","store path",Je).option("--json").action((e,o)=>{let t=Ze(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()});_e.command("label <callId> <question> <value>").description("attach ground truth to one answer (append-only; newest wins)").option("--path <file>","store path",Je).option("--kind <kind>","human | outcome | replay","human").option("--by <who>").option("--note <text>").action((e,o,t,n)=>{let s=Ze(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()});_e.command("unlabeled").description("lowest-confidence unlabeled answers first \u2014 the most informative to label").option("--path <file>","store path",Je).option("--seat <seat>").option("--limit <n>","default 20","20").option("--json").action(e=>{let o=Ze(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()});_e.command("backfill-labels").description("derive ground truth from what actually happened (monitor-prefilter seat)").option("--path <file>","store path",Je).option("--db <file>","observability db holding session_reviews",".agentx/db.sqlite").action(e=>{let o=Ze(e,!0),t=ps(process.cwd(),e.db);Wr(t)||(console.log(U.red(` No observability db at ${t}`)),o.close(),process.exit(1));let n=new Pl(t,{readonly:!0});try{let s=Pi(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
|
|
181
|
+
label those by hand: agentx decisions unlabeled --seat monitor-prefilter`))}finally{n.close(),o.close()}});_e.command("calibrate").description("is this seat's confidence worth anything? reliability, ECE, Brier, temperature").option("--path <file>","store path",Je).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=Ze(e),t=o.gradedRows(fs(e)),n=pi(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(`
|
|
182
|
+
${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(`
|
|
183
|
+
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(`
|
|
184
|
+
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(`
|
|
185
|
+
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(`
|
|
186
|
+
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
|
|
187
|
+
only the decisions this policy chose NOT to skip \u2014 it cannot tell you
|
|
188
|
+
what skipping would cost. Raise decisions.seats.<seat>.explore.`))),console.log(U.bold(`
|
|
189
|
+
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()});_e.command("recalibrate").description("is one global temperature enough, or does calibration differ by group?").option("--path <file>","store path",Je).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=Ze(e),t=o.gradedRows(fs(e)),n=String(e.by).split(",").map(i=>i.trim()).filter(Boolean),s=ui(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(`
|
|
190
|
+
${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.
|
|
191
|
+
`)),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(`
|
|
192
|
+
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(`
|
|
193
|
+
One global temperature is enough. ${n.join("/")} carries no calibration signal here.`)):console.log(U.dim(`
|
|
194
|
+
Neither correction beats the raw confidence out of sample. Leave it alone.`)),o.close()});_e.command("coverage").description("accuracy at each threshold against the traffic it keeps \u2014 read this to pick one").option("--path <file>","store path",Je).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=Ze(e),t=o.gradedRows({...fs(e),labeledOnly:!0}),n=mi(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()});_e.command("consistency").description("does the question hold still? resample one recorded state N times").option("--path <file>","store path",Je).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=>{Wo();let o=Ze(e),t=o.db.prepare(`SELECT id, backend, model, state_json, questions_json FROM decision_calls
|
|
195
|
+
WHERE seat = ? AND state_json IS NOT NULL AND error IS NULL
|
|
196
|
+
${e.call?"AND id = ?":""}
|
|
197
|
+
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 fi(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(`
|
|
198
|
+
${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
|
|
199
|
+
`)),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(`
|
|
200
|
+
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(`
|
|
201
|
+
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.
|
|
202
|
+
Split it, or narrow it to a single clause in the state's own vocabulary.`))):console.log(U.green(`
|
|
203
|
+
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()});_e.command("backends").description("registered decision backends and what they claim").action(()=>{Wo();let e=ci().map(o=>{let t=Gn(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(`
|
|
204
|
+
source where the numbers come from. "verbalized" means the model wrote them
|
|
205
|
+
into its answer; "logits" means they were read off its next-token
|
|
206
|
+
distribution. Logits are the model's actual posterior \u2014 verbalized
|
|
207
|
+
ones are quantized at round values and are not.
|
|
208
|
+
calibrated whether an answer given 0.8 is right about 80% of the time ON YOUR
|
|
209
|
+
traffic. Reading real logits does not buy this: a posterior can be
|
|
210
|
+
confidently wrong. It comes from a recalibrator fitted on your own
|
|
211
|
+
labeled rows \u2014 see \`agentx decisions recalibrate\`.`))});_e.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=>{Wo();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=qo(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 Gn(e.backend).decide({state:e.state,questions:o,model:e.model});console.log(JSON.stringify(n,null,2))});import{Command as Ml}from"commander";import I from"chalk";import{resolve as Br}from"path";import{existsSync as Ul}from"fs";import Fl from"better-sqlite3";var jt=new Ml().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function ys(e){let o=Br(e.cwd??process.cwd()),t=Br(o,e.path??".agentx/db.sqlite");Ul(t)||(console.log(I.red(` No db at ${t}`)),console.log(I.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new Fl(t,{readonly:!0})}catch(n){console.log(I.red(` Could not open ${t}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(I.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function ql(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 Wl(e){if(!e)return;let o=ql(e);if(o===null){let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(I.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-o}function Bl(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 hs(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}jt.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let o=ys(e),t=Ri(o,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:Wl(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(I.dim(" (no traces)"));return}for(let n of t){let s=hs(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?I.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?I.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${I.dim(n.taskId)} ${s} ${I.bold(n.agentId)}${I.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${I.dim("\xB7")} ${i}${a} ${I.dim(Bl(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});jt.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,o)=>{let t=ys(o),n=Vn(t,e);if(n||(console.log(I.red(` No trace at ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}Jl(n.task,n.steps)});function Jl(e,o){let t=hs(e.status)(e.status);if(console.log(I.bold(`Trace ${e.taskId}`)),console.log(` ${I.dim("agent")} ${e.agentId}`),console.log(` ${I.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${I.dim("workflow")} ${I.cyan(e.workflowRunId)}${n?I.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${I.dim("intent")} ${e.intentEventId} ${I.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${I.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${I.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${I.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${I.dim("status")} ${t}`),e.durationMs!=null&&console.log(` ${I.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${I.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.error&&console.log(` ${I.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${I.dim("message")} ${e.messagePreview}`),console.log(),o.length===0){console.log(I.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(I.bold(`Steps (${o.length}):`));for(let n of o){let s=n.status?hs(n.status)(n.status):I.dim("\u2014"),i=n.action?I.cyan(n.action):"";if(console.log(` ${I.dim(`#${n.seq}`)} ${I.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?I.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
|
|
212
|
+
`).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2192")} ${a}`).join(`
|
|
213
|
+
`)),n.inputSummary.split(`
|
|
214
|
+
`).length>8&&console.log(` ${I.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
|
|
215
|
+
`).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2190")} ${a}`).join(`
|
|
216
|
+
`)),n.outputSummary.split(`
|
|
217
|
+
`).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}jt.command("replay <taskId>").description("re-run a recorded task against the current agent config (handoff item #11)").option("--cwd <dir>","project root",process.cwd()).option("--path <p>","sqlite db path (relative to --cwd)",".agentx/db.sqlite").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--diff","show original input + output vs new output side-by-side").option("--no-fresh","do NOT freshSession (default is fresh \u2014 required for clean replay)").action(async(e,o)=>{let t=ys(o),n=Vn(t,e);n||(console.log(I.red(` task not found: ${e}`)),console.log(I.dim(" agentx trace list \u2014 see what's available")),process.exit(1));let s=n.task,i=s.originalMessage??s.messagePreview;i||(console.log(I.red(` task ${e} has no recorded input message \u2014 cannot replay`)),process.exit(1)),!s.originalMessage&&s.messagePreview!=null&&console.log(I.yellow(" \u26A0 pre-migration-v8 row: input message was capped at 200 chars; replay uses the preview")),console.log(),console.log(I.bold(` replay ${I.cyan(e)}`)),console.log(I.dim(` agent=${s.agentId} channel=${s.channel??"\u2014"} chatId=${s.chatId??"\u2014"}`)),console.log(I.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(I.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(I.red(` replay failed (${d.status}): ${g.error||"unknown error"}`)),process.exit(1)),o.diff){console.log(I.bold(" INPUT (replayed verbatim)")),console.log(),fn(i),console.log(),console.log(I.bold(` ORIGINAL OUTPUT ${I.dim(`status=${s.status} ${s.durationMs??"?"}ms`)}`)),console.log(),s.finalResponse?fn(s.finalResponse):console.log(I.yellow(" (not captured \u2014 pre-migration-v8 row, or response was empty)")),console.log(),console.log(I.bold(` CURRENT OUTPUT ${I.dim(`status=${g.error?"error":"ok"} ${u}ms tokens=in:${g.usage?.inputTokens??0}/out:${g.usage?.outputTokens??0}`)}`)),console.log(),fn(g.content??"(empty reply)"),g.error&&console.log(I.red(` error: ${g.error}`)),console.log();let p=(s.finalResponse??"").trim()===(g.content??"").trim();s.finalResponse&&(console.log(p?I.dim(" outputs are identical"):I.yellow(" outputs differ \u2014 read both blocks to see what changed")),console.log())}else console.log(I.green(` \u2713 replayed in ${u}ms`)),console.log(),fn(g.content??"(empty reply)"),g.error&&console.log(I.red(`
|
|
218
|
+
error: ${g.error}`)),console.log(),console.log(I.dim(` agentx trace replay ${e} --diff to compare against the original output`)),console.log()});function fn(e){let o=e.split(`
|
|
219
|
+
`),t=60,n=o.slice(0,t);for(let s of n)console.log(` ${I.dim("\u2502")} ${s}`);o.length>t&&console.log(` ${I.dim("\u2502")} ${I.dim(`\u2026+${o.length-t} more lines`)}`)}import{Command as Yl}from"commander";import ae from"chalk";import{existsSync as Kl,mkdirSync as Vl,writeFileSync as Xl}from"fs";import{resolve as Gr,join as Hr,dirname as Ql}from"path";var Hl=`# AgentX destructive-action guardrails \u2014 global policy
|
|
220
|
+
#
|
|
221
|
+
# This file + environments/*.yaml + agents/<id>.yaml are deep-merged
|
|
222
|
+
# (most specific wins). The built-in catalog (prisma / rm -rf / docker /
|
|
223
|
+
# terraform / git push --force ... patterns) is ALWAYS applied underneath.
|
|
224
|
+
# The guard reads policy live on every tool call \u2014 edits take effect on the
|
|
225
|
+
# next command, no daemon restart needed.
|
|
226
|
+
version: 1
|
|
227
|
+
|
|
228
|
+
# warn = compute + audit but never block (Phase 1 rollout stance).
|
|
229
|
+
# enforce = honor the verdict (deny blocks; escalate asks).
|
|
230
|
+
# off = kill-switch, allow everything.
|
|
231
|
+
# Flip to enforce once \`agentx guard log\` shows an acceptable false-positive rate.
|
|
232
|
+
mode: warn
|
|
233
|
+
|
|
234
|
+
defaults:
|
|
235
|
+
fail_mode: closed # guard error on a protected-target command => deny
|
|
236
|
+
unmatched: allow # commands no rule matches run freely (keep routine work fast)
|
|
237
|
+
|
|
238
|
+
# Extra global rules beyond the catalog go here. Example:
|
|
239
|
+
# rules:
|
|
240
|
+
# - id: no-prod-ssh
|
|
241
|
+
# match: { tool: Bash, command_regex: "ssh ", target_in: production }
|
|
242
|
+
# action: escalate
|
|
243
|
+
# severity: high
|
|
244
|
+
rules: []
|
|
245
|
+
`,Gl=`# Production protected resources.
|
|
246
|
+
#
|
|
247
|
+
# The catalog rules reference \`target_in: production\`, so DECLARING this set is
|
|
248
|
+
# what arms them. \`resolve_env: true\` expands $VAR / \${VAR} and reads .env* in
|
|
249
|
+
# the workspace before matching \u2014 so \`--shadow-database-url $DATABASE_URL\` is
|
|
250
|
+
# caught even though the literal string "production" never appears in the command
|
|
251
|
+
# (this is exactly the 2026-07-21 incident class).
|
|
252
|
+
protected_resources:
|
|
253
|
+
production:
|
|
254
|
+
resolve_env: true
|
|
255
|
+
db_urls:
|
|
256
|
+
- "\${PROD_DATABASE_URL}"
|
|
257
|
+
hosts:
|
|
258
|
+
- "api.demosite.example.com"
|
|
259
|
+
- "203.0.113.12"
|
|
260
|
+
# buckets:
|
|
261
|
+
# - "my-prod-uploads"
|
|
262
|
+
# contexts: # k8s contexts, droplet ids, cluster names
|
|
263
|
+
# - "do-fra1-prod"
|
|
264
|
+
|
|
265
|
+
# Production-only rules beyond the catalog:
|
|
266
|
+
rules: []
|
|
267
|
+
`,zl=`# Per-agent override for coder-agent. Top-level rules here are auto-scoped to
|
|
268
|
+
# this agent (the filename names it). coder agents never touch production.
|
|
269
|
+
rules:
|
|
270
|
+
- id: coder-no-prod
|
|
271
|
+
match:
|
|
272
|
+
target_in: production
|
|
273
|
+
action: deny
|
|
274
|
+
severity: critical
|
|
275
|
+
message: "coder-agent is not permitted to run commands against production."
|
|
276
|
+
`,Jr=[{relPath:"policy.yaml",content:Hl},{relPath:"environments/production.yaml",content:Gl},{relPath:"agents/coder-agent.yaml",content:zl}];var wo=new Yl().name("guard").description("destructive-action guardrails \u2014 policy, checks, audit");function ws(e){return e==="deny"?ae.red:e==="escalate"||e==="ask"?ae.yellow:e==="warn"?ae.magenta:ae.green}function hn(e){return e.root?Gr(e.root):er()}wo.command("check").description("PreToolUse hook entrypoint: read a tool-call payload on stdin, emit a Claude Code decision").option("--agent <id>","agent id this workspace belongs to").option("--root <dir>","AgentX install root (holds .agentx/guardrails + .agentx/db.sqlite)").option("--env <name>","environment scope (e.g. production)").action(async e=>{await Zi({root:hn(e),agentId:e.agent,env:e.env}),process.exit(0)});wo.command("test <command>").description("dry-run a command through the policy engine and print the verdict").option("--agent <id>","evaluate as this agent").option("--env <name>","environment scope").option("--tool <name>","tool name","Bash").option("--cwd <dir>","workspace cwd for $VAR/.env resolution",process.cwd()).option("--root <dir>","AgentX install root (policy source)").option("--enforce","evaluate as if mode=enforce (show what WOULD block)").option("--json","emit JSON").action((e,o)=>{let t=hn(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}Zl(s,i,r)});function Zl(e,o,t){let n=ws(e.action);console.log(),console.log(` policy verdict ${n(e.action.toUpperCase())}${e.matched?"":ae.dim(" (no rule matched)")}`),console.log(` enforced as ${ws(e.effectiveAction)(e.effectiveAction)} ${ae.dim(`(mode=${o})`)}`),e.ruleId&&console.log(` rule ${ae.cyan(e.ruleId)}${e.severity?ae.dim(` [${e.severity}]`):""}`),e.resolvedTarget&&console.log(` resolved target ${ae.yellow(e.resolvedTarget)}`),e.message&&console.log(` message ${e.message}`),console.log(` ${ae.dim(`evaluated in ${t}ms`)}`),console.log()}wo.command("log").description("read the guardrail decision audit trail (newest first)").option("--root <dir>","AgentX install root (holds .agentx/db.sqlite)").option("--verdict <v>","filter by verdict (deny|escalate|warn|allow)").option("--agent <id>","filter by agent").option("--task <id>","filter by task id").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let o=Xi({root:hn(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(ae.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=ws(t.verdict),i=t.effective_action!==t.verdict?ae.dim(`->${t.effective_action}`):"";console.log(` ${ae.dim(n)} ${s(t.verdict.toUpperCase().padEnd(8))}${i} ${ae.cyan((t.agent_id??"?").padEnd(16))} ${ae.dim((t.matched_rule??"-").padEnd(24))} ${(t.command??"").slice(0,70)}`),t.resolved_target&&console.log(ae.dim(` target: ${t.resolved_target}`))}});wo.command("init").description("scaffold .agentx/guardrails/ with a starter policy + protected-resource example").option("--root <dir>","where to create .agentx/guardrails/",process.cwd()).option("--force","overwrite existing files").action(e=>{let o=Hr(Gr(e.root),Ki),t=0;for(let n of Jr){let s=Hr(o,n.relPath);if(Kl(s)&&!e.force){console.log(ae.dim(` skip (exists) ${n.relPath}`));continue}Vl(Ql(s),{recursive:!0}),Xl(s,n.content),console.log(ae.green(` created ${n.relPath}`)),t++}console.log(),console.log(` Guardrails scaffolded under ${ae.cyan(o)}`),console.log(ae.dim(" Edit environments/production.yaml with YOUR prod hosts/URLs, then")),console.log(ae.dim(' `agentx guard test "<cmd>" --enforce` to preview, and flip mode: enforce when ready.'))});wo.command("reload").description("signal the daemon to reload (note: guard policy is read live per tool call already)").option("--url <url>","daemon base url",process.env.AGENTX_DAEMON_URL||"http://localhost:19900").action(async e=>{try{let o=await fetch(`${String(e.url).replace(/\/$/,"")}/reload`,{method:"POST"});o.ok?console.log(ae.green(` daemon reloaded (${e.url})`)):console.log(ae.yellow(` daemon reachable but returned ${o.status}`))}catch(o){console.log(ae.dim(` daemon not reachable (${o.message}). Policy files are still read live on each check.`))}});wo.command("policy").description("print the resolved (merged) policy for an agent").option("--agent <id>","agent id").option("--root <dir>","AgentX install root").action(e=>{let o=Vi(hn(e),e.agent);console.log(JSON.stringify(o,null,2))});bt();import{Command as ad}from"commander";import{execFile as cd}from"child_process";import{promisify as ld}from"util";import{existsSync as dd}from"fs";import He from"chalk";wt();var Tt="ui-element";function yn(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:Rt(t.tried,80),screenChanged:t.changed,note:t.note?Rt(t.note,120):null}))}:{},controls:e.candidates.map(t=>({id:String(t.id),role:zr(t.role),label:Rt(t.label,120),value:t.value?Rt(t.value,80):null,enabled:t.enabled}))}}function wn(e){let o={};for(let t of e){let n=t.label||t.value||"(unlabelled)";o[String(t.id)]=`${zr(t.role)}: ${Rt(n,80)}`}return{target:qo(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 bn(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 zr(e){return e.replace(/^AX/,"").replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Rt(e,o){let t=String(e??"").replace(/\s+/g," ").trim();return t.length>o?t.slice(0,o):t}import{homedir as td}from"node:os";import{execFile as nd}from"child_process";import{promisify as sd}from"util";import{existsSync as id}from"fs";var ed=/^AX(Button|MenuItem|MenuButton|TextField|TextArea|CheckBox|RadioButton|PopUpButton|Link|Tab|Row|Cell|ComboBox|SearchField|Slider|Disclosure|Toolbar|StaticText)/;function od(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 Yr(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 od(e).filter(n=>ed.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 Kr=sd(nd),xe=br(process.cwd(),td(),process.env.AGENTX_MAC_HELPER),rd=6;async function $n(e={}){if(!id(xe))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let{stdout:o}=await Kr(xe,["read","--max","400"]),t=JSON.parse(o),n=Yr(t.elements,e.max??60),s=new Map;if(!(e.ocr!==!1&&n.length<rd))return{app:t.app,window:t.window??null,candidates:n,elements:t.elements,usedOCR:!1,ocrRects:s};try{let{stdout:r}=await Kr(xe,["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 Nt(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 Vr=ld(cd),Xr=new ad().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)=>{dd(xe)||(console.log(He.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1));let t;try{t=await $n({max:Number(o.max)||40})}catch(g){console.log(He.red(` could not read the screen: ${g?.message??g}`)),process.exit(1)}let n=t.candidates;if(n.length===0&&(console.log(He.yellow(` ${t.app} exposes no usable controls and no readable text`)),process.exit(2)),n.length===1){let g=Nt(t,n[0].id);g&&(console.log(He.yellow(` ${t.app} exposes exactly one target \u2014 pointing at it: `)+He.bold(n[0].label)),await Vr(xe,["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 Ye(Tt,yn({request:e,app:t.app,window:t.window,candidates:n}),wn(n),{features:{app:t.app,candidates:n.length,ocr:t.usedOCR}});s||(console.log(He.red(` the ui-element seat is unavailable \u2014 set decisions.seats.${Tt}.mode`)),process.exit(1));let i=bn(s.answers,n),r=Nt(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(He.yellow(` nothing on screen matches "${e}"`)+He.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(` ${He.green("\u2192")} ${He.bold(d)} `+He.dim(`(${c?"read from screen":"control"}, confidence ${i.confidence.toFixed(2)}, P(exists) ${i.present.toFixed(2)})`)),await Vr(xe,["point","--x",String(r.x),"--y",String(r.y),"--w",String(r.width),"--h",String(r.height),"--label",d])});import{Command as Pd}from"commander";import De from"chalk";import{execFile as gd}from"child_process";import{promisify as md}from"util";import{existsSync as pd,readFileSync as bs}from"fs";import{homedir as ud,tmpdir as fd}from"os";import{join as Qr}from"path";var hd=md(gd),Zr=12e5,yd="https://openrouter.ai/api/v1/chat/completions",wd=process.env.AGENTX_VISION_MODEL??"anthropic/claude-sonnet-5";async function bd(e={kind:"window"},o=Zr){if(!pd(xe))throw new Error("helper not built \u2014 run apps/mac-helper/build.sh");let n=["capture","--out",Qr(fd(),`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 hd(xe,n),i=JSON.parse(s);if(!i.ok)throw new Error(i.error??"capture failed");let r=bs(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 $d=`You are reading a screenshot of a macOS screen to answer one question about what is CURRENTLY TRUE on it.
|
|
277
|
+
|
|
278
|
+
Report only what is visible in this image.
|
|
279
|
+
|
|
280
|
+
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.
|
|
281
|
+
|
|
282
|
+
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.
|
|
283
|
+
|
|
284
|
+
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 kd(e,o,t,n){let s=xd();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=bs(o.path).toString("base64"),r={model:t,max_tokens:700,messages:[{role:"user",content:[{type:"text",text:`Question: ${e}
|
|
285
|
+
|
|
286
|
+
The image is the region ${vd(o)}.`},{type:"image_url",image_url:{url:`data:image/png;base64,${i}`}}]}],system:$d,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(yd,{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 kn(e,o={}){let t=Date.now(),n=await bd(o.region??{kind:"window"},o.maxPixels??Zr),s=await kd(e,n,o.model??wd,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 vd(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 _t;function xd(){if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;if(_t!==void 0)return _t??void 0;try{let e=bs(Qr(ud(),".agentx","openrouter-key.txt"),"utf-8").trim();_t=e.length>0?e:null}catch{_t=null}return _t??void 0}import{execFile as Sd}from"child_process";import{promisify as Ed}from"util";var Ad=Ed(Sd),Od=["screencapture"],Id=["Screen Studio","OBS","QuickTime Player","Zoom"];async function oa(e){let o=e.toLowerCase(),t=[];return/record|recording|capturing|screen ?capture|screencast/.test(o)&&t.push(await Cd()),t}async function Cd(){let e=await ea(Od);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 ea(Id);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 ea(e){let o=[];for(let t of e)try{let{stdout:n}=await Ad("pgrep",["-x",t]),s=n.trim().split(`
|
|
287
|
+
`)[0];s&&o.push(`${t} (pid ${s})`)}catch{}return o}bt();wt();var ta="screen-state",na={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 sa(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 ia(e){return{observable:e.observable.noul,holds:e.holds.noul}}var jd=.6,Rd=.7,Td=.3;async function xn(e,o={}){let[t,n]=await Promise.all([kn(e,o),oa(e).catch(()=>[])]),s=o.observableFloor??jd,i=await Ye(ta,sa({claim:e,observation:t.observation,evidence:t.evidence,reading:t.reading,region:Dd(t),treeNote:o.treeNote,probes:n}),na,{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:_d(l,t),sighting:t,probes:n}}let{observable:r,holds:a}=ia(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 (${vn(r)} that the evidence settles it). Seen: ${t.observation||"nothing conclusive"}`,sighting:t,probes:n};let c=a>=Rd?"confirmed":a<=Td?"refuted":"unknown";return{claim:e,outcome:c,ok:c==="confirmed",observable:r,holds:a,calibrated:!0,reason:Nd(c,a,t),sighting:t,probes:n}}function Nd(e,o,t){let n=t.evidence||t.observation||"no specific detail";return e==="confirmed"?`Confirmed (${vn(o)}). ${n}`:e==="refuted"?`Not true (${vn(1-o)} it is false). ${n}`:`Inconclusive (${vn(o)}, between the thresholds). ${n}`}function _d(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 Dd(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 vn=e=>`${Math.round(e*100)}%`;var ra=new Pd().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(De.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 xn(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"?De.green("\u2713"):s.outcome==="refuted"?De.red("\u2717"):De.yellow("?");console.log(` ${i} ${De.bold(s.claim)}`),console.log(` ${s.reason}`),s.calibrated||console.log(De.dim(" (screen-state seat off \u2014 set AGENTX_DECISION_SEAT_SCREEN_STATE=active)")),console.log(De.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 kn(e,{region:t,model:o.model});if(o.json){console.log(JSON.stringify(n,null,2));return}console.log(` ${De.bold(n.observation)}`),n.evidence&&console.log(De.dim(` evidence: ${n.evidence}`)),console.log(` reading: ${Ld(n.reading)}`),console.log(De.dim(` ${n.model} \xB7 ${n.latencyMs}ms \xB7 ${Math.round(n.shot.bytes/1024)}KB \xB7 ${n.shot.path}`))}catch(n){console.log(De.red(` ${n?.message??n}`)),process.exit(1)}});function Ld(e){return e==="yes"?De.green(e):e==="no"?De.red(e):De.yellow(e)}bt();import{Command as Fd}from"commander";import{execFile as ua}from"child_process";import{promisify as qd}from"util";import{existsSync as Wd,readFileSync as Bd,writeFileSync as fa,mkdirSync as Jd}from"fs";import{homedir as Hd}from"os";import{join as Gd,dirname as zd}from"path";import Ce from"chalk";wt();var $s="paste-transform";function aa(e){return{pastingInto:{app:e.app,control:e.destination,label:e.destinationLabel||null},clipboard:{characters:e.length,lines:e.lineCount,preview:e.preview}}}function ca(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:qo(o,"What shape should this paste arrive in?")}}function la(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 Md=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"]),Ud=e=>/^https?:\/\/\S+$/i.test(e.trim()),ks=[{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(`
|
|
288
|
+
`);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(`
|
|
289
|
+
`).map(s=>s.trim()).filter(Boolean).join(" ")).filter(Boolean).join(`
|
|
290
|
+
|
|
291
|
+
`)}},{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(`
|
|
292
|
+
`).map(t=>t.trim()).filter(Boolean);return o.length<2||o.every(t=>/^([-*+]|\d+[.)])\s/.test(t))?null:o.map(t=>`- ${t}`).join(`
|
|
293
|
+
`)}},{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(`
|
|
294
|
+
`);return o.every(t=>t.startsWith(">")||!t.trim())?null:o.map(t=>t.trim()?`> ${t}`:">").join(`
|
|
295
|
+
`)}},{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(!Ud(o))return null;try{let t=new URL(o),n=0;for(let s of[...t.searchParams.keys()])Md.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(`
|
|
296
|
+
`)||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,`
|
|
297
|
+
`).trim();return o===e?null:o}}];function da(e){let o=[];for(let t of ks){let n=t.apply(e);n!==null&&(t.id!=="asIs"&&n===e||o.push({transform:t,result:n}))}return o}function ga(e,o=320){if(e.length<=o)return e;let t=Math.floor(o*.7),n=o-t;return`${e.slice(0,t)}
|
|
298
|
+
\u2026[${e.length-o} more characters]\u2026
|
|
299
|
+
${e.slice(-n)}`}function ma(e){let o=e.trim();return o.includes(`
|
|
300
|
+
`)||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 vs=qd(ua),ha=new Fd().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 (${ks.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=Kd();c===null&&(console.log(Ce.yellow(" nothing to undo")),process.exit(2)),await wa(c),console.log(` ${Ce.green("\u2192")} clipboard restored`);return}let o=await Vd();if(o||(console.log(Ce.yellow(" clipboard is empty")),process.exit(2)),ma(o)){ya(e,{applied:"asIs",reason:"looks like a credential \u2014 left untouched",worthChanging:0});return}let t=da(o),n=await Xd();if(e.as){let c=t.find(l=>l.transform.id===e.as);c||(console.log(Ce.red(` "${e.as}" does not apply to this clipboard`)),console.log(Ce.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 Ye($s,aa({preview:ga(o),length:o.length,lineCount:o.split(`
|
|
301
|
+
`).length,app:n.app,destination:n.role,destinationLabel:n.label}),ca(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.${$s}.mode`,0);return}let i=la(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)&&(Yd(n),await wa(t)),ya(e,{applied:o,reason:s,worthChanging:i,result:t,original:n,changed:r}),e.paste&&await vs(xe,["key","--name","v","--mod","command"]).catch(a=>{console.log(Ce.red(` could not paste: ${a?.message??a}`))})}function ya(e,o){if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.changed){console.log(` ${Ce.dim("\u2192")} ${Ce.bold("unchanged")} ${Ce.dim(`\xB7 ${o.reason}`)}`);return}console.log(` ${Ce.green("\u2192")} ${Ce.bold(o.applied)} ${Ce.dim(`\xB7 ${o.reason}`)}`),console.log(Ce.dim(" \u2500\u2500\u2500 before \u2500\u2500\u2500")),console.log(Ce.dim(pa(o.original))),console.log(Ce.dim(" \u2500\u2500\u2500 after \u2500\u2500\u2500\u2500")),console.log(pa(o.result)),!e.apply&&!e.paste&&console.log(Ce.dim(`
|
|
302
|
+
(dry run \u2014 pass --apply to write it back)`))}var pa=(e,o=400)=>(e.length>o?`${e.slice(0,o)}\u2026`:e).split(`
|
|
303
|
+
`).map(t=>` ${t}`).join(`
|
|
304
|
+
`),Sn=Gd(Hd(),".agentx","paste-undo.txt");function Yd(e){try{Jd(zd(Sn),{recursive:!0}),fa(Sn,e,{mode:384})}catch{}}function Kd(){try{let e=Bd(Sn,"utf-8");return fa(Sn,"",{mode:384}),e.length?e:null}catch{return null}}async function Vd(){let{stdout:e}=await vs("pbpaste",[],{maxBuffer:16777216});return e}async function wa(e){await new Promise((o,t)=>{ua("pbcopy",[],s=>s?t(s):o()).stdin?.end(e)})}async function Xd(){if(!Wd(xe))return{app:"unknown",role:"an unknown control",label:null};try{let{stdout:e}=await vs(xe,["focused"]),o=JSON.parse(e);return o.ok===!1||!o.role?{app:"unknown",role:"an unknown control",label:null}:{app:o.app??"unknown",role:Qd(o.role??"",o.editable),label:o.label||null}}catch{return{app:"unknown",role:"an unknown control",label:null}}}function Qd(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 Zd}from"commander";import Ge from"chalk";var eg=process.env.AGENTX_DAEMON_URL??"http://127.0.0.1:18800";function og(e,o){return async({title:t,message:n,channel:s,chatId:i})=>{let r=t&&!n.startsWith(t)?`${t}
|
|
305
|
+
${n}`:n,a=await fetch(`${eg}/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 ba=new Zd().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 Ji,n=Wi(),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?Ge.yellow("\u25D0"):Ge.green("\u25CB")} ${Bi(n)} ${Ge.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(Ge.dim(` ${c} ${a.from}: ${a.message.slice(0,70)}`))}return}let i=og(o.channel,o.chatId);if(o.flush){let r=await Gi(i,{queue:t,sound:s});console.log(r?Ge.green(` delivered ${r} held notification(s)`):Ge.dim(" nothing was held"));return}e?.trim()||(console.log(Ge.red(" nothing to say \u2014 pass a message, or use --status / --flush")),process.exit(1));try{let r=await Hi({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?Ge.green("\u2192"):Ge.yellow("\u23F8");console.log(` ${a} ${r.reason}`),r.held&&console.log(Ge.dim(" it will arrive with the others when Focus ends"))}catch(r){console.log(Ge.red(` ${r?.message??r}`)),s!==!1&&zi(),process.exit(1)}});bt();yi();li();wt();import{Command as tg}from"commander";import{readFileSync as ng}from"fs";var $a=new tg().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?ng(e.file,"utf8"):await sg()}catch(r){_o(`could not read the spec: ${r?.message??r}`);return}if(!o.trim())return _o("no spec given \u2014 pipe JSON on stdin or pass --file");let t;try{t=JSON.parse(o)}catch(r){return _o(`spec is not valid JSON: ${r?.message??r}`)}if(!t.state)return _o("spec needs a `state`");if(!t.questions||Object.keys(t.questions).length===0)return _o("spec needs at least one entry in `questions`");try{gi(t.questions)}catch(r){return _o(r?.message??String(r))}let n=t.seat||e.seat;Wo(),process.env[bi(n)]="active";let s=null;if(e.record!==!1)try{s=new Yt({})}catch(r){process.stderr.write(`[decide] not recording (${r?.message??r})
|
|
306
|
+
`)}wi({enabled:!0,defaultBackend:e.backend,store:s,seats:{[n]:{mode:"active",backend:e.backend}}});let i=await Ye(n,t.state,t.questions,{timeoutMs:Number(e.timeout)||2e4,features:{via:"cli"}});if(!i)return _o(`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 _o(e){console.log(JSON.stringify({ok:!1,error:e},null,2)),process.exitCode=1}async function sg(){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")}bt();import{Command as ag}from"commander";import{execFile as cg,spawn as ka}from"child_process";import{promisify as lg}from"util";import{existsSync as dg,readFileSync as gg,writeFileSync as mg,unlinkSync as pg,statSync as ug}from"fs";import{join as va}from"path";import{tmpdir as fg}from"os";import te from"chalk";var ig={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."}]},rg={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."}]},xs=[ig,rg];var En=lg(cg),xa=new ag().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(`
|
|
307
|
+
lessons
|
|
308
|
+
`));for(let l of xs)console.log(` ${te.cyan(l.id.padEnd(22))} ${l.title}`),console.log(` ${" ".repeat(22)} ${te.dim(l.appHint)}
|
|
309
|
+
`);return}let t=xs.find(l=>l.id===e);t||(console.log(te.red(` no lesson "${e}" \u2014 run \`agentx teach\` to list them`)),process.exit(1)),dg(xe)||(console.log(te.red(" helper not built \u2014 run apps/mac-helper/build.sh")),process.exit(1)),console.log(te.bold(`
|
|
310
|
+
${t.title}`)),console.log(te.dim(` ${t.appHint}
|
|
311
|
+
`));let n=null,s=null;o.record&&(s=va(o.recordDir||process.cwd(),`teach-${t.id}-${new Date().toISOString().slice(11,19).replace(/:/g,"")}.mov`),console.log(te.dim(` recording \u2192 ${s}`)),n=ka("/usr/sbin/screencapture",["-v","-x","-C",s],{stdio:["pipe","ignore","ignore"]}),await io(2e3));let i=o.hud===!1?null:ka(xe,["hud"],{stdio:["pipe","ignore","ignore"]}),r=(l,d,g,u)=>{try{i?.stdin?.write(JSON.stringify({title:l,body:d,state:g,avoid:u})+`
|
|
312
|
+
`)}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():yg(d.say,o.voice),u=d.find?await hg(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 En(xe,["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 Ss(["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 io(d.afterClickWaitMs??1500)}if(d.type){r(`Step ${l+1} of ${t.steps.length}`,d.type,"typing");let{error:p}=await Ss(["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 io(2e3))}if(d.key){r(`Step ${l+1} of ${t.steps.length}`,`\u21B5 ${d.key}`,"typing");let{error:p}=await Ss(["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 io(2e3))}if(!u&&!d.type&&!d.key?await io((d.holdSeconds??1.2)*1e3):d.holdSeconds&&await io(d.holdSeconds*1e3),d.verify){r(`Step ${l+1} of ${t.steps.length}`,"Checking that worked\u2026","waiting");let p;try{p=await xn(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(`
|
|
313
|
+
stopping: could not confirm \u2014 ${d.verify}`)),console.log(te.dim(` ${p.reason}`)),console.log(te.dim(` screenshot: ${p.sighting.shot.path}`)),await io(2500);try{i?.stdin?.end()}catch{}c=!0;break}}}}if(!c){r("Done",t.title,"done"),await io(1200);try{i?.stdin?.end()}catch{}}if(n&&s){n.kill("SIGINT"),await io(2500);try{let{size:l}=ug(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.
|
|
314
|
+
`)),process.exitCode=3;return}console.log(te.green(`
|
|
315
|
+
done.
|
|
316
|
+
`))});async function Ss(e){try{let{stdout:o}=await En(xe,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 hg(e,o=[]){try{let t=await $n({max:45});if(t.candidates.length<2)return null;let n=await Ye(Tt,yn({request:e,app:t.app,window:t.window,candidates:t.candidates,priorAttempts:o}),wn(t.candidates),{features:{app:t.app,via:"teach",ocr:t.usedOCR}});if(!n)return null;let s=bn(n.answers,t.candidates);return s.present<.5?null:Nt(t,s.id)}catch{return null}}async function yg(e,o){let t=wg();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=va(fg(),`agentx-teach-${Date.now()}.mp3`);mg(i,Buffer.from(await s.arrayBuffer())),await En("/usr/bin/afplay",[i]);try{pg(i)}catch{}return}}catch{}await En("/usr/bin/say",[e]).catch(()=>{})}function wg(){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=gg(e,"utf8").trim();if(o)return o}catch{}return null}var io=e=>new Promise(o=>setTimeout(o,e));import{Command as bg}from"commander";import L from"chalk";var Do=new bg().name("attach").description("wear an agentx agent identity in this Claude Code session"),Es=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${Et()}`;function As(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Os(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 Is(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${L.cyan("agentx daemon start")}`:o}function Sa(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function $g(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):L.gray("(not bound)"),n=e.pending?L.yellow(`${e.pending} pending`):L.gray("empty"),s=o?L.cyan(" \u2190 this session"):"";console.log(` ${L.bold(t)} ${Sa(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}Do.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Yn.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",Es).action(async(e,o)=>{let t=As(o.session);t||(console.error(L.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${L.cyan("--session <id>")} (list them with ${L.cyan("agentx attach list")}).`),process.exit(1)),xi(o.mode)||(console.error(L.red(`Invalid mode "${o.mode}". Expected one of: ${Yn.join(", ")}`)),process.exit(1)),gn()||(console.error(L.yellow("Attach hooks are not installed yet.")),console.error(`Run ${L.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Os(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${L.green("\u2713")} This session is now wearing ${L.bold(e)} (${Sa(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(L.yellow(` ${s} message(s) already queued for it.`)),console.log(L.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(L.red(`Bind failed: ${Is(n)}`)),process.exit(1)}});Do.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",Es).action(async e=>{let o=As(e.session);o||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Os(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${L.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(L.red(`Detach failed: ${Is(t)}`)),process.exit(1)}});Do.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",Es).option("--json","raw JSON output").action(async e=>{let o=As();try{let n=(await Os(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:gn(),sessions:n},null,2));return}console.log(),console.log(gn()?`${L.green("\u2713")} Attach hooks installed ${L.gray(St())}`:`${L.yellow("!")} Attach hooks not installed \u2014 run ${L.cyan("agentx attach install")}`),console.log();let s=n.filter(r=>r.agentIds.length>0);if(s.length===0)console.log(L.gray(" No session is wearing an identity right now."));else for(let r of s)$g(r,r.sessionId===o);let i=n.length-s.length;i>0&&console.log(L.gray(`
|
|
317
|
+
${i} registered session(s) with no binding.`)),console.log()}catch(t){console.error(L.red(`Could not read attach state: ${Is(t)}`)),process.exit(1)}});Do.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||Et()),t=Ir(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${L.green("\u2713")} Installed attach hooks in ${L.gray(t.path)}`:`${L.green("\u2713")} Attach hooks already up to date in ${L.gray(t.path)}`),console.log(L.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(L.gray(" PreToolUse guard installed at user scope.")),console.log(L.gray(` (An attached session runs under your permissions, not the agent's workspace
|
|
318
|
+
settings \u2014 without this an attached production identity would be less
|
|
319
|
+
guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Do.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=Cr({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});Oe();import{Command as kg}from"commander";import pe from"chalk";var An=new kg().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Aa(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=W(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 Oa(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Ea(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 vg(e){return e==="busy"?pe.magenta:e==="warm-hot"?pe.green:e==="warm-cold"?pe.cyan:e==="idle"?pe.yellow:e==="dead"?pe.red:pe.dim}An.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}=Aa(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Oa(t)})}catch(r){console.log(pe.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(pe.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(pe.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(pe.dim(" (no processes)"));return}for(let r of i){let a=vg(r.state)(r.state.padEnd(9)),c=Ea(r.spawnedAt),l=r.lastTurnAt?Ea(r.lastTurnAt)+" ago":"\u2014",d=r.lastInputTokens?pe.dim(`last_in=${r.lastInputTokens} tok`):"",g=r.claudeSessionId?pe.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):pe.dim("sess=\u2014"),u=r.pendingTaskId?pe.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${pe.bold(r.key.agentId)}${pe.dim(":"+r.key.channel+":"+r.key.chatId)} ${pe.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${g} ${d} ${u}`),r.deadReason&&console.log(` ${pe.red("dead:")} ${r.deadReason}`)}});An.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}=Aa(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Oa(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(pe.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(pe.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(pe.red(` ${a}`)),process.exit(1)}console.log(pe.green(` killed ${e}:${o}:${t}`))});import{Command as xg}from"commander";import je from"chalk";import{existsSync as Cs,rmSync as Sg}from"fs";import{resolve as js}from"path";var nt=new xg().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 Oi(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=js(e.cwd,".agentx","rag");if(!Cs(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=>Cs(js(o,s,"index.json")));if(n.length===0){console.log(je.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Kn(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=Ii(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Kn(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=js(process.cwd(),".agentx","rag",e);if(!Cs(o)){console.log(je.dim(` no index for ${e} \u2014 nothing to clear`));return}Sg(o,{recursive:!0,force:!0}),console.log(je.green(` \u2713 cleared index for ${e}`))});Oe();import{Command as Eg}from"commander";import V from"chalk";import st from"prompts";var Po=new Eg().name("backlog").description("manage the local backlog used by business workSource=backlog");function Dt(e){let o=W(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new or(n)}}function Ag(e){return e?V.cyan(`${e.type}:${e.project}#${e.iid}`):V.dim("manual")}function Og(e){return{todo:V.gray("todo"),doing:V.yellow("doing"),blocked:V.red("blocked"),done:V.green("done")}[e]}Po.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}=Dt(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(` ${Og(n.status).padEnd(7)} ${Ag(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()}`))});Po.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=Dt(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=tr([o],i.source,n.config),a=await Qn(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}`))}});Po.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=Dt(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 Qn(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}`))}});Po.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}=Dt(o.config);t.remove(e)||(console.error(V.red(` item ${e} not found`)),process.exit(1)),console.log(V.green(` removed ${e}`))});Po.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=Dt(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"?Cg(o.config):jg(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 Rg(o.config,i,a):await Tg(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=Xn({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"?Ig(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Xn(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 Ig(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Cg(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 jg(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 Rg(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 Tg(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(Ia)}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(Ia):[]}function Ia(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 Dg}from"commander";import z from"chalk";import{existsSync as Pg,readFileSync as Lg}from"fs";import{resolve as Mg}from"path";import Ug from"prompts";Oe();import Ng from"cronstrue";var Rs={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},On={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 Ng.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function _g(e){if(/\b(noon|midday)\b/.test(e))return On.noon;if(/\bmidnight\b/.test(e))return On.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 Ts(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=_g(o),s=null;for(let[g,u]of Object.entries(On))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(Rs).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(Rs))if(new RegExp(`\\b${u}s?\\b`).test(g)){let p=Rs[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(On).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 Ca(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function ja(e){let o=e||Mg(process.cwd(),"agentx.json");return Pg(o)||(console.log(z.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Lg(o,"utf-8"))}function Fg(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function qg(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(z.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Ug([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(z.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var bo=new Dg().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');bo.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){bo.help();return}o.agent||(console.log(z.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(z.red(' --do "<prompt>" is required')),process.exit(1));let t=Ts(e);t||(console.log(z.red(` Couldn't parse: "${e}"`)),console.log(z.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(z.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(z.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=ja(o.config),s=di(n);n.agents?.[o.agent]||(console.log(z.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(z.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=Fg(o.onError),r=await qg(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||Ca(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 de(g=>we(g,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(z.red(` \u2717 ${l.error}`)),process.exit(1));let d=o.dryRun?"would add":"Added";console.log(z.green(` \u2713 ${d} cron ${z.cyan(a)}`)),console.log(z.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(z.dim(` Agent: ${o.agent}`)),r&&console.log(z.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(z.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.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=ja(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(z.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?z.green("\u25CF"):z.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${z.cyan(s.padEnd(32))} ${z.dim(i.schedule.padEnd(14))} ${z.dim("\u2192")} ${i.agent}`),console.log(z.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(z.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])bo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await de(s=>{if(!Oo(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);we(s,`crons.${t}.enabled`,o)});n.success||(console.log(z.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await de(t=>{if(!Oo(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Ti(t,`crons.${e}`)});o.success||(console.log(z.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(z.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(z.dim(" Daemon hot-reloaded."))});bo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ts(o);t||(console.log(z.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(z.green(` "${o}"`)),console.log(z.dim(` \u2192 ${t.cron}`)),console.log(z.dim(` \u2192 ${t.human}`))});import{Command as dm}from"commander";import it from"chalk";import Q from"chalk";import Lt from"prompts";import{readFileSync as Wg,writeFileSync as Bg,existsSync as Jg}from"fs";import{resolve as Ra}from"path";var Hg=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Gg(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Ns(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Ta(e=".env"){let o=Ra(e);if(!Jg(o))return[];let t=Wg(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(Hg);i?n.push({kind:"kv",key:i[1],value:Gg(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function zg(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Ns(o.value)}`:o.raw).join(`
|
|
320
|
+
`)+`
|
|
321
|
+
`}function Pt(e,o,t=".env"){let n=Ra(t),s=Ta(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Ns(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Ns(o)}`})),Bg(n,zg(s))}function _s(e,o=".env"){return Ta(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Na="https://t.me/BotFather";async function Yg(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 Kg(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 _a(e={}){console.log(),console.log(Q.bold(" Connect Telegram")),console.log(),console.log(Q.dim(` 1. Open ${Na}`)),console.log(Q.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Q.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Lt({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,[Na],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Lt({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(Q.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Yg(t.trim());n||(console.log(Q.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Q.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(Q.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(Q.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await Lt({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(Q.red(" Aborted")),process.exit(1));let g=c.channels?.telegram?.accounts||{},u=e.account||d;g[u]&&g[u].agentBinding!==d&&(u=(await Lt({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(Q.red(" Aborted")),process.exit(1));let p=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Pt(p,t.trim()),process.env[p]=t.trim();let f=await de(b=>{we(b,"channels.telegram.enabled",!0),we(b,`channels.telegram.accounts.${u}`,{token:`\${${p}}`,agentBinding:d});let x=Oo(b,`agents.${d}.mentions`)||[],A=`@${n.username}`;x.includes(A)||(x.push(A),we(b,`agents.${d}.mentions`,x))},{configPath:e.configPath});if(f.success||(console.log(Q.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(Q.green(` \u2713 Bot @${n.username} bound to agent "${d}"`)),console.log(Q.dim(` Token stored in .env as ${p}`)),console.log(Q.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(Q.dim(" Daemon hot-reloaded.")):console.log(Q.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Lt({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(Q.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Q.dim(" Waiting up to 90s..."));let y=await Kg(t.trim(),9e4);if(!y){console.log(Q.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Q.dim(" agentx config set notifications.destination.channel telegram")),console.log(Q.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Q.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await de(b=>{we(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(Q.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(Q.green(" \u2713 Default --notify target set")),console.log(Q.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Q.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(Q.dim(" Daemon hot-reloaded."))}import ue from"chalk";import Ds from"prompts";import{existsSync as Ls,mkdirSync as Vg,readdirSync as Xg,readFileSync as Da}from"fs";import{resolve as Ps}from"path";var Qg=".agentx/whatsapp-sessions";function Zg(){let e=Ps(process.cwd(),".agentx/daemon.pid");if(!Ls(e))return!1;try{let o=parseInt(Da(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function em(e){if(!Ls(e))return!1;try{return Xg(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function om(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ue.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ue.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;Vg(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(ue.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(ue.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(ue.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(ue.red(" \u2717 Authorization failed \u2014 rescan required")),d(!1))})})}async function Pa(e={}){if(console.log(),console.log(ue.bold(" Connect WhatsApp")),console.log(),Zg()){console.log(ue.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ue.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ds({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ue.red(" Aborted")),process.exit(1))}let o=e.configPath||Ps(process.cwd(),"agentx.json");Ls(o)||(console.log(ue.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Da(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Qg,s=Ps(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ue.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Ds({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(d=>({title:d,value:d})),initial:0})).agent),r||(console.log(ue.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(em(s)&&a){let{keep:l}=await Ds({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(ue.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await om(s,d=>console.log(d))||(console.log(ue.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{we(l,"channels.whatsapp.enabled",!0),we(l,"channels.whatsapp.sessionDir",n),we(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ue.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ue.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ue.dim(` Session: ${n}`)),console.log(ue.dim(" Start the daemon to begin receiving:")),console.log(ue.dim(" agentx daemon start")),console.log(ue.dim(" Add routes later with:")),console.log(ue.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as tm}from"crypto";import be from"chalk";import La from"prompts";var In="agentx-mesh:",Cn="//join/";function nm(e){return Buffer.from(e,"utf-8").toString("base64url")}function sm(e){return Buffer.from(e,"base64url").toString("utf-8")}function im(e){return`${In}${Cn}${nm(JSON.stringify(e))}`}function rm(e){if(!e.startsWith(`${In}${Cn}`))throw new Error(`Not a mesh invite link \u2014 expected ${In}${Cn}\u2026`);let o=e.slice(In.length+Cn.length),t=JSON.parse(sm(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 am(){return tm(32).toString("hex")}function cm(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function lm(e){return e?.node?.name||e?.node?.id||"node"}async function Ma(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(be.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=_s("MESH_TOKEN");r||(r=am(),Pt("MESH_TOKEN",r),console.log(be.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||cm(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:g}=await La({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(be.red(" Aborted")),process.exit(1)),a=g}let l=await de(g=>{we(g,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(be.red(` \u2717 ${l.error}`)),process.exit(1));let d=im({url:a,token:r,name:lm(i),version:1});console.log(),console.log(be.bold(" Mesh invite")),console.log(),console.log(` ${be.cyan(d)}`),console.log(),console.log(be.dim(" Run on the other node:")),console.log(be.dim(` agentx connect mesh join "${d}"`)),console.log(),console.log(be.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Ua(e,o={}){let t;try{t=rm(e)}catch(i){console.log(be.red(` \u2717 ${i.message}`)),process.exit(1)}let n=_s("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await La({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(be.red(" Aborted (keeping existing .env)")),process.exit(1))}Pt("MESH_TOKEN",t.token);let s=await de(i=>{we(i,"mesh.enabled",!0);let r=Oo(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),we(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(be.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(be.green(" \u2713 Joined mesh")),console.log(be.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(be.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(be.dim(" Daemon hot-reloaded.")):console.log(be.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(be.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(be.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(be.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var rt=new dm().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");rt.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 _a({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});rt.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 Pa({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Fa=rt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Fa.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 Ma({url:e.url,configPath:e.config})});Fa.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 Ua(e,{configPath:o.config})});rt.action(()=>{console.log(),console.log(it.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${it.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${it.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${it.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${it.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(it.dim(" GitLab connect is the next slice.")),console.log()});Oe();import{Command as gm}from"commander";import ce from"chalk";var Mt=new gm().name("usage").description("token usage analysis and reporting");Mt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=W(),[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(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ce.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: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.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(` ${ce.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ce.dim(d)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});Mt.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(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});Mt.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-GSZ5AYAM.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(ce.bold(` Never used in the last ${e.days} days (${d.length}/${c.length})`)),console.log();for(let g of d)console.log(` ${ce.dim("\xB7")} ${g}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.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(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ce.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ce.dim(`${i.days}d`);console.log(` ${ce.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as mm}from"commander";import fe from"chalk";import{resolve as pm}from"path";Oe();var $o=new mm().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");$o.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{$i(pm(process.cwd(),".env"))}catch{}let o=um(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-QR7CVTKA.js");t(o)}catch(o){console.log(fe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(fe.dim(o.stack)),process.exit(1)}});function um(e,o){try{let t=W();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(fe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(fe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
322
|
+
`)),{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}}}}$o.command("list").description("list configured boards").action(()=>{try{let e=W();if(!e.boards?.length){console.log(fe.dim(`
|
|
323
|
+
No boards configured.
|
|
324
|
+
`));return}console.log();for(let o of e.boards){console.log(` ${fe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(fe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(fe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(fe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(fe.red(` ${e.message}`)),process.exit(1)}});$o.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{Ut(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(fe.red(` ${t.message}`)),process.exit(1)}});$o.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{Ut(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(fe.red(` ${t.message}`)),process.exit(1)}});var Ms=$o.command("column").description("manage a board's columns (add / remove / edit / list)");Ms.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(_c("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(fe.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(` ${fe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${fe.dim(i)}`)}}catch(o){console.log(fe.red(` ${o.message}`)),process.exit(1)}});Ms.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{Ut(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(fe.red(` ${n.message}`)),process.exit(1)}});Ms.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Ut(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(fe.red(` ${t.message}`)),process.exit(1)}});$o.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Ut(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(fe.red(` ${o.message}`)),process.exit(1)}});function Ut(e){let{summary:o,backupPath:t}=Yo(n=>e(n));console.log(fe.green(`
|
|
325
|
+
\u2713 ${o}
|
|
326
|
+
`)),t&&console.log(fe.dim(` Backup: ${t}`)),console.log(fe.dim(` Restart the dashboard to pick up the change if not auto-reloading.
|
|
327
|
+
`))}import{Command as fm}from"commander";import m from"chalk";import{resolve as F,relative as qa,dirname as Wa}from"path";import{execSync as Lo}from"child_process";import{writeFileSync as Mo,mkdirSync as ro,readFileSync as Ft,readdirSync as hm,renameSync as jn,rmSync as ym,existsSync as qe}from"fs";function $e(e,o){return new zn(qt(e),void 0,o||"graph")}function qt(e){return e||F(process.cwd(),".agentx/wiki")}function Fs(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Z=new fm().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=$e(e.dir,o),n=t.summary(),i=t.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Fs(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=$e(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=$e(e.dir,o),n=e.agent?[e.agent]:t.listAgents(),s=parseInt(e.max),i=(()=>{try{let u=F(process.cwd(),".agentx/graph");return qe(u)?new lo({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}] ---
|
|
328
|
+
${$.content}
|
|
329
|
+
--- END ENTRY ---`).join(`
|
|
330
|
+
|
|
331
|
+
`),x="";if(e.facts!==!1){let{extractHints:$,resolveFacts:T,mergeRecords:j,renderFactsBlock:C,installPrompts:D,defaultSources:q,recordsFromEntries:P}=await import("./facts-YVEJOM7O.js");if(!a){let B=new Set;for(let ke of t.listAgents())for(let he of t.getAgentWiki(ke).listArticles(ke))he.meta.type==="person"&&B.add(he.meta.title);a=[...B]}let H=$(f.map(B=>({context:B.sourceContext,content:B.content,sender:typeof B.meta?.sender=="string"?B.meta.sender:void 0})),{known:a}),re=P(f);if(H.length>0||re.length>0){let B=q(),{records:ke,results:he}=H.length>0?await T(H,{sources:B}):{records:[],results:[]},_=j([...re,...ke]);x=C(_);let Me=[...re.length>0?[`entries:${re.length}`]:[],...he.filter(ye=>ye.records.length>0).map(ye=>`${ye.source}:${ye.records.length}`)];console.log(m.dim(` Facts: ${H.length} entities \u2192 ${_.length} resolved${Me.length?` (${Me.join(" ")})`:""}`));for(let ye of D(he,B))console.log(m.yellow(` ! ${ye.source} ${ye.kind} \u2014 would supply ${ye.provides.join(", ")}`)),console.log(m.dim(` ${ye.hint}`))}}let A=Ui(o,u,k,y.articles,b,f.length,x);console.log(m.dim(` Mode: ${Fs(o)}`));let v=F(w.baseDir,"_tmp");ro(v,{recursive:!0});let E=F(v,"absorb-prompt.txt");Mo(E,A),console.log(m.dim(" Compiling with Claude..."));try{let $;try{$=Lo(`cat '${E}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Bo({...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 j,C=[],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 H=T[P],re=H==="{"?"}":"]",B=0,ke=-1;for(let _=P;_<T.length;_++)if(T[_]===H)B++;else if(T[_]===re&&(B--,B===0)){ke=_+1;break}if(ke===-1){console.log(m.red(" Unbalanced JSON"));continue}let he=T.slice(P,ke);try{let _=JSON.parse(he);Array.isArray(_)?j=_:(j=_.articles||[],C=_.gaps||[])}catch(_){console.log(m.red(` JSON parse error: ${_.message}`)),console.log(m.dim(` First 300 chars: ${he.slice(0,300)}`));continue}for(let _ of j){let Me=new Date().toISOString().slice(0,10),ye=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:ye},_.content,u);let Eo=_.type?m.magenta(`[${_.type}]`)+" ":"",R=Array.isArray(_.related)&&_.related.length?` \u2192 ${_.related.slice(0,3).join(", ")}${_.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Eo}${_.path}: ${_.title}${m.dim(R)}`);let me=(_.tags||[]).slice(0,4).join(", ");me&&console.log(m.dim(` tags: ${me}`)),ye?.length&&(console.log(m.dim(` graphPath: ${ye.join(" \u203A ")}`)),g++),d++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let _ of C)console.log(m.yellow(` ? ${_}`));try{let{QuestionStore:_}=await import("./questions-4B4KSPXG.js"),Me=new _(qt(e.dir)).add(C.map(ye=>({kind:"article",agentId:u,path:"",subject:String(ye).slice(0,120),question:`No article yet for: ${String(ye).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=wm(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-RQU5KNZM.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!qe(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 Fi({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 wm(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-SQDHE4HV.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=$e(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(`
|
|
332
|
+
`)||"_(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:**
|
|
333
|
+
|
|
334
|
+
${v.answer}
|
|
335
|
+
|
|
336
|
+
**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(`
|
|
337
|
+
`);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?Ft(e.answers,"utf-8").split(/\r?\n/).filter(R=>R.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=$e(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(R){console.log(m.red(` can't open wiki for agent "${e.agent}": ${R.message}`));return}let c=s?null:o.createInterface({input:process.stdin,output:process.stdout}),l=async R=>{if(s){let me=s[i++]??"";return process.stdout.write(R+m.dim(`[scripted] ${me.slice(0,80)}${me.length>80?"\u2026":""}`)+`
|
|
338
|
+
`),me.trim()}return(await c.question(R)).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 R=await l(m.cyan(" Type? "));if(R==="/abort"){c?.close();return}u.has(R)?g=R:(console.log(m.yellow(` "${R}" 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 R=0;R<f.length;R++){let me=f[R],We=await l(` ${m.dim(`[${R+1}/${f.length}]`)} ${me}
|
|
339
|
+
${m.green(">")} `);if(We==="/abort"){y=!0;break}if(We==="/done")break;We!=="/skip"&&We&&w.push({q:me,a:We})}if(!y){let R=await l(`
|
|
340
|
+
${m.dim("Anything else worth capturing?")}
|
|
341
|
+
${m.green(">")} `);R&&R!=="/abort"&&R!=="/done"&&w.push({q:"Anything else worth capturing?",a:R})}if(y||w.length===0){console.log(m.yellow(`
|
|
342
|
+
Nothing captured. Exiting.`)),c?.close();return}let b=a.listArticles(e.agent).slice(0,40).map(R=>`- ${R.meta.title} [${R.meta.type||"?"}]`).join(`
|
|
343
|
+
`),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(R=>`
|
|
344
|
+
Q: ${R.q}
|
|
345
|
+
A: ${R.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(`
|
|
346
|
+
`),A=F(a.baseDir,"_tmp");ro(A,{recursive:!0});let v=F(A,`interview-${t().slice(0,8)}.txt`);Mo(v,x),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let E="";try{let R=`cat '${v}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=Lo(R,{env:Bo({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let We=JSON.parse(me);E=String(We.result||We.content||"")}catch{E=me}}catch(R){console.log(m.red(` synthesis failed: ${R.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 j=E.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!j){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(E.slice(0,600)),c?.close();return}let C={};for(let R of j[1].split(`
|
|
347
|
+
`)){let me=R.match(/^(\w+):\s*(.+)$/);me&&(C[me[1]]=me[2].trim().replace(/^"(.*)"$/,"$1"))}let D=j[2],q=C.title||d,P=q.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),re=`${{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: ${re}`)),console.log(),console.log(E),console.log();let B=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),B==="scrap"||B==="/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 ke=D,he={title:q,type:C.type||g,related:C.related?C.related.replace(/^\[|\]$/g,"").split(",").map(R=>R.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:C.tags?C.tags.replace(/^\[|\]$/g,"").split(",").map(R=>R.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:C.access||"public",created:C.created||new Date().toISOString().slice(0,10),lastUpdated:C.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(B==="edit"){let R=process.env.EDITOR||"vi",me=F(A,`draft-${t().slice(0,8)}.md`);Mo(me,E);try{Lo(`${R} '${me}'`,{stdio:"inherit"});let Jn=Ft(me,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Jn){let co={};for(let yt of Jn[1].split(`
|
|
348
|
+
`)){let Hn=yt.match(/^(\w+):\s*(.+)$/);Hn&&(co[Hn[1]]=Hn[2].trim().replace(/^"(.*)"$/,"$1"))}ke=Jn[2],he={...he,title:co.title||he.title,type:co.type||he.type,access:co.access||he.access,related:co.related?co.related.replace(/^\[|\]$/g,"").split(",").map(yt=>yt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.related,tags:co.tags?co.tags.replace(/^\[|\]$/g,"").split(",").map(yt=>yt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.tags}}}catch(We){console.log(m.red(` editor failed: ${We.message}`));return}}if(!a.writeArticle(re,he,ke,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${re} saved.`));let Me=a.extractWikilinks(ke),ye=new Map;for(let R of a.listArticles(e.agent))ye.set(R.meta.title.toLowerCase(),!0);let Eo=Me.filter(R=>!ye.has(R.toLowerCase()));if(Eo.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let R of Eo.slice(0,8))console.log(m.dim(` - ${R}`));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-SQDHE4HV.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=$e(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=Ft(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 H=r[p];if(!H)break;f=H.q,w=H.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(H){console.log(m.red(`failed: ${H.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 H=y.citations.map(re=>`${re.title} [${re.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
349
|
+
`)),console.log(m.dim(" citations: "+H))}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 $=$m(E.content,x,A,E.meta.title,E.meta.type),T=F(i.baseDir,"_tmp");ro(T,{recursive:!0});let j=F(T,`quiz-patch-${t().slice(0,8)}.txt`);Mo(j,$);let C="";try{let H=`cat '${j}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,re=Lo(H,{env:Bo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let ke=JSON.parse(re);C=String(ke.result||ke.content||"")}catch{C=re}let B=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);B&&(C=B[1].trim()),C=C.trim()}catch(H){console.log(m.red(` patch failed: ${H.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=E.content.split(`
|
|
350
|
+
`).length,q=C.split(`
|
|
351
|
+
`).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)},C,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}\``:""),"")}Mo(e.out,p.join(`
|
|
352
|
+
`)),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=$e(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=Ha(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{Lo(`${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=$e(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=Ha(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=bm(l.content,l.meta.title,l.meta.type,t),g=F(a.baseDir,"_tmp");ro(g,{recursive:!0});let u=F(g,`patch-${i().slice(0,8)}.txt`);Mo(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=Lo(v,{env:Bo({...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(`
|
|
353
|
+
`).length,w=p.split(`
|
|
354
|
+
`).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 Ha(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 bm(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(`
|
|
355
|
+
`)}function $m(e,o,t,n,s){let i={"/correct":`The operator says the article contains an error:
|
|
356
|
+
|
|
357
|
+
${t}
|
|
358
|
+
|
|
359
|
+
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:
|
|
360
|
+
|
|
361
|
+
${t}
|
|
362
|
+
|
|
363
|
+
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:
|
|
364
|
+
|
|
365
|
+
${t}
|
|
366
|
+
|
|
367
|
+
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(`
|
|
368
|
+
`)}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=$e(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(!qe(u))continue;let p=F(u,i),f=r.map(b=>({mode:b,dir:F(u,b)})).filter(b=>qe(b.dir));if(f.length===0)continue;let w=new Map;Us(p,b=>{let x=qa(p,b);if(x.startsWith("_")||x.startsWith("raw/")||x.includes("_tmp/"))return;let A=Ba(Ft(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)Us(b.dir,x=>{let A=qa(b.dir,x);if(A.startsWith("_")||A.startsWith("raw/")||A.includes("_tmp/"))return;let v=Ba(Ft(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 j=F(p,b.relPath);qe(j)?(console.log(m.yellow(` ! target path already exists, archiving instead: ${b.relPath}`)),Ja(u,b),d++):(ro(Wa(j),{recursive:!0}),jn(b.absPath,j),w.set(x,{relPath:b.relPath,type:b.type,lastUpdated:b.lastUpdated}),c++)}else if(v==="upgrade"){let j=F(p,A.relPath);if(qe(j)){let C=F(u,"_versions",A.relPath.replace(/\.md$/,""));ro(C,{recursive:!0});let D=new Date().toISOString().replace(/[:.]/g,"-");jn(j,F(C,`${D}.md`))}ro(Wa(j),{recursive:!0}),jn(b.absPath,j),w.set(x,{relPath:A.relPath,type:b.type,lastUpdated:b.lastUpdated}),l++}else Ja(u,b),d++}catch(j){console.log(m.red(` ! ${v} failed: ${j.message?.slice(0,120)}`))}}if(n){for(let b of f)try{ym(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 Us(e,o){if(qe(e))for(let t of hm(e,{withFileTypes:!0})){let n=F(e,t.name);t.isDirectory()?Us(n,o):t.isFile()&&t.name.endsWith(".md")&&o(n)}}function Ba(e){let o=e.match(/^---\n([\s\S]*?)\n---/);if(!o)return null;let t={};for(let n of o[1].split(`
|
|
369
|
+
`)){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 Ja(e,o){let t=F(e,"_versions",`legacy-${o.mode}`,o.relPath.replace(/\.md$/,""));ro(t,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");jn(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=$e(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");ro(y,{recursive:!0});for(let k=0;k<f;k+=n){let b=u.slice(k,Math.min(k+n,f)),x=vm(b),A=F(y,"migrate-prompt.txt");Mo(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"`,$=Lo(E,{env:Bo({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),T=JSON.parse($),C=String(T.result||T.content||"").match(/\[[\s\S]*\]/);if(!C)throw new Error("no JSON array in classifier response");v=JSON.parse(C[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=km($?.type);if(!$||!T){console.log(m.yellow(` ? ${E.path}: unclassified${$?` (got "${$.type}")`:""}`));continue}let j=d.extractWikilinks(E.content),C={...E.meta,type:T.type,related:j.length?j:void 0,lastUpdated:new Date().toISOString().slice(0,10)},D=j.length?m.dim(` \u2192 ${j.slice(0,3).join(", ")}${j.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,C,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 km(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 vm(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}"
|
|
370
|
+
title: "${t.meta.title}"
|
|
371
|
+
tags: [${i}]
|
|
372
|
+
body: ${s}${t.content.length>400?"\u2026":""}`}).join(`
|
|
373
|
+
|
|
374
|
+
`);return`Classify each of these ${e.length} wiki articles into EXACTLY ONE type from this closed set (no synonyms, no plurals, no new values):
|
|
375
|
+
|
|
376
|
+
person | project | place | concept | event | decision | pattern
|
|
377
|
+
|
|
378
|
+
What each type means:
|
|
379
|
+
- person: an individual human (team member, stakeholder, contact)
|
|
380
|
+
- project: a named initiative, repo, product, service, bot, agent, team, or org
|
|
381
|
+
- place: a physical or logical location (office, server, environment, infrastructure)
|
|
382
|
+
- concept: a recurring idea, philosophy, methodology, or thinking pattern
|
|
383
|
+
- event: a specific dated thing that happened (incident, deploy, launch, GitLab issue, MR)
|
|
384
|
+
- decision: a specific choice made and why (architecture decision, policy, ADR)
|
|
385
|
+
- pattern: a reusable workflow, template, recipe, procedure, runbook, or SOP
|
|
386
|
+
|
|
387
|
+
Explicit mappings (you WILL be tempted to volunteer these \u2014 don't; use the right-hand value):
|
|
388
|
+
- "agent" / "bot" / "service" / "repo" / "team" \u2192 project
|
|
389
|
+
- "issue" / "MR" / "ticket" / "incident" / "deploy" \u2192 event
|
|
390
|
+
- "process" / "procedure" / "runbook" / "workflow" \u2192 pattern
|
|
391
|
+
- "infrastructure" / "server" / "environment" \u2192 place
|
|
392
|
+
- "ADR" / "decision record" \u2192 decision
|
|
393
|
+
|
|
394
|
+
Rules:
|
|
395
|
+
- Return EXACTLY one type per article, by path, from the 7 allowed values above.
|
|
396
|
+
- Do not invent new types. Do not return plurals. Do not return synonyms.
|
|
397
|
+
- 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.
|
|
398
|
+
- If you genuinely cannot decide, pick "concept" as the fallback.
|
|
399
|
+
- Output ONLY valid JSON, no markdown fencing, no prose.
|
|
400
|
+
|
|
401
|
+
Articles:
|
|
402
|
+
|
|
403
|
+
${o}
|
|
404
|
+
|
|
405
|
+
Output (JSON array, one entry per input article, same order):
|
|
406
|
+
[
|
|
407
|
+
{"path": "path/to/article.md", "type": "project"},
|
|
408
|
+
...
|
|
409
|
+
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(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-HMW3EBZL.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(),gr(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-7WM7II2B.js"),c=$e(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(`
|
|
410
|
+
${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(`
|
|
411
|
+
${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-SQDHE4HV.js"),n=$e(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=$e(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=$e(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=F(process.cwd(),".agentx/graph");if(!qe(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new lo({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??""),j=s.fingerprint({text:$.content,channel:$.source,sender:T}),C=r.get(j);if(!C?.length)continue;let D=C.join("/"),q=A.get(D);q?q.n++:A.set(D,{path:C,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=$e(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-HMW3EBZL.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 zn(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:Fs(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");qe(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=qe(s)?d(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${xm(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-7WM7II2B.js"),{QuestionStore:c}=await import("./questions-4B4KSPXG.js"),l=$e(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 j=$.readArticle(T.path);if(!j||e.type&&j.meta.type!==e.type)continue;p++;let C=await a(r,n({title:j.meta.title,type:j.meta.type,body:j.content}),o(j.meta.type),{links:[{kind:"article",id:T.path}],features:{agent:E,type:j.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=t(j.meta.type,C.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:j.meta.title,field:q.field,tier:q.tier,question:`${j.meta.title} (${j.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:j.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&d.length>0&&(w=new c(qt(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(j=>(E[j.tier??"furniture"]??9)<=$);if(T.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:j}=await import("./config-HMW3EBZL.js"),C=j(),D=C?.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(B=>`\u2022 ${B.question}`).join(`
|
|
412
|
+
`),P=T.length>10?`
|
|
413
|
+
\u2026and ${T.length-10} more`:"",H=`${T.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
414
|
+
${q}${P}
|
|
415
|
+
|
|
416
|
+
agentx wiki questions`,re=C?.daemon?.port??C?.port??18800;try{let B=await fetch(`http://127.0.0.1:${re}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:H})});console.log(B.ok?m.cyan(` Pushed ${T.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${B.status}) \u2014 questions are still queued.`))}catch(B){console.log(m.yellow(` Push failed (${String(B?.message??B).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-7WM7II2B.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:d,recordsFromEntries:g}=await import("./facts-YVEJOM7O.js"),{backfillArticle:u}=await import("./backfill-MTD2B62I.js"),p=$e(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(C=>[C.name.toLowerCase().trim(),C])),x=0,A=0,v=[],E=!1;e:for(let C of f){let D=p.getAgentWiki(C);for(let q of D.listArticles(C)){if(x>=w)break e;if(q.meta.type!=="person")continue;let P=D.readArticle(q.path);if(!P)continue;x++;let H=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:C,op:"backfill"}});if(!H){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let B=t(P.meta.type,H.answers).missing.filter(R=>i.includes(R));if(B.length===0)continue;let{records:ke,results:he}=await a([{name:P.meta.title,type:"person"}],{sources:y}),_=b.get(P.meta.title.toLowerCase().trim());if(!E){for(let R of l(he,y))console.log(m.yellow(` ! ${R.source} ${R.kind} \u2014 would supply ${R.provides.join(", ")}`)),console.log(m.dim(` ${R.hint}`));E=!0}let Me=c([..._?[{name:_.name,source:"entries",fields:Object.fromEntries(Object.entries(_.fields).map(([R,me])=>[R,me.value]))}]:[],...ke]);if(Me.length===0)continue;let{content:ye,edits:Eo}=u(P.content,Me[0],B);if(Eo.length!==0){for(let R of Eo)v.push({agent:C,article:P.meta.title.slice(0,32),field:R.field,action:R.replaced?"replace":"add",got:`${R.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(q.path,P.meta,ye,C)?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(C=>Math.max(C.length,...v.map(D=>String(D[C]).length))),j=C=>C.map((D,q)=>String(D).padEnd(T[q])).join(" ");console.log(),console.log(m.bold(j($)));for(let C of v)console.log(j($.map(D=>C[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(qt(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(qt(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=$e(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-7WM7II2B.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=$e(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 H=await i(o,n(P),t,{features:{source:P.source??"",absorbed:P.absorbed}});if(!H){v++;continue}let re=H.answers;A.push({entry:P,verdict:s(H.answers,x),citeWorthy:re.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"),j=g(T,{minN:50}),C=((Date.now()-E)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:$,calibration:j,failures:v,elapsed:C},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 j)||!j.insufficient)&&console.log(` ECE ${j.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(` ${C}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:H,points:re}=d(A,{minRecall:P});if(console.log(),console.log(m.bold(` threshold sweep (${re.length} policies, recall floor ${D(P)})`)),H)console.log(` best: ${H.requireTyped?`typed & type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} durability>=${H.minDurability}`),console.log(` recall ${D(H.recall)} \xB7 filtered ${D(H.filtered)} \xB7 precision ${D(H.precision)} \xB7 lost ${H.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 B=re.slice().sort((ke,he)=>he.recall-ke.recall)[0];B&&console.log(m.dim(` Best recall available: ${D(B.recall)} at ${B.requireTyped?`type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} dur>=${B.minDurability}, filtering ${D(B.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);qe(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");qe(n)&&!o.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=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 xm(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"}Fc();import{Command as Sm}from"commander";import N from"chalk";import{resolve as Rn}from"path";import{existsSync as Em}from"fs";Oe();var at=new Sm().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");at.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=W();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 lo({baseDir:Rn(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=Vt(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=Am(w,a,c),b=null;try{b=await Om(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{Im(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()});at.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=W();if(!o.graph){console.log(N.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Rn(process.cwd(),o.graph.baseDir);if(!Em(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 lo({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()});at.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=W();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 lo({baseDir:Rn(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 j=await fetch(`${t}/graph/nodes`,{headers:s});if(!j.ok)throw new Error(`nodes HTTP ${j.status}`);d=(await j.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);g=(await C.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 Am(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(`
|
|
417
|
+
`),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(`
|
|
418
|
+
`)}async function Om(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 hi((c?.content||"").toString())}finally{clearTimeout(r)}}function Im(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function qs(){let e=W();if(!e.graph?.baseDir)return console.log(N.red(" graph.baseDir is not configured")),null;let o=Rn(process.cwd(),e.graph.baseDir);return{store:new lo({baseDir:o}),baseDir:o}}var Ws=at.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Ws.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=qs();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(Vt(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]"))});Ws.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=qs();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}: ${Vt(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(N.dim(` should have been: ${t.path}`))});Ws.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=qs();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 _m}from"commander";import Y from"chalk";import{Command as za}from"commander";import se from"chalk";import{existsSync as Cm}from"fs";import{resolve as jm}from"path";import Rm from"better-sqlite3";function Tm(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(se.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Nm(e){let o=jm(process.cwd(),e);return Cm(o)||(console.log(se.red(` No db at ${o}`)),process.exit(1)),new Rm(o,{readonly:!0})}var Ya=new za().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(kt)).option("--max <n>","max clusters distilled per run",String(Zt)).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(se.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Nm(e.path),t=await qi(o,{since:Tm(e.since),agentId:e.agent,sessions:new ki(process.cwd()),minOccurrences:Number(e.minOccurrences)||kt,max:Number(e.max)||Zt,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(se.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(` ${se.cyan(n.key)} ${se.bold(`\xD7${n.count}`)} ${se.dim(n.status)}`),n.sampleMessage&&console.log(se.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(se.dim(`
|
|
419
|
+
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(se.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(se.green(` \u2713 draft written: ${n.id}`)+se.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(se.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(se.yellow(` \u26A0 ${n}`));t.dryRun?console.log(se.dim(`
|
|
420
|
+
dry run only; pass --commit --via <agentId> to write drafts`)):t.drafted.length&&console.log(se.dim(`
|
|
421
|
+
review with: agentx procedure list --drafts \xB7 then promote/reject <id>`))}),Ga={hourly:"0 * * * *",daily:"0 3 * * *"},Ka=new za().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(kt)).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?Ga.hourly:e.daily?Ga.daily:void 0);!e.off&&!o&&!e.onTask&&(console.log(se.red(" pick a cadence: --hourly, --daily, --cron <expr>, and/or --on-task (or --off)")),process.exit(1)),!e.off&&!e.via&&(console.log(se.red(" --via <agentId> is required: drafts are distilled through that agent's session")),process.exit(1));let t=Number(e.minOccurrences)||kt,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 ${Zt} --min-occurrences ${t} --via ${e.via} --commit`,"","Report a one-line summary of drafted/skipped counts."].join(`
|
|
422
|
+
`),i=await de(a=>{we(a,"procedures.extraction",n),e.off?a.crons?.["procedure-extract"]&&we(a,"crons.procedure-extract.enabled",!1):o&&we(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(se.red(` \u2717 ${i.error}`)),process.exit(1));let r=e.dryRun?"would set":"Set";e.off?console.log(se.green(` \u2713 ${r} procedure extraction: off`)):(console.log(se.green(` \u2713 ${r} procedure extraction cadence`)),o&&console.log(se.dim(` cron: ${o} (${e.timezone}) via ${e.via}`)),e.onTask&&console.log(se.dim(" on-task counting: enabled")),console.log(se.dim(` threshold: ${t} occurrences`))),console.log(se.yellow(" \u26A0 restart the daemon to activate \u2014 hot-reload does not pick up new config blocks"))});var ze=new _m().name("procedure").description("procedures (SOPs) \u2014 extract from activity, review drafts, match, schedule");ze.addCommand(Ya);ze.addCommand(Ka);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 go,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 go,t=e.steps?String(e.steps):`## Steps
|
|
423
|
+
|
|
424
|
+
1. (fill in)
|
|
425
|
+
|
|
426
|
+
## Notes
|
|
427
|
+
|
|
428
|
+
`;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 go,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 go;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 go;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 go;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 go,n=Ni(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 Lm}from"commander";import S from"chalk";import{resolve as lt,basename as Mm}from"path";import{existsSync as Bs,readFileSync as Js,writeFileSync as Tn}from"fs";import Nb from"better-sqlite3";import{readFileSync as Dm}from"fs";import{resolve as ct,dirname as Va}from"path";import{fileURLToPath as Pm}from"url";var Wt=[{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 Xa(e){let o=Va(Pm(import.meta.url)),t=process.argv[1]?Va(process.argv[1]):"",n=[ct(o,`${e}.yaml`),ct(o,"workflows/templates",`${e}.yaml`),ct(o,"..","workflows/templates",`${e}.yaml`),ct(o,"../..","workflows/templates",`${e}.yaml`),t?ct(t,"workflows/templates",`${e}.yaml`):"",t?ct(t,"..","workflows/templates",`${e}.yaml`):""].filter(Boolean);for(let s of n)try{return Dm(s,"utf-8")}catch{}throw new Error(`workflow template "${e}" not found in any of:
|
|
429
|
+
${n.join(`
|
|
430
|
+
`)}`)}var Pe=new Lm().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Pe.command("list").description("list all workflows with their trigger + state count").action(()=>{let o=new Ao().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"}.`))});Pe.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 Ao().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(Si(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))});Pe.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=lt(process.cwd(),e);Bs(i)||(console.log(S.red(` file not found: ${i}`)),process.exit(1));try{let r=Js(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Go(r,{filePath:e}):JSON.parse(r),l=Ho.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=Xt(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 Qt?r.message:`parse error: ${r?.message??r}`;console.log(S.red(` ${a}`)),process.exit(1)}return}let t=new Ao().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)});Pe.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Wt.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");Wt.some(a=>a.name===t)||(console.log(S.red(` unknown template "${o.template}"`)),console.log(S.dim(` available: ${Wt.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 Ao;!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=Xa(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=Go(s,{filePath:`${e}.yaml`}),c=Ho.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=lt(process.cwd(),".agentx/workflows",`${e}.${i}`);if(o.json){let a=Go(s,{filePath:`${e}.yaml`}),c=Ho.parse(a);Tn(r,JSON.stringify(c,null,2)+`
|
|
431
|
+
`)}else Tn(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()});Pe.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Wt)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()});Pe.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=lt(process.cwd(),e);Bs(t)||(console.log(S.red(` file not found: ${t}`)),process.exit(1));let n=Js(t,"utf-8"),s=/\.(ya?ml)$/i.test(e),i;try{i=s?Go(n,{filePath:e}):JSON.parse(n)}catch(u){let p=u instanceof Qt?u.message:`parse error: ${u?.message??u}`;console.log(S.red(` ${p}`)),process.exit(1)}let r=Ho.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=Xt(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 Ao,l=s?Mm(e).match(/\.yml$/i)?"yml":"yaml":"json",d=lt(c.baseDir,`${r.data.id}.${l}`);if(Tn(d,s?n:JSON.stringify(r.data,null,2)+`
|
|
432
|
+
`),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`))}});Pe.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 $t({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"}.`))});Pe.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=lt(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Bs(s)){let c=Js(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),d;try{d=l?Go(c,{filePath:e}):JSON.parse(c)}catch(b){let x=b instanceof Qt?b.message:`parse error: ${b?.message??b}`;console.log(S.red(` ${x}`)),process.exit(1)}let g=Ho.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=Xt(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 Ao,f=g.data.id.startsWith("_adhoc-")?g.data.id:`_adhoc-${g.data.id}-${Date.now().toString(36)}`,w=l?"yaml":"json",y=lt(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)+`
|
|
433
|
+
`;Tn(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 Um({daemonUrl:String(o.daemon).replace(/\/$/,""),runId:a})});async function Um(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())}Pe.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}Qa(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)Qa(i)});function Qa(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()}Pe.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 $t({nodeId:t}).setStatus(e,"paused")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 paused ${e}`))});Pe.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 $t({nodeId:t}).setStatus(e,"running")||(console.log(S.yellow(` no such run: ${e}`)),process.exit(1)),console.log(S.green(` \u2713 resumed ${e}`))});Pe.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 $t({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 Za}from"commander";import ee from"chalk";import Uo from"prompts";import{readFileSync as Fm,existsSync as qm}from"fs";import{resolve as Wm}from"path";var Bt=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],Hs=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),ec={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 oc(){let e=Wm(process.cwd(),"agentx.json");if(!qm(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Fm(e,"utf-8"))}function Bm(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?ee.yellow("\u26A0 no signing secret"):ee.green("\u2713 active"):ee.dim("disabled")}function Jm(e,o){let t=o?`${o.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=Hs.has(e.source)?ee.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${ee.cyan(e.id)} ${Bm(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 ao=new Za().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");ao.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let o=oc(),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(`
|
|
434
|
+
No webhooks registered. Add one with: agentx webhook add
|
|
435
|
+
`));return}console.log();for(let n of t)Jm(n)});ao.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${Bt.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=oc(),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 Uo({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 Uo({type:"select",name:"source",message:"Source",choices:Bt.map(f=>({title:`${f}${Hs.has(f)?" \u2713 wired":""}`,value:f,description:ec[f]}))})).source),!Bt.includes(a))throw new Error(`Source must be one of: ${Bt.join(", ")}`);if(!c&&g&&(i?c=((await Uo({type:"text",name:"agentId",message:`Agent on remote peer "${i}"`})).agentId||"").trim():c=(await Uo({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 Uo({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!d&&g&&(d=((await Uo({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let u=await de(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"))});ao.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,o)=>{if(!o.yes&&!(await Uo({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let t=await de(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 tc(e){return async o=>{let t=await de(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}"`))}}ao.command("enable <id>").description("enable a webhook entry").action(tc(!0));ao.command("disable <id>").description("disable a webhook entry").action(tc(!1));var Nn=new Za().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Nn.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,o,t)=>{let n=await de(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}`))});Nn.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,o)=>{let t=await de(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}"`))});Nn.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 de(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}`}`))});ao.addCommand(Nn);ao.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let o=Bt.map(t=>({source:t,wired:Hs.has(t),hint:ec[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";Oe();function dt(e){let{summary:o,backupPath:t}=Yo(n=>e(n));console.log(oe.green(`
|
|
436
|
+
\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.
|
|
437
|
+
`))}function _n(){try{return W().business||{}}catch{return{}}}var gt=new Hm().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");gt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let o=_n();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 Gs=gt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Gs.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let o=_n(),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}`):""}`)});Gs.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);dt(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}`:""})`))});Gs.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{dt(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 zs=gt.command("project").description("manage business.projects \u2014 id, pm, client");zs.command("list").description("list projects").option("--json","JSON output").action(e=>{let t=_n().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())});zs.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)=>{dt(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`})});zs.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{dt(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 Ys=gt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Ys.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let t=_n().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:""}`)}});Ys.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)),dt(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`})});Ys.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=>{dt(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 Gm}from"commander";import Re from"chalk";Oe();var zm={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Ks(e){let o=zm[e.toLowerCase()];if(!o)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return o}function Dn(){let o=W().business?.standup?.plansDir||".agentx/plans";return new nr(o)}var mt=new Gm().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");mt.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=Ks(e),n=Dn(),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(`
|
|
438
|
+
`):(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=Zn(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}`))}});mt.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let o=Dn();if(e){let n=Ks(e),s=o.read(n);if(!s){console.log(Re.dim(` No ${n} plan set.`));return}nc(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}nc(t.tier,t.date,t.content)});mt.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let t=Dn().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)}`)});mt.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let o=Ks(e),n=Dn().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 nc(e,o,t){console.log(Re.cyan(` ${e} plan \u2014 ${o}`)),console.log();for(let s of t.split(`
|
|
439
|
+
`))console.log(` ${s}`);console.log();let n=Zn(t);n.length&&console.log(Re.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Ym}from"commander";import Ue from"chalk";Oe();function Km(){try{return W().notifications||{}}catch{return{}}}function Pn(e){let{summary:o,backupPath:t}=Yo(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(Ue.green(`
|
|
440
|
+
\u2713 ${o}`)),t&&console.log(Ue.dim(` Backup: ${t}`)),console.log(Ue.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
441
|
+
`))}var pt=new Ym().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");pt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let o=Km();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 ${Ue.cyan(o.destination.channel+":"+o.destination.chatId)}${Ue.dim(n)}`)}else console.log(` destination ${Ue.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${o.longTaskThreshold??30}s ${Ue.dim("(0 disables long-task pings)")}`);let t=o.on||{};console.log(` on.taskComplete ${t.taskComplete===!1?Ue.dim("off"):"on"}`),console.log(` on.taskError ${t.taskError===!1?Ue.dim("off"):"on"}`),console.log(` on.taskQueued ${t.taskQueued?"on":Ue.dim("off")}`),console.log()});pt.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){Pn(o=>(delete o.destination,"notifications destination cleared"));return}Pn(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})`:""}`))});pt.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(Ue.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(Ue.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";Pn(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});pt.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(Ue.red(" threshold must be a non-negative integer")),process.exit(1)),Pn(t=>(t.longTaskThreshold=o,`longTaskThreshold = ${o}s`))});import{Command as Vm}from"commander";import ko from"chalk";import{readdirSync as Vs,statSync as sc,unlinkSync as Xm,rmSync as Qm,existsSync as ic}from"fs";import{resolve as rc,join as ac}from"path";var cc=[{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 Xs(e,o){if(!ic(e))return[];let t=[];for(let n of Vs(e,{withFileTypes:!0})){let s=ac(e,n.name);n.isFile()?t.push(s):n.isDirectory()&&o&&t.push(...Xs(s,!0))}return t}var Mn=new Vm().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");Mn.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let o of cc){let t=rc(process.cwd(),o.dir),n=Xs(t,!!o.recursive),s=0,i=null;for(let a of n)try{let c=sc(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${ko.cyan(o.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${Ln(s).padStart(10)} oldest=${r}`)}console.log(ko.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${Ln(e).padStart(10)} total`)),console.log(),console.log(ko.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});Mn.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let o=parseInt(e.days,10);(!Number.isFinite(o)||o<1)&&(console.log(ko.red(" --days must be a positive integer")),process.exit(1));let t=Date.now()-o*864e5,n=e.target,s=0,i=0;console.log(),console.log(ko.bold(` Pruning files older than ${o}d (${new Date(t).toISOString().slice(0,10)})${e.dryRun?ko.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of cc){if(n&&r.dir!==n)continue;let a=rc(process.cwd(),r.dir),c=Xs(a,!!r.recursive),l=0,d=0;for(let u of c)try{let p=sc(u);if(p.mtimeMs<t&&(d+=p.size,l++,!e.dryRun))try{Xm(u)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{lc(a)}catch{}let g=e.dryRun?"would remove":"removed";console.log(` ${ko.cyan(r.dir.padEnd(22))} ${g} ${String(l).padStart(5)} files (${Ln(d)})`),s+=l,i+=d}console.log(),console.log(ko.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${Ln(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function lc(e){if(ic(e))for(let o of Vs(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let t=ac(e,o.name);lc(t);try{Vs(t).length===0&&Qm(t,{recursive:!1})}catch{}}}function Ln(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 Zm}from"commander";import M from"chalk";var vo=new Zm().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");vo.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let t=new zo().list();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(),console.log(M.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?M.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(` ${M.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${M.dim(i)}`)}console.log()});vo.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,o)=>{let n=new zo().get(e);if(n||(console.log(M.red(` no action "${e}"`)),process.exit(1)),o.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(M.bold(` ${n.title}`)),n.description&&console.log(M.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(M.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?M.red("*"):" ",r=s.defaultValue!==void 0?M.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?M.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${M.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});vo.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,o)=>{let t=ep(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(M.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(M.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(M.red(" --headers must be valid JSON")),process.exit(1)}o.body&&(n.body=o.body)}else console.log(M.red(" --kind must be shell|http")),process.exit(1);let s=Ei.safeParse(n);if(!s.success){console.log(M.red(" validation failed:"));for(let a of s.error.issues)console.log(M.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new zo().save(s.data);console.log(M.green(`
|
|
442
|
+
\u2713 action "${r.id}" saved (${r.kind}).`)),console.log(M.dim(` Test: agentx actions run ${r.id}
|
|
443
|
+
`))});vo.command("remove <id>").alias("rm").description("delete an action").action(e=>{new zo().delete(e)||(console.log(M.red(` no action "${e}"`)),process.exit(1)),console.log(M.green(` \u2713 action "${e}" removed`))});vo.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new zo().get(e);n||(console.log(M.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(M.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Ai(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?M.green("\u2713 ok"):M.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(M.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(M.dim(" --- errors ---")),console.log(M.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(M.red(` ${i.message}`)),process.exit(1)}});vo.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(M.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(M.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(M.bold(" Built-in typed actions")),console.log(M.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?M.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${M.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(M.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(M.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(M.bold(` ${r.name}`)),r.description&&console.log(M.dim(` ${r.description}`)),console.log(),console.log(M.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(M.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(M.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(M.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(M.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(M.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function ep(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}Oe();import{Command as op}from"commander";import X from"chalk";var dc=new op().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=W(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(X.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(X.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(X.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(`
|
|
444
|
+
|
|
445
|
+
`))>=0;){let p=l.slice(0,u);l=l.slice(u+2),tp(p)}}}catch(r){console.error(X.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function tp(e){let o="message",t="";for(let i of e.split(`
|
|
446
|
+
`))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?X.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=X.cyan(n.phase?.padEnd(9)??"run"),r=X.bold(n.workflowId??""),a=X.dim((n.runId??"").slice(0,8)),c=n.nodeId?X.yellow(n.nodeId):"",l=n.note?X.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=X.magenta(`task.${n.phase}`.padEnd(14)),r=X.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?X.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${X.cyan(a)} ${c}`);break}case"signal":{let i=X.green("signal".padEnd(9)),r=X.bold(n.name),a=X.dim(`(${n.scope})`),c=n.workflowId?X.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=X.blue("mesh".padEnd(9)),r=X.bold(n.peer),a=n.healthy?X.green("\u2713 healthy"):X.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${X.dim(n.delta??"")}`);break}case"channel":{let i=X.yellow("channel".padEnd(9)),r=n.direction==="in"?X.cyan("\u2190"):X.magenta("\u2192"),a=X.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?X.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(X.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 sp}from"commander";import Un from"chalk";import{spawn as ip}from"node:child_process";import{execFileSync as np}from"node:child_process";function gc(e=()=>np("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var mc=new sp().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error(Un.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-ZLSXGPTV.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:gc();if(n?.ok){let{fetchAgents:l}=await import("./client-ZLSXGPTV.js"),d=await l(t);if(!d.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let g=e.agent||d[0].id;if(!d.some(y=>y.id===g))throw new Error(`Unknown AgentX agent: ${g}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let p=Object.fromEntries(d.map(y=>[y.id,{name:`AgentX ${y.name||y.id}`}])),f={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${g}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:p}}})};console.error(Un.dim(`Opening ${n.version} with AgentX model ${g}.`));let w=ip("opencode",["--standalone"],{stdio:"inherit",env:f});await new Promise((y,k)=>{w.once("error",k),w.once("exit",b=>b===0?y():k(new Error(`OpenCode exited with code ${b??"unknown"}`)))});return}n&&!n.ok&&(console.error(Un.yellow(n.reason)),console.error(Un.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-CKPH3HHF.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as rp}from"commander";import K from"chalk";import{randomUUID as fc}from"crypto";import{createInterface as ap}from"node:readline/promises";import cp from"ora";import Fn from"chalk";function pc(e){console.error(),console.error(Fn.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(Fn.dim(` ${e.why}`)),console.error(),console.error(` Use ${Fn.cyan(e.instead)} instead.`),e.note&&console.error(Fn.dim(` ${e.note}`)),console.error()}var uc={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 hc=new rp().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)=>{pc({what:"agentx chat",...uc});let t=mr({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${fc().slice(0,12)}`,r=[];try{r=await on(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-MX7IG4K2.js"),u=(await import("react")).default;await d(u.createElement(g,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}dp(t.baseUrl,n,i,s);let a=ap({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(K.dim(`
|
|
447
|
+
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:${fc().slice(0,12)}`,console.log(K.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(d==="/agents"){try{let f=await on(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 on(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=cp({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),p=lp(n);try{let f=await pr(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 lp(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${K.green(`@${e}`)}
|
|
448
|
+
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
449
|
+
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
450
|
+
`&&(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(`
|
|
451
|
+
`),t=!0);let c=r.arg?K.dim(`(${r.arg})`):"";process.stdout.write(` ${K.green("\u25CF")} ${K.bold(r.name)}${c}
|
|
452
|
+
`)}else r.status==="result"&&r.error&&(t||(process.stdout.write(`
|
|
453
|
+
`),t=!0),process.stdout.write(` ${K.red("\u25CF")} ${K.dim(`${r.name??"tool"} failed`)}
|
|
454
|
+
`))},finish(r,a){if(!o){process.stdout.write(`${K.green(`@${e}`)} ${K.dim("\xB7 (empty reply)")}
|
|
455
|
+
|
|
456
|
+
`);return}t||process.stdout.write(`
|
|
457
|
+
`);let c=a?.outputTokens!=null?`, ${a.outputTokens} tok`:"";process.stdout.write(K.dim(` \xB7 ${r}s${c}
|
|
458
|
+
|
|
459
|
+
`))},finishError(r){o&&!t&&process.stdout.write(`
|
|
460
|
+
`),process.stdout.write(K.red(` \u2717 ${r}
|
|
461
|
+
|
|
462
|
+
`))}}}function dp(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 gp}from"commander";import Te from"chalk";import{readFileSync as mp}from"fs";var qn=["user","feedback","project","reference"],Fo=new gp().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");Fo.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(!qn.includes(e.type)){console.error(Te.red(` --type must be one of: ${qn.join(", ")}`)),process.exitCode=1;return}let o=e.body??"";if(e.file)if(e.file==="-")o=await pp();else try{o=mp(e.file,"utf-8")}catch(s){console.error(Te.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!o.trim()){console.error(Te.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new Jo().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:o});console.log(Te.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});Fo.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 Jo().list(e.agent);if(e.type){if(!qn.includes(e.type)){console.error(Te.red(` --type must be one of: ${qn.join(", ")}`)),process.exitCode=1;return}t=t.filter(s=>s.type===e.type)}if(!t.length){console.log(Te.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(Te.bold(` ${s.type}`)),n=s.type),console.log(` ${Te.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(Te.dim(` ${t.length} memor${t.length===1?"y":"ies"} for ${e.agent}`))});Fo.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 Jo().get(o.agent,e);if(!n){console.error(Te.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Te.bold(`${n.type}/${n.name}`)+Te.dim(` (${n.description})`)),console.log(Te.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});Fo.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,o)=>{if(!new Jo().remove(o.agent,e)){console.error(Te.red(` no memory "${e}" for agent "${o.agent}"`)),process.exitCode=1;return}console.log(Te.green(` \u2713 memory "${e}" removed`))});Fo.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 Jo().indexMarkdown(e.agent);if(!t){console.log(Te.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(t)});async function pp(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}Dc();import Qs from"chalk";import{Command as up}from"commander";import{resolve as fp}from"path";var yc=new up().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(fp(e.cwd)),e.stdio!==!1?await _i():(oo.error("Only stdio transport is currently supported."),oo.info(`Usage: ${Qs.green("agentx serve --stdio")} or configure in your MCP client.`),oo.break(),oo.info("Add to Claude Code:"),oo.info(Qs.dim(" claude mcp add agentx -- npx agentx serve --stdio")),oo.break(),oo.info("Add to Cursor/MCP config:"),oo.info(Qs.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(o){sr(o)}});import{Command as hp}from"commander";import le from"chalk";import{spawn as Zs}from"child_process";import{mkdirSync as yp,writeFileSync as ei,rmSync as bc,openSync as $c,existsSync as kc}from"fs";import{resolve as wp,join as Fe}from"path";import{randomBytes as bp}from"crypto";var wc={id:"demo-report",version:2,title:"Draft the demo shop report",description:"Scripted documentation example. Review and enable before running.",status:"draft",state:"disabled",nodes:[{id:"start",type:"trigger.manual",config:{},position:{x:80,y:180}},{id:"report",type:"agent",config:{agentId:"cx",prompt:"Prepare the demo shop report."},position:{x:380,y:180}},{id:"done",type:"end",config:{status:"completed"},position:{x:680,y:180}}],edges:[{from:"start",to:"report"},{from:"report",to:"done"}]};var vc="[demo] Customer reports checkout is broken and CI is red on demo/shop. Handle it.",$p="CI is red on demo/shop \u2014 checkout.test.ts failing on Node 22. Diagnose, fix, and report back.";function kp(e,o){return[{dir:Fe(e,"node-a"),id:"demo-laptop",name:"laptop-paris",port:o,agentId:"cx",agentName:"CX",persona:"You are CX, the customer-facing coordinator. You triage inbound issues and delegate technical work to @builder on the vps node.",script:{steps:[{match:"USER: Build the demo report workflow",reply:"Here is a scripted example: start it manually, ask CX for a report, then finish. It is saved disabled so you can review it before running.\n\n```json\n"+JSON.stringify(wc,null,2)+"\n```",delayMs:300,chunkMs:2},{match:"Prepare the demo shop report",reply:"Demo shop report: checkout checks passed, MR !47 is ready for review, and CX has drafted the customer update. This is a scripted example.",delayMs:500},{match:"checkout is broken",thinking:"Checkout failure + red CI \u2014 this is a build problem, not a support question. @builder on vps-nyc owns demo/shop.",reply:"Checkout failure traced to the red pipeline on demo/shop. This needs a code fix \u2014 delegating to @builder on the vps-nyc node over the mesh. I'll report back on this thread.",delayMs:900},{match:"Builder reports",thinking:"Fix confirmed and pipeline green \u2014 close the loop with the customer.",reply:"Resolved \u2705 \u2014 builder patched checkout.test.ts (Node 22 crypto import), MR !47 merged, pipeline green. Customer thread updated. Every hop of this run is in the ledger: `agentx ledger`.",delayMs:800}],fallback:{reply:"Demo mode \u2014 I answer from a script. Try the scripted scenario, or run `agentx setup` to connect a real model."}}},{dir:Fe(e,"node-b"),id:"demo-vps",name:"vps-nyc",port:o+1,agentId:"builder",agentName:"Builder",persona:"You are Builder, the engineering agent on the vps node. You fix code, open MRs, and report results tersely.",script:{steps:[{match:"checkout\\.test\\.ts|CI is red",thinking:"Reproducing on Node 22\u2026 crypto.webcrypto import moved. Patching the test setup, rerunning the suite.",reply:"Fixed. checkout.test.ts assumed the legacy crypto.webcrypto import \u2014 patched for Node 22, suite green locally. Opened MR !47 on demo/shop; pipeline is green. Handing back to @cx.",delayMs:1400,chunkMs:40}],fallback:{reply:"Builder here (demo script). Send me a failing pipeline."}}},{dir:Fe(e,"node-c"),id:"demo-pi",name:"pi-office",port:o+2,agentId:"scout",agentName:"Scout",persona:"You are Scout, the monitoring agent on the office Raspberry Pi. You watch schedules and report status.",script:{fallback:{reply:"Scout here (demo script) \u2014 all monitors green on pi-office."},steps:[]}}]}function vp(e,o,t){let n=Fe(e.dir,"workspaces",e.agentId);yp(n,{recursive:!0}),ei(Fe(n,"CLAUDE.md"),`# ${e.agentName}
|
|
463
|
+
|
|
464
|
+
${e.persona}
|
|
465
|
+
`),ei(Fe(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};ei(Fe(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function oi(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 ti(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 Wn(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
|
|
466
|
+
`).join(`
|
|
467
|
+
`)}`)}var xc=new hp().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=wp(process.cwd(),".agentx-demo"),n=kp(t,o),s=bp(24).toString("hex"),i=[],r=process.argv[1];(!r||!kc(r))&&(console.error(le.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),kc(t)&&bc(t,{recursive:!0,force:!0});for(let d of n)vp(d,n,s);console.log(),console.log(le.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(le.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(le.dim(" Run `agentx setup` to wire real agents.\n"));let a=!1,c=d=>{if(!a){a=!0;for(let g of i)try{g.kill("SIGTERM")}catch{}setTimeout(()=>{if(!e.keep)try{bc(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=$c(Fe(p.dir,"daemon.log"),"a"),w=Zs(process.execPath,[r,"daemon","start","-c",Fe(p.dir,"agentx.json")],{cwd:p.dir,env:{...l,MESH_TOKEN:s,AGENTX_DEMO_SCRIPT:Fe(p.dir,"demo-script.json")},stdio:["ignore",f,f]});i.push(w),console.log(le.dim(` \u25B8 ${p.name} starting on 127.0.0.1:${p.port} (log: ${Fe(p.dir,"daemon.log")})`))}for(let p of n)await oi(`${p.name} /health`,async()=>(await fetch(`http://127.0.0.1:${p.port}/health`)).ok,3e4);console.log(le.green(" \u2713 three daemons up"));let d=n[0].port+10;{let p=$c(Fe(n[0].dir,"board.log"),"a"),f=Zs(process.execPath,[r,"board","serve"],{cwd:n[0].dir,env:{...l,MESH_TOKEN:s},stdio:["ignore",p,p]});i.push(f)}await oi("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${d}/live`)).ok,3e4),console.log(le.green(" \u2713 dashboard up")),await oi("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(le.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: ${le.cyan(g)} (all three nodes via the mesh)`),console.log(le.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{Zs(p,[g],{stdio:"ignore",detached:!0}).unref()}catch{}}let u=async()=>{console.log(),console.log(le.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Wn("You \u2192 @cx (laptop-paris)",vc,le.cyan);let p=await ti(n[0].port,"/task",{agent:"cx",message:vc});Wn("@cx (laptop-paris)",p.content||"(no content)",le.green),console.log(),console.log(le.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let f=await ti(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:$p}),w=typeof f.messageId=="string"?f.messageId:f.content||"(no reply)";Wn("@builder (vps-nyc)",w,le.yellow);let y=await ti(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${w}`});Wn("@cx (laptop-paris)",y.content||"(no content)",le.green),console.log(),console.log(le.dim(` Inspect the run: ${g} \xB7 ledger rows on each node record every dispatch`)),console.log(le.dim(` Worth your time? A star helps others find it: ${le.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(await u(),e.once){console.log(),console.log(le.dim(" --once: shutting down.")),c(0);return}console.log(),console.log(le.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{u().catch(p=>console.error(le.red(` Replay failed: ${p.message}`)))}),process.stdin.resume()}catch(d){console.error(),console.error(le.red(` Demo failed: ${d.message}`)),console.error(le.dim(` Node logs: ${n.map(g=>Fe(g.dir,"daemon.log")).join(", ")}`)),c(1)}});Oe();import{Command as xp}from"commander";import Se from"chalk";var xo=new xp().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");xo.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 Jt("/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(Se.dim(" no chats cached yet"));return}console.log(),console.log(Se.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Se.cyan("group"):Se.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Se.dim(n.jid.padEnd(40))} ${Se.dim(i)}`)}console.log()}catch(o){ut(o)}});xo.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 Jt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Se.dim(" no contacts cached yet"));return}console.log(),console.log(Se.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} ${Se.dim(i)} ${Se.dim(n.jid)}`)}console.log()}catch(o){ut(o)}});xo.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 si("/whatsapp/ingest",o);ni(t,!!e.dryRun)}catch(o){ut(o)}});xo.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 si("/whatsapp/ingest",t);ni(n,!!o.dryRun)}catch(t){ut(t)}});xo.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 si("/whatsapp/ingest",t);ni(n,!!o.dryRun)}catch(t){ut(t)}});xo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Jt("/whatsapp/state"),o=await Jt("/whatsapp/chats"),t=await Jt("/whatsapp/contacts");console.log(),console.log(Se.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){ut(e)}});function ni(e,o){if(console.log(),console.log(Se.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(Se.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Se.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Se.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Se.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Se.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Sc(){try{let e=W(),[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 Jt(e){let o=await fetch(`${Sc()}${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 si(e,o){let t=await fetch(`${Sc()}${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 ut(e){console.error(Se.red(` ${e.message||e}`)),process.exit(1)}Oe();import{Command as Sp}from"commander";import ie from"chalk";import{existsSync as Ep,mkdirSync as Ec,writeFileSync as Ht}from"fs";import{join as ft,resolve as Ap}from"path";var Gt=new Sp().name("plugin").description("manage agentx plugins (Move B)");Gt.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=W().plugins??[];if(console.log(),o.length===0){console.log(ie.dim(" No plugins configured.")),console.log(ie.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ie.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ie.cyan(t)}`);console.log(),console.log(ie.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ie.red(` ${e.message}`)),process.exitCode=1}});Gt.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(ie.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=Ap(o.cwd,t);Ep(n)&&!o.force&&(console.log(ie.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Ec(n,{recursive:!0}),Ec(ft(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;Ht(ft(n,"package.json"),jp(e,s)),Ht(ft(n,"tsconfig.json"),Rp()),Ht(ft(n,"src/index.ts"),Tp(e)),Ht(ft(n,"README.md"),Np(e,s)),Ht(ft(n,".gitignore"),_p()),console.log(),console.log(ie.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ie.bold(" Next steps:")),console.log(ie.dim(` cd ${t}`)),console.log(ie.dim(" pnpm install")),console.log(ie.dim(" pnpm build")),console.log(ie.dim(" pnpm link --global # for local testing")),console.log(ie.dim(" # then in your agentx project:")),console.log(ie.dim(` pnpm link --global ${e}`)),console.log(ie.dim(` agentx config set plugins[0] "${e}"`)),console.log(ie.dim(" agentx plugin doctor")),console.log()});Gt.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=W().plugins??[];if(console.log(),o.length===0){console.log(ie.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Op(n);s.kind==="ok"?console.log(` ${ie.green("\u2713")} ${ie.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ie.red("\u2717")} ${ie.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ie.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ie.red(` ${e.message}`)),process.exitCode=1}});async function Op(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Ip(o);if(!Cp(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=Yi.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 Ip(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 Cp(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function jp(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)+`
|
|
468
|
+
`}function Rp(){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)+`
|
|
469
|
+
`}function Tp(e){return`// ${e} \u2014 AgentX plugin
|
|
470
|
+
//
|
|
471
|
+
// A plugin's default export is { manifest, setup }. The daemon calls
|
|
472
|
+
// setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
|
|
473
|
+
// registers a custom channel adapter; ctx.log() namespaces output.
|
|
474
|
+
|
|
475
|
+
const plugin = {
|
|
476
|
+
manifest: {
|
|
477
|
+
name: ${JSON.stringify(e)},
|
|
478
|
+
version: "0.1.0",
|
|
479
|
+
// agentxRange: "0.x", // optional \u2014 gate against the daemon's major.minor
|
|
480
|
+
},
|
|
481
|
+
|
|
482
|
+
setup(ctx: any) {
|
|
483
|
+
ctx.log("hello from", ${JSON.stringify(e)})
|
|
484
|
+
|
|
485
|
+
// Example: log every completed task.
|
|
486
|
+
ctx.on("task:completed", (payload: any) => {
|
|
487
|
+
ctx.log("task done:", payload.agentId, payload.durationMs + "ms")
|
|
488
|
+
})
|
|
489
|
+
|
|
490
|
+
// Example: register a no-op channel adapter.
|
|
491
|
+
// ctx.addChannel({
|
|
492
|
+
// name: "my-channel",
|
|
493
|
+
// start: async () => {},
|
|
494
|
+
// stop: async () => {},
|
|
495
|
+
// send: async (out) => { ctx.log("send:", out) },
|
|
496
|
+
// })
|
|
497
|
+
},
|
|
498
|
+
|
|
499
|
+
// Optional \u2014 only needed for resources you own (timers, sockets).
|
|
500
|
+
// Bus subscriptions are removed automatically.
|
|
501
|
+
// teardown() {},
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export default plugin
|
|
505
|
+
`}function Np(e,o){return`# ${e}
|
|
506
|
+
|
|
507
|
+
${o}
|
|
508
|
+
|
|
509
|
+
## Install
|
|
510
|
+
|
|
511
|
+
\`\`\`bash
|
|
512
|
+
pnpm install ${e}
|
|
513
|
+
\`\`\`
|
|
514
|
+
|
|
515
|
+
## Use
|
|
516
|
+
|
|
517
|
+
Add to \`agentx.json\`:
|
|
518
|
+
|
|
519
|
+
\`\`\`json
|
|
520
|
+
{
|
|
521
|
+
"plugins": ["${e}"]
|
|
522
|
+
}
|
|
523
|
+
\`\`\`
|
|
524
|
+
|
|
525
|
+
Then verify the load:
|
|
526
|
+
|
|
527
|
+
\`\`\`bash
|
|
528
|
+
agentx plugin doctor
|
|
529
|
+
\`\`\`
|
|
530
|
+
|
|
531
|
+
Restart the daemon to activate.
|
|
532
|
+
`}function _p(){return`node_modules/
|
|
533
|
+
dist/
|
|
534
|
+
*.log
|
|
535
|
+
.env
|
|
536
|
+
`}import{Command as Dp}from"commander";import Ee from"chalk";import{writeFileSync as Pp,mkdirSync as Lp,existsSync as Bn,readFileSync as Ac,appendFileSync as Oc}from"fs";import{resolve as ht,dirname as jc}from"path";import{homedir as ri}from"os";var Rc=new Dp().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-GSZ5AYAM.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Fp(t);break;case"bash":s=Hp(t);break;case"fish":s=Gp(t);break;default:console.error(Ee.red(`unsupported shell: ${n}`)),console.error(Ee.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?ht(String(e.output)):Mp(n);Lp(jc(i),{recursive:!0}),Pp(i,s),console.log(Ee.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Up(n,i,!!e.yes)});function Mp(e){let o=ri();switch(e){case"zsh":return ht(o,".zsh","completions","_agentx");case"bash":return ht(o,".bash_completion.d","agentx.bash");case"fish":return ht(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Up(e,o,t){if(e==="zsh"){let n=ht(ri(),".zshrc"),s=jc(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Bn(n)?Ac(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ee.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Bn(n)){let d=["","# agentx completion"];c&&d.push(i),l&&d.push(r),Oc(n,d.join(`
|
|
537
|
+
`)+`
|
|
538
|
+
`),console.log(Ee.green("\u2713 Patched ~/.zshrc")),console.log(Ee.dim("Reload your shell: exec zsh"));return}console.log(Ee.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ee.cyan(` ${i}`)),l&&console.log(Ee.cyan(` ${r}`)),console.log(),console.log(Ee.dim("Then reload: exec zsh")),console.log(Ee.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=ht(ri(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Bn(n)?Ac(n,"utf-8"):"").includes(o)){console.log(Ee.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Bn(n)){Oc(n,`
|
|
539
|
+
# agentx completion
|
|
540
|
+
${s}
|
|
541
|
+
`),console.log(Ee.green("\u2713 Patched ~/.bashrc")),console.log(Ee.dim("Reload your shell: exec bash"));return}console.log(Ee.dim("Add this to ~/.bashrc:")),console.log(Ee.cyan(` ${s}`)),console.log(),console.log(Ee.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(Ee.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function Le(e){return e._name||e.name()||""}function So(e){return e.commands.filter(o=>{let t=Le(o);return!(!t||t==="help")})}function zt(e){return e.options.filter(o=>!o.hidden)}function Fp(e){let o=[];return o.push("#compdef agentx"),o.push(""),Tc(e,[],o),o.push("compdef _agentx_root_completion agentx"),o.push(""),o.join(`
|
|
542
|
+
`)}function Ic(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Tc(e,o,t){let n=So(e),i=zt(e).map(Bp).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(Jp).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,Le(c)]);t.push(` (${Le(c)}) ${l} ;;`)}t.push(" esac"),t.push(" ;;"),t.push(" esac")}t.push("}"),t.push("");for(let c of n)Tc(c,[...o,Le(c)],t)}function qp(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Wp(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Bp(e){let o=e.short||void 0,t=e.long||void 0;if(!o&&!t)return null;let n=qp(e.description||"");return o&&t?` "(${t} ${o})"{${t},${o}}"[${n}]"`:` "${t||o}[${n}]"`}function Jp(e){let o=Wp(e.description()||"");return`'${Le(e)}[${o}]'`}function Hp(e){let o=So(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(Le).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=So(n).map(Le),i=Cc(n);if(t.push(` ${Le(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 So(n)){let a=Cc(r);t.push(` ${Le(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(`
|
|
543
|
+
`)}function Cc(e){let o=[];for(let t of zt(e))t.long&&o.push(t.long),t.short&&o.push(t.short);return o.join(" ")}function Gp(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 So(e)){let n=ai(t.description()||"");o.push(`complete -c agentx -n "__fish_use_subcommand" -a "${Le(t)}" -d "${n}"`)}o.push("");for(let t of zt(e)){let n=ii(t,["__fish_use_subcommand"]);n&&o.push(n)}o.push("");for(let t of So(e)){let n=Le(t);o.push(`# ${n}`);for(let s of zt(t)){let i=ii(s,[`__fish_seen_subcommand_from ${n}`]);i&&o.push(i)}for(let s of So(t)){let i=ai(s.description()||"");o.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${So(t).map(Le).join(" ")}" -a "${Le(s)}" -d "${i}"`);for(let r of zt(s)){let a=ii(r,[`__fish_seen_subcommand_from ${Le(s)}`]);a&&o.push(a)}}o.push("")}return o.join(`
|
|
544
|
+
`)}function ai(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ii(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=ai(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 wv(){let e=await ir(),o=new zp().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=lr(n);dr(s)&&cr("cli",s)});for(let t of[Mr,Dr,rt,Vo,Ke,ar,Co,pn,bo,Do,mn,mc,wo,Xr,ra,ha,ba,$a,xa,Mt,yc,Ot,uo,Rc])o.addCommand(t);for(let t of Nc)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Nc.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Yp(t,74," "),""].join(`
|
|
545
|
+
`)}),o}var Nc=[Z,at,Fo,ze,Ct,nt,Pe,ao,$o,Po,gt,mt,yo,_e,jt,An,dc,so,et,ur,jo,Gt,gs,vo,Zo,ms,Mn,pt,xo,xc,hc];function Yp(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(`
|
|
546
|
+
`)}export{wv as a};
|
|
547
|
+
//# sourceMappingURL=chunk-VIH7ARPF.js.map
|