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
package/dist/chunk-E5CXCI33.js
DELETED
|
@@ -1,155 +0,0 @@
|
|
|
1
|
-
import{C as sn,a as zt,e as nn}from"./chunk-MTAPOCGA.js";import{c as Kt,e as Qt,f as Xt,h as Yt}from"./chunk-67Q4DCPS.js";import{a as tn}from"./chunk-W4YR2RO2.js";import{a as Le,c as Vt}from"./chunk-D46VZ7K7.js";import{a as je,b as at}from"./chunk-HR4JSRZS.js";import{b as Gt,c as qt,f as Jt}from"./chunk-BFXONUUN.js";import{a as ct,b as Zt}from"./chunk-SR3X25TN.js";import{a as dt,b as en}from"./chunk-53NRX2NA.js";import{e as ie}from"./chunk-DSYKYZMT.js";import{a as Bt}from"./chunk-5U35WAZF.js";import{c as Ne,d as Fe}from"./chunk-QOYAX2FT.js";import{execa as Ge}from"execa";import{execFile as bs}from"child_process";import{StringDecoder as ke}from"string_decoder";import{mkdtempSync as un,readFileSync as ln,rmSync as gn}from"fs";import{join as Ke}from"path";import{tmpdir as pn}from"os";function He(r){let e=(r||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let s=n?.error||n,o=typeof s?.type=="string"?s.type:void 0,i=typeof s?.message=="string"?s.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ue(r){return r.fix?`${r.message} \u2014 ${r.fix}`:r.message}var rn=null;function We(){return rn}function ro(r){rn=r}function Te(r){return`${r.agentId}:${r.channel}:${r.chatId}`}var pe=class extends Error{constructor(t,n,s){super(t);this.scope=n;this.cap=s;this.name="RegistryCapExceeded"}},on=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=Te(e),s=this.handles.get(n);if(s&&s.state()!=="dead")return s.claim?.(),s;if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new pe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new pe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Te(e),s=this.handles.get(n);s&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&s.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Te(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Te(e),s=this.handles.get(n);s&&(this.handles.delete(n),this.handleWorkspace.delete(n),await s.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let s=Te(t.key);return this.handles.delete(s),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${s} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let s=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-s.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==s.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=s.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};function K(r){let e=He(r);if(e.kind==="invalid_request"||e.kind==="unknown"){let t=(r||"").replace(/\s+/g," ").slice(0,800);t&&process.stderr.write(`[agentx][model-error][${e.kind}] raw=${t}
|
|
2
|
-
`)}return{error:Ue(e),errorKind:e.kind}}function fn(){return`Claude Code CLI not found on PATH. Install it before starting an agent: https://docs.claude.com/en/docs/claude-code . On Linux/macOS: npm i -g @anthropic-ai/claude-code then verify with claude --version. If you don't intend to use the claude-code engine, set the agent's tier to "sdk" or "orchestrator" in agentx.json.`}function Be(){return`Codex CLI not found on PATH. Install it before starting an agent: npm i -g @openai/codex then verify with codex --version. If you don't intend to use the codex-cli engine, set the agent's tier to "claude-code", "sdk", or "orchestrator" in agentx.json.`}function an(){return`OpenCode CLI not found on PATH. Install it from https://opencode.ai/docs/ and verify with opencode --version. If you don't intend to use the opencode engine, set the agent's tier to "claude-code", "codex-cli", "sdk", or "orchestrator" in agentx.json.`}function ae(r,e,t){let n=[];if(e.context&&!t){let s=e.context,o=["","[Environment]"],i=s.channel==="gitlab"||s.channel?.startsWith("webhook:"),a=s.channel==="telegram";if(s.channel&&o.push(`Channel: ${s.channel}`),s.group&&o.push(`Group: ${s.group}`),s.sender&&o.push(`Message from: ${s.sender}`),s.myHandle&&o.push(`Your handle on this channel: ${s.myHandle}`),i&&(o.push(""),o.push("[IMPORTANT: You are responding to a GitLab comment/event]"),o.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),o.push("- Lead with the result or action, not a narration of what you plan to do"),o.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),o.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),o.push("- Do NOT try to delegate to other agents \u2014 reply directly"),o.push("- Reference issues with #IID and MRs with !IID")),a&&s.peers?.length){o.push(""),o.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let c of s.peers){let d=c.handle?` (mention: ${c.handle})`:"",u=c.role?` \u2014 ${c.role}`:"";o.push(`\u2022 ${c.name}${d}${u}`)}o.push(""),o.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(o.join(`
|
|
3
|
-
`))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
|
|
4
|
-
`)}function hn(r,e,t,n,s,o){let i=["-p",e,"--output-format",t?"stream-json":"json"];t&&i.push("--verbose"),n&&i.push("--resume",n);let a=s||r.model;return a&&i.push("--model",a),r.permissionMode==="bypassPermissions"&&i.push("--dangerously-skip-permissions"),o&&o.trim().length>0&&i.push("--append-system-prompt",o),i}function mn(r,e){return!e||e.trim().length===0?r:`[System]
|
|
5
|
-
${e.trim()}
|
|
6
|
-
|
|
7
|
-
[User]
|
|
8
|
-
${r}`}function xs(r,e,t,n,s){let o=["run","--format","json","--thinking"],i=t||r.model;return i&&o.push("--model",i),s&&o.push("--session",s),r.permissionMode==="bypassPermissions"&&o.push("--auto"),o.push(mn(e,n)),o}function ws(r){if(!r||typeof r!="object"||r.type!=="error")return;let e=r.error?.message??r.error??r.message??r.part?.error?.message;return typeof e=="string"&&e.trim()?e.trim():void 0}function cn(r){return JSON.stringify(r)}function Ts(){let r=process.argv[1]||"dist/cli.js";return["-c",`mcp_servers.agentx.command=${cn(process.execPath)}`,"-c",`mcp_servers.agentx.args=[${[r,"serve","--stdio","--cwd",process.cwd()].map(cn).join(",")}]`]}function yn(r,e,t,n,s,o,i){let a=i?["exec","resume"]:["exec"];a.push("--ignore-user-config","--skip-git-repo-check",...Ts()),i||a.push("--color","never");let c=n||r.model;return c&&a.push("--model",c),r.permissionMode==="bypassPermissions"?a.push("--dangerously-bypass-approvals-and-sandbox"):i||a.push("--sandbox","workspace-write"),(t||i||o)&&a.push("--json"),o&&a.push("--output-last-message",o),i&&a.push(i),a.push(mn(e,s)),a}function ut(r,e){let t=je(r.workspace),n=t.HOME||process.env.HOME,s=[t.PATH||"",n?`${n}/.bun/bin`:"",n?`${n}/.local/bin`:"",n?`${n}/.opencode/bin`:"","/opt/homebrew/bin","/usr/local/bin"].filter(Boolean);return t.PATH=Array.from(new Set(s.flatMap(o=>o.split(":")).filter(Boolean))).join(":"),t.AGENTX_AGENT_ID=e.agentId,e.context?.channel&&(t.AGENTX_CHANNEL=e.context.channel),e.context?.chatId&&(t.AGENTX_CHAT_ID=e.context.chatId),t}function ks(r,e){let t=ut(r,e),n={};if(t.OPENCODE_CONFIG_CONTENT)try{n=JSON.parse(t.OPENCODE_CONFIG_CONTENT)}catch{}let s={...n.mcp||{}};for(let[i,a]of Object.entries(r.mcp||{}))s[i]=a.type==="http"?{type:"remote",url:a.url,headers:a.headers}:{type:"local",command:[a.command,...a.args||[]],environment:a.env};let o=process.argv[1]||"dist/cli.js";return s.agentx={type:"local",command:[process.execPath,o,"serve","--stdio","--cwd",process.cwd()]},t.OPENCODE_CONFIG_CONTENT=JSON.stringify({...n,mcp:s}),t}function Is(r){if(!r||typeof r!="object")return;if(typeof r.delta=="string")return r.delta;if(typeof r.text_delta=="string")return r.text_delta;if(typeof r.message=="string"&&/message|delta/i.test(String(r.type||"")))return r.message;if(typeof r.text=="string"&&/message|delta|response/i.test(String(r.type||"")))return r.text;let e=r.item||r.msg||r.message;if(e?.type==="agent_message"&&typeof e.text=="string"||typeof e?.text=="string"&&/message|delta|response|item/i.test(String(r.type||"")))return e.text;let t=e?.content;if(Array.isArray(t)){let n=t.map(s=>typeof s?.text=="string"?s.text:"").join("");if(n)return n}}function ee(...r){for(let e of r)if(typeof e=="number"&&Number.isFinite(e))return e;return 0}function lt(r,e=0){if(!r||typeof r!="object"||e>4)return;let t=r.usage||r.token_usage||r.tokenUsage||r.metrics?.usage;if(t&&typeof t=="object")return{inputTokens:ee(t.input_tokens,t.inputTokens,t.prompt_tokens,t.promptTokens),outputTokens:ee(t.output_tokens,t.outputTokens,t.completion_tokens,t.completionTokens),cacheReadTokens:ee(t.cache_read_input_tokens,t.cached_input_tokens,t.cacheReadTokens,t.cachedInputTokens),cacheCreateTokens:ee(t.cache_creation_input_tokens,t.cacheCreateTokens)};for(let n of[r.msg,r.message,r.response,r.result,r.item]){let s=lt(n,e+1);if(s)return s}}function bn(r){if(!(!r||typeof r!="object"))return typeof r.model=="string"&&r.model||typeof r.msg?.model=="string"&&r.msg.model||typeof r.message?.model=="string"&&r.message.model||typeof r.response?.model=="string"&&r.response.model||void 0}function gt(r,e=0){if(!(!r||typeof r!="object"||e>4)){for(let t of["thread_id","threadId","session_id","sessionId","conversation_id","conversationId"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}for(let t of[r.msg,r.message,r.response,r.result,r.item]){let n=gt(t,e+1);if(n)return n}}}function Ss(r){let e=typeof r=="string"?r:r?.toString("utf8")||"",t,n,s,o;for(let i of e.split(`
|
|
9
|
-
`))if(i.trim())try{let a=JSON.parse(i);t=lt(a)||t,n=bn(a)||n,s=gt(a)||s,o=xn(a)||o}catch{}return{usage:t,billedModel:n,sessionId:s,apiError:o}}function xn(r){if(!(!r||typeof r!="object")){if(r.type==="error"&&typeof r.message=="string")return dn(r.message);if(r.type==="turn.failed"){let e=r.error?.message??r.error;if(typeof e=="string")return dn(e)}}}function dn(r){let e=r.trim();if(e.startsWith("{"))try{let t=JSON.parse(e),n=t?.error?.message??t?.message;if(typeof n=="string"&&n.trim())return n.trim()}catch{}return e}function Cs(r){let e=r.permissionMode||"default",t=e==="bypassPermissions",n=t?"bypassPermissions (--dangerously-skip-permissions)":`${e} (no skip-permissions flag)`;return{configured:e,skipPermissions:t,summary:n}}function pt(r,e,t,n,s){let o=Cs(e),i=t||e.model||"<default>",a=n?` resume=${n.slice(0,8)}\u2026`:"";process.stderr.write(`[claude-spawn] agent=${r} via=${s} model=${i} perm=${o.summary}${a}
|
|
10
|
-
`)}function vs(r){try{let e=JSON.parse(r);if(e&&e.is_error&&typeof e.result=="string")return e.result;if(e&&e.error&&typeof e.error=="string")return e.error}catch{}return null}function $s(r){try{let e=JSON.parse(r),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0,n=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:n}}catch{return{text:r}}}async function As(r,e,t,n,s){let o=Date.now(),i=ae(r,e,t),a=hn(r,i,!1,n,e.model,e.systemPromptAppend);if(pt(e.agentId,r,e.model,n,"spawn"),s?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-o};let c;try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),{stdout:u,stderr:l,exitCode:g,killed:m}=await new Promise(x=>{let p=at(je(r.workspace)),f=!1,D=bs("claude",a,{cwd:r.workspace,timeout:d,maxBuffer:10*1024*1024,env:{...p,HOME:p.HOME||"/home/"+(p.USER||"user")}},(C,T,$)=>{x({stdout:T||"",stderr:$||"",exitCode:C?C.code??1:0,killed:f})});if(D.stdin?.end(),s){let C=()=>{f=!0,c=s.reason?.message||(typeof s.reason=="string"?s.reason:"task cancelled by operator");try{D.kill("SIGTERM")}catch{}setTimeout(()=>{try{D.killed||D.kill("SIGKILL")}catch{}},3e3).unref?.()};s.aborted?C():s.addEventListener("abort",C,{once:!0})}});if(m)return{content:"",error:c||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-o};if(!u&&g!==0){let x;return g===143?x=`Claude Code timed out after ${Math.round(d/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:g==="ENOENT"||/ENOENT|spawn claude/i.test(l||"")?x=fn():x=l?.trim()||`Claude Code exited with code ${g}`,{content:"",...K(x),duration:Date.now()-o}}let b=vs(u);if(b)return{content:"",...K(b),duration:Date.now()-o};let w=$s(u);return{content:w.text,duration:Date.now()-o,claudeSessionId:w.sessionId,usage:w.usage,billedModel:w.billedModel}}catch(d){return console.error(`[runtime] execFile threw: ${d.message}`),{content:"",error:d.message||"Claude Code failed",duration:Date.now()-o}}}async function Ms(r,e,t,n,s,o,i){let a=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",duration:Date.now()-a};let c=ae(r,e,n),d=hn(r,c,!0,s,e.model,e.systemPromptAppend);pt(e.agentId,r,e.model,s,"stream");let u="",l,g,m,b,w;try{let x=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),p=at(je(r.workspace)),f=Ge("claude",d,{cwd:r.workspace,timeout:x,reject:!1,env:p,extendEnv:!1,buffer:!1,stdin:"ignore"}),D=!1,C;if(i){let A=()=>{D=!0,C=i.reason?.message||(typeof i.reason=="string"?i.reason:"task cancelled by operator");try{f.kill("SIGTERM")}catch{}setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},3e3).unref?.()};i.aborted?A():i.addEventListener("abort",A,{once:!0})}let T="",$=new ke("utf8");f.stdout&&f.stdout.on("data",A=>{T+=$.write(A);let R=T.split(`
|
|
11
|
-
`);T=R.pop()||"";for(let S of R)if(S.trim())try{let I=JSON.parse(S);if(o)try{o(I)}catch{}if(I.type==="assistant"&&I.message?.usage){let P=I.message.usage,E=(P.input_tokens||0)+(P.cache_read_input_tokens||0)+(P.cache_creation_input_tokens||0);E>0&&(b=E)}if(I.type==="assistant"&&I.message?.content){for(let P of I.message.content)if(P.type==="text"&&P.text){let E=P.text.slice(u.length);E&&(u=P.text,t(E,u))}}if(I.type==="content_block_delta"&&I.delta?.text&&(u+=I.delta.text,t(I.delta.text,u)),I.type==="result"&&I.result){if(I.is_error&&typeof I.result=="string")w=I.result;else{let P=(typeof I.result=="string",I.result);if(typeof P=="string"&&P.length>u.length){let E=P.slice(u.length);u=P,E&&t(E,u)}}I.usage&&(g={inputTokens:I.usage.input_tokens||0,outputTokens:I.usage.output_tokens||0,cacheReadTokens:I.usage.cache_read_input_tokens||0,cacheCreateTokens:I.usage.cache_creation_input_tokens||0}),typeof I.model=="string"&&(l=I.model),typeof I.session_id=="string"&&(m=I.session_id)}I.type==="system"&&I.subtype==="init"&&(typeof I.model=="string"&&(l=I.model),process.env.AGENTX_DEBUG_CLAUDE_ENV==="1"&&process.stderr.write(`[claude-init] agent=${e.agentId} apiKeySource=${I.apiKeySource} version=${I.claude_code_version} model=${I.model} permMode=${I.permissionMode}
|
|
12
|
-
`))}catch{S.trim()&&!S.startsWith("{")&&(u+=S+`
|
|
13
|
-
`,t(S+`
|
|
14
|
-
`,u))}});let F=await f,k=$.end();if(k&&(T+=k),D)return{content:"",error:C||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-a};if(!u&&F.stdout&&(u=typeof F.stdout=="string"?F.stdout:""),F.exitCode!==0&&!u){let A=typeof F.stderr=="string"?F.stderr:"",R=F,S;return R.timedOut?S=`Claude Code timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:R.signal?S=A.trim()||`Claude Code killed by signal ${R.signal}`:R.code==="ENOENT"||/ENOENT|spawn claude/i.test((R.shortMessage||"")+" "+A)?S=fn():S=A.trim()||`Claude Code exited with code ${R.exitCode??"unknown"}`,{content:"",...K(S),duration:Date.now()-a}}return w?{content:"",...K(w),duration:Date.now()-a,usage:g,contextTokens:b,billedModel:l,claudeSessionId:m}:{content:u,duration:Date.now()-a,usage:g,contextTokens:b,billedModel:l,claudeSessionId:m}}catch(x){return{content:u||"",...K(x.message),duration:Date.now()-a,usage:g,contextTokens:b,billedModel:l,claudeSessionId:m}}}async function Rs(r,e,t,n){let s=Date.now(),o=ae(r,e,t),i=un(Ke(pn(),"agentx-codex-")),a=Ke(i,"last-message.txt"),c=yn(r,o,!1,e.model,e.systemPromptAppend,a,n);try{let d=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),u=await Ge("codex",c,{cwd:r.workspace,timeout:d,reject:!1,env:ut(r,e),extendEnv:!1,stdin:"ignore"}),l=Ss(u.stdout);if(u.exitCode!==0||l.apiError){let m=u,b;return m.timedOut?b=`Codex CLI timed out after ${Math.round(d/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:l.apiError?b=l.apiError:m.signal?b=u.stderr.trim()||`Codex CLI killed by signal ${m.signal}`:m.code==="ENOENT"||/ENOENT|spawn codex/i.test((m.shortMessage||"")+" "+u.stderr)?b=Be():b=u.stderr.trim()||u.stdout.trim()||`Codex CLI exited with code ${m.exitCode??"unknown"}`,{content:"",...K(b),duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}let g="";try{g=ln(a,"utf8").trim()}catch{}return g||(g=u.stdout.trim()),{content:g,duration:Date.now()-s,usage:l.usage,billedModel:l.billedModel,codexSessionId:l.sessionId||n}}catch(d){let u=/ENOENT|spawn codex/i.test(d?.message||"")?Be():d?.message;return{content:"",...K(u||"Codex CLI failed"),duration:Date.now()-s}}finally{gn(i,{recursive:!0,force:!0})}}async function Ps(r,e,t,n,s,o){let i=Date.now(),a=ae(r,e,n),c=un(Ke(pn(),"agentx-codex-")),d=Ke(c,"last-message.txt"),u=yn(r,a,!0,e.model,e.systemPromptAppend,d,s),l="",g,m,b,w;try{let x=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),p=Ge("codex",u,{cwd:r.workspace,timeout:x,reject:!1,env:ut(r,e),extendEnv:!1,buffer:!1,stdin:"ignore"});if(o)try{o({type:"codex.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let f="",D="",C=!1,T=new ke("utf8"),$=new ke("utf8"),F=Math.min(x,Math.max(3e4,Number(process.env.AGENTX_CODEX_IDLE_TIMEOUT_MS||18e4))),k,A=()=>{k&&clearTimeout(k),k=setTimeout(()=>{C=!0,p.kill("SIGTERM",{forceKillAfterTimeout:5e3})},F)};A(),p.stderr?.on("data",E=>{A(),D+=$.write(E),D.length>16e3&&(D=D.slice(-16e3))}),p.stdout?.on("data",E=>{A(),f+=T.write(E);let W=f.split(`
|
|
15
|
-
`);f=W.pop()||"";for(let _ of W)if(_.trim())try{let q=JSON.parse(_);if(o)try{o(q)}catch{}g=lt(q)||g,m=bn(q)||m,b=gt(q)||b,w=xn(q)||w;let O=Is(q);if(O&&O!==l){let J=O.startsWith(l)?O.slice(l.length):O;l=O.startsWith(l)?O:l+O,J&&t(J,l)}}catch{l+=_+`
|
|
16
|
-
`,t(_+`
|
|
17
|
-
`,l)}});let R=await p;k&&clearTimeout(k);let S=T.end();S&&(f+=S);let I=$.end();if(I&&(D+=I),R.exitCode!==0&&!l||w){let E=D||(typeof R.stderr=="string"?R.stderr:""),W=R,_;return C?_=`Codex CLI produced no output for ${Math.round(F/1e3)}s and was stopped. AgentX sent a smaller prompt; retry the task or set AGENTX_CODEX_IDLE_TIMEOUT_MS if this turn needs longer.`:W.timedOut?_=`Codex CLI timed out after ${Math.round(x/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:w?_=w:W.signal?_=E.trim()||`Codex CLI killed by signal ${W.signal}`:W.code==="ENOENT"||/ENOENT|spawn codex/i.test((W.shortMessage||"")+" "+E)?_=Be():_=E.trim()||`Codex CLI exited with code ${W.exitCode??"unknown"}`,{content:"",...K(_),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:b||s}}let P="";try{P=ln(d,"utf8").trim()}catch{}if(P&&P!==l){let E=P.startsWith(l)?P.slice(l.length):P;l=P,E&&t(E,l)}return{content:l,duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:b||s}}catch(x){let p=/ENOENT|spawn codex/i.test(x?.message||"")?Be():x?.message;return{content:l,...K(p||"Codex CLI failed"),duration:Date.now()-i,usage:g,billedModel:m,codexSessionId:b||s}}finally{gn(c,{recursive:!0,force:!0})}}async function Ds(r,e,t,n,s,o,i,a){let c=Date.now();if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:0};let d=ae(r,e,n),u=xs(r,d,e.model,e.systemPromptAppend,s),l="",g,m=s,b;try{let w=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),x=Ge("opencode",u,{cwd:r.workspace,timeout:w,reject:!1,env:ks(r,e),extendEnv:!1,buffer:!1,stdin:"ignore"});try{o?.({type:"opencode.spawned",model:e.model||r.model,resumeSessionId:s})}catch{}let p=!1,f,D=()=>{p=!0,f=i?.reason?.message||(typeof i?.reason=="string"?i.reason:"task cancelled by operator");try{x.kill("SIGTERM",{forceKillAfterTimeout:3e3})}catch{}};i&&i.addEventListener("abort",D,{once:!0});let C="",T="",$=new ke("utf8"),F=new ke("utf8"),k=R=>{if(R.trim())try{let S=JSON.parse(R);try{o?.(S)}catch{}typeof S.sessionID=="string"&&(m=S.sessionID);let I=S.type==="text"&&typeof S.part?.text=="string"?S.part.text:void 0;I&&(l+=I,t?.(I,l));let P=S.type==="reasoning"&&typeof S.part?.text=="string"?S.part.text:void 0;P&&a?.(P);let E=S.type==="step_finish"?S.part?.tokens:void 0;E&&(g={inputTokens:ee(E.input),outputTokens:ee(E.output),cacheReadTokens:ee(E.cache?.read),cacheCreateTokens:ee(E.cache?.write)}),b=ws(S)||b}catch{l+=R+`
|
|
18
|
-
`,t?.(R+`
|
|
19
|
-
`,l)}};x.stdout?.on("data",R=>{C+=$.write(R);let S=C.split(`
|
|
20
|
-
`);C=S.pop()||"";for(let I of S)k(I)}),x.stderr?.on("data",R=>{T+=F.write(R)});let A=await x;if(i&&i.removeEventListener("abort",D),C+=$.end(),C.trim()&&k(C),T+=F.end(),p)return{content:"",error:f||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(A.exitCode!==0||b){let R=A,S;return R.timedOut?S=`OpenCode timed out after ${Math.round(w/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`:b?S=b:R.code==="ENOENT"||/ENOENT|spawn opencode/i.test((R.shortMessage||"")+" "+T)?S=an():S=T.trim()||`OpenCode exited with code ${R.exitCode??"unknown"}`,{content:"",...K(S),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return{content:l.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||r.model,opencodeSessionId:m}}catch(w){let x=/ENOENT|spawn opencode/i.test(w?.message||"")?an():w?.message;return{content:l,...K(x||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}}async function Os(r,e,t,n){let s=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ae(r,e,n),c="",d=i({prompt:a,options:{model:e.model||r.model,cwd:r.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-s}}catch(o){return{content:"",...K(`SDK error: ${o.message}`),duration:Date.now()-s}}}async function _s(r,e,t,n,s,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(r.maxExecutionMinutes??20)*6e4),l=new AbortController,g=!1,m=()=>{let x=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(x))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let b=setTimeout(()=>{g=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);b.unref?.();let w=()=>({content:"",...K(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${r.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let x=r.provider||"claude-code",p=n?`${n}
|
|
21
|
-
|
|
22
|
-
${e.message}`:e.message,f=e.context?.sender,D=typeof f=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(f),C=e.context?.channel==="web-chat"&&D?{userId:f,agentId:e.agentId||"noqta-public"}:void 0,T=Kt(r),$=Object.keys(T).length>0,F={task:p,cwd:r.workspace,provider:x,model:e.model||r.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,noqtaContext:C,providerOpts:o,abortSignal:l.signal,mcpServers:$?T:void 0};if(s){let{generateStream:I}=await import("./agent-5QMITZT6.js"),P="",E,W,_,q;for await(let O of I(F)){if(c)try{c(O)}catch{}if(O.type==="text_delta")P+=O.text,s(O.text,P);else if(O.type==="thinking_delta")O.text&&i&&i(O.text);else if(O.type==="generate_result"){if(O.result.content&&O.result.content!==P){let J=O.result.content.slice(P.length);J?(P=O.result.content,s(J,P)):P=O.result.content}E=O.result.tokensUsed,O.result.inputTokens!=null&&(W=O.result.inputTokens),O.result.outputTokens!=null&&(_=O.result.outputTokens)}else if(O.type==="done"){if(O.result.content&&O.result.content!==P){let J=O.result.content.slice(P.length);J?(P=O.result.content,s(J,P)):P=O.result.content}O.result.tokensUsed!=null&&(E=O.result.tokensUsed)}else O.type==="error"&&(q=O.error)}return q&&!P?g?w():q==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${q}`),duration:Date.now()-d}:((W===void 0||_===void 0)&&E&&(W=Math.round(E*.7),_=E-W),{content:P||"Done.",tokensUsed:E,usage:W!==void 0||_!==void 0?{inputTokens:W||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:k}=await import("./agent-5QMITZT6.js"),A=await k(F),R=A.inputTokens,S=A.outputTokens;if((R===void 0||S===void 0)&&A.tokensUsed){let I=A.tokensUsed;R=Math.round(I*.7),S=I-R}return{content:A.content||"Done.",tokensUsed:A.tokensUsed,usage:R!==void 0||S!==void 0?{inputTokens:R||0,outputTokens:S||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(x){return g?w():x?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${x.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",m)}}async function Es(r,e,t,n,s,o){let i=We();if(!i)return null;let a=Date.now(),c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:c,chatId:d};if(e.freshSession)try{await i.kill(u,"freshSession=true")}catch{}let l,g=!1;try{let k=i.list().length;l=i.acquire(u,{agentId:e.agentId,channel:c,chatId:d,workspace:r.workspace,model:e.model||r.model,permissionMode:r.permissionMode,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),g=i.list().length>k}catch(k){return k instanceof pe,null}g&&pt(e.agentId,r,e.model,n,"persistent");let m=ae(r,e,t),b="",w,x,p,f,D,C,T=!1,$=()=>{T=!0,i.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?$():o.addEventListener("abort",$,{once:!0}));let F=!1;try{for await(let k of l.runTurn({message:m,taskId:e.taskId??"unknown"})){if(F=!0,s)try{s(k.raw)}catch{}if(k.type==="assistant"){let A=k.raw.message?.content??[];for(let S of A)S.type==="text"&&typeof S.text=="string"&&(b=S.text);let R=k.raw.message?.usage;if(R){let S=(R.input_tokens||0)+(R.cache_read_input_tokens||0)+(R.cache_creation_input_tokens||0);S>0&&(f=S)}}if(k.type==="result"){let A=k.raw;if(A.is_error){let R=K(typeof A.result=="string"?A.result:"claude error");w=R.error,x=R.errorKind}else typeof A.result=="string"&&A.result.length>0&&(b=A.result);typeof A.session_id=="string"&&(C=A.session_id),A.usage&&(p={inputTokens:A.usage.input_tokens||0,outputTokens:A.usage.output_tokens||0,cacheReadTokens:A.usage.cache_read_input_tokens||0,cacheCreateTokens:A.usage.cache_creation_input_tokens||0}),typeof A.message?.model=="string"?D=A.message.model:typeof A.model=="string"&&(D=A.model)}}}catch(k){if(T)w="task cancelled by operator",x="cancelled";else if(F){let A=K(`persistent claude process error: ${k?.message||String(k)}`);w=A.error,x=A.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${k?.message||k}); falling back to spawn-per-task`),i.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",$),null}finally{o&&o.removeEventListener("abort",$)}return T&&!w&&(w="task cancelled by operator",x="cancelled"),{content:T?"":b,error:w,errorKind:x,duration:Date.now()-a,usage:p,contextTokens:f,billedModel:D,claudeSessionId:C}}async function wn(r,e,t,n,s,o,i,a,c){switch(r.tier){case"claude-code":if(r.persistentProcess){let d=await Es(r,e,s,o,i,a);if(d!==null)return d}return n?Ms(r,e,n,s,o,i,a):As(r,e,s,o,a);case"codex-cli":return n?Ps(r,e,n,s,o,i):Rs(r,e,s,o);case"opencode":return Ds(r,e,n,s,o,i,a,c);case"sdk":{let d=r.provider||"claude",u=t[d]?.apiKey;return u?Os(r,e,u,s):{content:"",error:`No API key for provider "${d}". Configure providers.${d}.apiKey`}}case"orchestrator":{let d=r.provider||"claude-code",u=t[d],l=u?.apiKey;return _s(r,e,l,s,n,{thinking:u?.thinking},c,a,i)}default:return{content:"",error:`Unknown tier: ${r.tier}`}}}import{readFileSync as fe,writeFileSync as Tn,mkdirSync as Ns,existsSync as ft,readdirSync as ht}from"fs";import{resolve as he}from"path";var mt=12e3,Ie=30,Fs=720,js=40,Ls=18e4,Hs="[Compacted conversation summary",Us=7*864e5,Ws=[/\bearlier\b/i,/\bbefore\b/i,/\bjust said\b/i,/\btold (?:me|you|us|him|her|them)\b/i,/\bmention(?:ed|ing)?\b/i,/\bask(?:ed)? (?:me|you|him|her|them|about)\b/i,/\bping(?:ed)?\b/i,/\bdm\b/i,/\bdirect message\b/i,/\bother (?:chat|group|conversation|thread)\b/i,/\bthat (?:chat|group|conversation|thread)\b/i,/\bsame (?:issue|thread|conversation)\b/i,/\bcontinuing\b/i,/@\w{2,}_?(?:bot|agent)\b/i,/قلت/,/قال(?:لك|لي|له|لها|لنا)?/,/قبل/,/الحين/,/الثاني/,/المجموعة/];function Ks(r){return r?Ws.some(e=>e.test(r)):!1}var Bs=[{re:/\byesterday\b/i,days:2},{re:/\bأمس\b/,days:2},{re:/\bcouple (?:of )?days\b/i,days:4},{re:/\bfew days\b/i,days:4},{re:/\blast week\b/i,days:8},{re:/\bالأسبوع الماضي\b/,days:8},{re:/\bweek ago\b/i,days:8},{re:/\bremember\b/i,days:3},{re:/\bpreviously\b/i,days:3},{re:/\bwe (?:discussed|talked|agreed|decided)\b/i,days:3},{re:/\bas (?:i|we) (?:said|told|mentioned)\b/i,days:3},{re:/\bcontinue from\b/i,days:3},{re:/\bتذكر\b/,days:3}];function In(r){if(!r)return null;let e=0;for(let t of Bs)t.re.test(r)&&(e=Math.max(e,t.days));return e>0?{lookbackDays:e}:null}function kn(r,e,t,n){if(r.length===0)return!1;let s=r[r.length-1];return s.role===e&&(s.name??"")===t&&s.content===n}function Gs(r){let e=r.slice(11,16),t=e.slice(0,2),n=parseInt(e.slice(3,5),10);if(Number.isNaN(n))return e;let s=Math.floor(n/15)*15;return`${t}:${s.toString().padStart(2,"0")}`}var qe=class{sessionsDir;cache=new Map;staleMinutes;maxTurnsPerSession;tierTwoThresholdTokens;adapterResolver;seedingPromises=new Map;constructor(e=process.cwd(),t={}){this.sessionsDir=he(e,".agentx/sessions"),ft(this.sessionsDir)||Ns(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??Fs),this.maxTurnsPerSession=Math.max(2,t.maxTurnsPerSession??js),this.tierTwoThresholdTokens=Math.max(5e4,t.tierTwoThresholdTokens??Ls)}setAdapterResolver(e){this.adapterResolver=e}async seedIfEmpty(e,t,n){if(!this.adapterResolver)return;let s=this.sessionKey(e,t,n),o=this.seedingPromises.get(s);if(o)return o;let i=this.getSession(e,t,n);if(i.messages.length>0)return;let a=this.adapterResolver(t);if(!a?.seedHistory)return;let c=(async()=>{try{let d=await a.seedHistory(n,{maxMessages:Ie,maxChars:mt});d.length>0&&this.appendSeededMessages(i,d)}catch{}})();this.seedingPromises.set(s,c);try{await c}finally{this.seedingPromises.delete(s)}}appendSeededMessages(e,t){if(t.length===0)return;let n=new Set;for(let o of e.messages)o.externalId&&n.add(o.externalId);let s=0;for(let o of t)o.externalId&&n.has(o.externalId)||(e.messages.push({role:o.role,name:o.name,content:o.content,timestamp:o.timestamp,seeded:!0,externalId:o.externalId}),s++);s!==0&&(this.trim(e),e.updatedAt=new Date().toISOString(),this.save(e))}sessionKey(e,t,n){let s=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${s}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return he(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let s=this.sessionKey(e,t,n);if(this.cache.has(s))return this.cache.get(s);let o=this.sessionFile(s);if(ft(o))try{let d=JSON.parse(fe(o,"utf-8"));return this.cache.set(s,d),d}catch{}let i=this.loadPreviousDaySession(e,t,n),a=new Date().toISOString().slice(0,10),c={id:s,agentId:e,channel:t,chatId:n,day:a,messages:[],createdAt:new Date().toISOString(),updatedAt:i?.updatedAt??new Date().toISOString(),claudeSessionId:i?.claudeSessionId,codexSessionId:i?.codexSessionId,turnCount:i?.turnCount,lastTurnInputTokens:i?.lastTurnInputTokens,lastTurnContextTokens:i?.lastTurnContextTokens};return this.cache.set(s,c),this.save(c),c}loadPreviousDaySession(e,t,n){let s=new Date(Date.now()-864e5).toISOString().slice(0,10),o=`${e}:${t}:${n}:${s}`,i=this.sessionFile(o);if(!ft(i))return null;try{return JSON.parse(fe(i,"utf-8"))}catch{return null}}addUserMessage(e,t,n,s,o){let i=this.getSession(e,t,n);kn(i.messages,"user",s,o)||(i.messages.push({role:"user",name:s,content:o,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i))}removeLastUserMessageIfMatches(e,t,n,s){let o=this.getSession(e,t,n),i=o.messages[o.messages.length-1];return!i||i.role!=="user"||(i.content||"").trim()!==(s||"").trim()?!1:(o.messages.pop(),o.updatedAt=new Date().toISOString(),this.save(o),!0)}addAgentMessage(e,t,n,s){let o=this.getSession(e,t,n);kn(o.messages,"agent",e,s)||(o.messages.push({role:"agent",name:e,content:s,timestamp:new Date().toISOString()}),this.trim(o),o.updatedAt=new Date().toISOString(),this.save(o))}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.claudeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getCodexSessionId(e,t,n){return this.getSession(e,t,n).codexSessionId}setCodexSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.codexSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}getOpenCodeSessionId(e,t,n){return this.getSession(e,t,n).opencodeSessionId}setOpenCodeSessionId(e,t,n,s){let o=this.getSession(e,t,n);o.opencodeSessionId=s,o.updatedAt=new Date().toISOString(),this.save(o)}buildHistoryContext(e,t,n,s={}){let o=this.getSession(e,t,n);if(o.messages.length===0)return"";let i=Math.max(1,s.maxMessages??Ie),a=Math.max(200,s.maxChars??mt),c=[],d=0;for(let g=o.messages.length-1;g>=0&&c.length<i;g--){let m=o.messages[g];if(d+=m.content.length,c.push(m),d>=a)break}c.reverse();let u=[`[Conversation history for today (${o.day})]`],l="";for(let g of c){let m=Gs(g.timestamp);m!==l&&(u.push(`\u2014 ${m} \u2014`),l=m);let b=g.name||(g.role==="user"?"User":"Agent");u.push(`${b}: ${g.content}`)}return u.push("[End of history \u2014 respond to the latest message above]"),u.push(""),u.join(`
|
|
23
|
-
`)}recallTurns(e){let t=Math.min(Math.max(e.limit??10,1),100),n=new Date;n.setUTCHours(0,0,0,0);let s=typeof e.lookbackDays=="number"&&e.lookbackDays>0?new Date(Date.now()-e.lookbackDays*24*60*60*1e3).toISOString():n.toISOString(),o=e.after??s,i=e.before??new Date(Date.now()+1e3).toISOString(),a=e.agentId.replace(/[^a-zA-Z0-9_:-]/g,"_"),c;try{c=ht(this.sessionsDir).filter(C=>C.startsWith(`${a}:`)&&C.endsWith(".json"))}catch{return{turns:[],oldestTs:null,hasMore:!1,totalScanned:0}}let d=o.slice(0,10),u=i.slice(0,10),l=/:(\d{4}-\d{2}-\d{2})\.json$/,g=c.filter(C=>{let T=C.match(l);if(!T)return!1;let $=T[1];return $>=d&&$<=u}),m=[],b=0,w=e.query?.toLowerCase(),x=e.participants?.length?new Set(e.participants):void 0;for(let C of g){let T;try{T=JSON.parse(fe(he(this.sessionsDir,C),"utf-8"))}catch{continue}if(T.agentId===e.agentId&&!(e.channel&&T.channel!==e.channel)&&!(e.chatId&&T.chatId!==e.chatId))for(let $ of T.messages)b++,!(!$.timestamp||$.timestamp<o||$.timestamp>=i)&&(x&&$.role==="user"&&!x.has($.name??"")||w&&!$.content.toLowerCase().includes(w)||m.push({ts:$.timestamp,role:$.role,senderName:$.name??"",content:$.content,channel:T.channel,chatId:T.chatId,day:T.day,sessionFile:C}))}m.sort((C,T)=>T.ts.localeCompare(C.ts));let p=m.slice(0,t),f=p.length>0?p[p.length-1].ts:null,D=m.length>t;return{turns:p,oldestTs:f,hasMore:D,totalScanned:b}}recentByChatId(e){let t=Math.min(Math.max(e.limit??Ie,1),200),n=e.sinceISO??new Date(Date.now()-24*60*60*1e3).toISOString(),s=n.slice(0,10),o;try{o=ht(this.sessionsDir).filter(l=>l.endsWith(".json"))}catch{return[]}let i=`:${e.channel}:${e.chatId}:`,a=o.filter(l=>{if(!l.includes(i))return!1;let g=l.match(/:(\d{4}-\d{2}-\d{2})\.json$/);return g?g[1]>=s:!1}),c=[];for(let l of a){let g;try{g=JSON.parse(fe(he(this.sessionsDir,l),"utf-8"))}catch{continue}if(!(g.channel!==e.channel||g.chatId!==e.chatId))for(let m of g.messages)!m.timestamp||m.timestamp<n||c.push({ts:m.timestamp,role:m.role,senderName:m.name??"",content:m.content,agentId:g.agentId,sessionFile:l})}let d=new Set,u=[];for(let l of c){let g=`${l.ts}|${l.role}|${l.senderName}|${l.content}`;d.has(g)||(d.add(g),u.push(l))}return u.sort((l,g)=>l.ts.localeCompare(g.ts)),u.slice(-t)}isSessionStale(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:Date.now()-new Date(s.updatedAt).getTime()>this.staleMinutes*60*1e3}getCrossSessionSummary(e,t,n,s){if(s!==void 0&&s!==""&&!Ks(s))return"";let o=new Date().toISOString().slice(0,10),i=this.sessionKey(e,t,n);try{let a=ht(this.sessionsDir).filter(d=>d.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&d.includes(o)&&d.endsWith(".json")),c=[];for(let d of a)try{let u=JSON.parse(fe(he(this.sessionsDir,d),"utf-8"));if(u.id===i||u.messages.length===0)continue;let l=u.messages.slice(-4),m=!u.chatId.startsWith("-")&&/^\d+$/.test(u.chatId)?"DM":u.chatId,b=l.map(w=>` [${w.timestamp.slice(11,16)}] ${w.name||w.role}: ${w.content.slice(0,200)}`);c.push(`From ${m} (${u.channel}):
|
|
24
|
-
${b.join(`
|
|
25
|
-
`)}`)}catch{}return c.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...c,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
26
|
-
`)}catch{return""}}async compactIfNeeded(e,t,n,s){let o=this.getSession(e,t,n),{needsCompaction:i,compactSession:a,applyCompaction:c}=await import("./compaction-NWEMOSHA.js");if(!i(o.messages))return{compacted:!1};let d=await a(o.messages,e,s);return d.compactedCount===0?{compacted:!1}:(o.messages=c(o.messages,d),o.updatedAt=new Date().toISOString(),this.save(o),{compacted:!0,qualityScore:d.qualityScore,lostEntities:d.lostEntities,drift:d.drift})}hasCompaction(e,t,n){let s=this.getSession(e,t,n);return s.messages.length>0&&s.messages[0].content.startsWith(Hs)}clearClaudeSessionId(e,t,n){let s=this.getSession(e,t,n);delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}clearSession(e,t,n){let s=this.getSession(e,t,n);s.messages=[],delete s.claudeSessionId,delete s.codexSessionId,delete s.opencodeSessionId,delete s.turnCount,delete s.lastTurnInputTokens,delete s.lastTurnContextTokens,s.updatedAt=new Date().toISOString(),this.save(s)}shouldRotateByTurns(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.turnCount??0)>=this.maxTurnsPerSession}shouldRotateByTierTwo(e,t,n){let s=this.getSession(e,t,n);return!s.claudeSessionId&&!s.codexSessionId&&!s.opencodeSessionId?!1:(s.lastTurnContextTokens??s.lastTurnInputTokens??0)>=this.tierTwoThresholdTokens}recordTurnUsage(e,t,n,s,o){let i=this.getSession(e,t,n);i.turnCount=(i.turnCount??0)+1,i.lastTurnInputTokens=(s.inputTokens||0)+(s.cacheReadTokens||0)+(s.cacheCreateTokens||0),i.lastTurnContextTokens=o,i.updatedAt=new Date().toISOString(),this.save(i)}rotationMemoFile(){return he(this.sessionsDir,"_rotation-memos.json")}readRotationMemos(){try{let e=JSON.parse(fe(this.rotationMemoFile(),"utf-8"));return e&&typeof e=="object"?e:{}}catch{return{}}}setRotationMemo(e,t,n,s,o){let i=this.readRotationMemos();i[`${e}:${t}:${n}`]={memo:s,reason:o,capturedAt:new Date().toISOString()},Tn(this.rotationMemoFile(),JSON.stringify(i,null,2))}getRotationMemo(e,t,n){let s=this.readRotationMemos()[`${e}:${t}:${n}`];if(!s?.memo)return null;let o=Date.now()-Date.parse(s.capturedAt);return!Number.isFinite(o)||o>Us?null:s}getTurnCount(e,t,n){return this.getSession(e,t,n).turnCount??0}getLastTurnInputTokens(e,t,n){return this.getSession(e,t,n).lastTurnInputTokens??0}getLastTurnContextTokens(e,t,n){let s=this.getSession(e,t,n);return s.lastTurnContextTokens??s.lastTurnInputTokens??0}getMaxTurnsPerSession(){return this.maxTurnsPerSession}getTierTwoThresholdTokens(){return this.tierTwoThresholdTokens}trim(e){let t=e.messages.length;e.messages.length>Ie&&(e.messages=e.messages.slice(-Ie));let n=e.messages.reduce((o,i)=>o+i.content.length,0);for(;n>mt&&e.messages.length>2;){let o=e.messages.shift();n-=o.content.length}let s=t-e.messages.length;s>0&&ie.cat("context",`[${e.agentId}] ${e.channel}:${e.chatId} trim dropped ${s} message(s): ${t} -> ${e.messages.length} (${n}c)`)}save(e){try{let t=this.sessionFile(e.id);Tn(t,JSON.stringify(e,null,2))}catch{}}};var Je=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],s=t-36e5,o=n.filter(c=>c>s),i=t-6e4,a=o.filter(c=>c>i);if(a.length>=this.maxPerMinute){let c=a[0],d=Math.max(50,c+6e4-t);return{allowed:!1,reason:`Rate limit: ${a.length}/${this.maxPerMinute} per minute`,waitMs:d}}if(o.length>=this.maxPerHour){let c=o[0],d=Math.max(1e3,c+36e5-t);return{allowed:!1,reason:`Rate limit: ${o.length}/${this.maxPerHour} per hour`,waitMs:d}}return o.push(t),this.windows.set(e,o),{allowed:!0}}async acquire(e,t={}){let n=t.maxWaitMs??3e5,s=Date.now()+n,o=!0;for(;;){let i=this.check(e);if(i.allowed)return{ok:!0};if(Date.now()>=s)return{ok:!1,reason:`${i.reason} (waited ${Math.round(n/1e3)}s, giving up)`};o&&(o=!1,t.onWait?.(i.reason,i.waitMs));let a=s-Date.now(),c=Math.min(i.waitMs??1e3,a,5e3);await new Promise(d=>setTimeout(d,c))}}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(s=>s>t-6e4).length,lastHour:n.filter(s=>s>t-36e5).length}}};import{readFileSync as Se,writeFileSync as Sn,appendFileSync as qs,existsSync as me,mkdirSync as Js}from"fs";import{resolve as ye}from"path";var vn={"claude-opus-4-6":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus-4-5":{input:5,output:25,cacheRead:.5,cacheCreate:6.25},"claude-opus":{input:15,output:75,cacheRead:1.5,cacheCreate:18.75},"claude-sonnet":{input:3,output:15,cacheRead:.3,cacheCreate:3.75},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheCreate:1.25}},$n=2e5,zs=1.5;function Qs(r){let e=r.toLowerCase();return e.includes("opus")?e.includes("4-6")||e.includes("4.6")||e.includes("opus-4-6")?"claude-opus-4-6":e.includes("4-5")||e.includes("4.5")||e.includes("opus-4-5")?"claude-opus-4-5":"claude-opus":e.includes("haiku")?"claude-haiku":"claude-sonnet"}function An(r){return r.inputTokens+r.cacheReadTokens+r.cacheCreateTokens>$n?{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:r.inputTokens,tier2OutputTokens:r.outputTokens,tier2CacheReadTokens:r.cacheReadTokens,tier2CacheCreateTokens:r.cacheCreateTokens}:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens,cacheCreateTokens:r.cacheCreateTokens,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0}}var Cn=500,Xs=".agentx/pricing/custom.json",be=class{dir;cache=null;pricing;constructor(e=ye(process.cwd(),".agentx/usage")){this.dir=e,Js(this.dir,{recursive:!0}),this.pricing=Ys()}getPricing(){return this.pricing}static calculateCost(e,t,n=vn){let s=Qs(t||e.model||"claude-sonnet"),o=n[s]||n["claude-sonnet"],i=e.tier2InputTokens||0,a=e.tier2OutputTokens||0,c=e.tier2CacheReadTokens||0,d=e.tier2CacheCreateTokens||0,u=(e.inputTokens||0)/1e6*o.input+(e.outputTokens||0)/1e6*o.output+(e.cacheReadTokens||0)/1e6*o.cacheRead+(e.cacheCreateTokens||0)/1e6*o.cacheCreate,l=i/1e6*o.input+a/1e6*o.output+c/1e6*o.cacheRead+d/1e6*o.cacheCreate;return u+l*zs}cost(e,t){return be.calculateCost(e,t,this.pricing)}record(e,t,n,s,o,i,a,c,d){let u=this.today(),l=u.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0,byChannel:{},sessionKeys:[]};l.tasks++,l.totalDuration+=t,a&&(l.model=a);let g=0,m=0,b=0,w=0,x=0,p=0,f=0,D=0;n?n.inputTokens+n.cacheReadTokens+n.cacheCreateTokens>$n?(x=n.inputTokens,p=n.outputTokens,f=n.cacheReadTokens,D=n.cacheCreateTokens):(g=n.inputTokens,m=n.outputTokens,b=n.cacheReadTokens,w=n.cacheCreateTokens):s!==void 0&&o!==void 0&&(g=Math.ceil(s/4),m=Math.ceil(o/4)),l.inputTokens+=g,l.outputTokens+=m,l.cacheReadTokens+=b,l.cacheCreateTokens+=w,l.tier2InputTokens=(l.tier2InputTokens||0)+x,l.tier2OutputTokens=(l.tier2OutputTokens||0)+p,l.tier2CacheReadTokens=(l.tier2CacheReadTokens||0)+f,l.tier2CacheCreateTokens=(l.tier2CacheCreateTokens||0)+D,i&&l.errors++,l.byChannel||(l.byChannel={});let C=(c||"other").toLowerCase(),T=l.byChannel[C]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,tier2InputTokens:0,tier2OutputTokens:0,tier2CacheReadTokens:0,tier2CacheCreateTokens:0,totalDuration:0,errors:0};T.tasks++,T.totalDuration+=t,T.inputTokens+=g,T.outputTokens+=m,T.cacheReadTokens+=b,T.cacheCreateTokens+=w,T.tier2InputTokens+=x,T.tier2OutputTokens+=p,T.tier2CacheReadTokens+=f,T.tier2CacheCreateTokens+=D,i&&T.errors++,l.byChannel[C]=T,d&&(l.sessionKeys||(l.sessionKeys=[]),l.sessionKeys.includes(d)||(l.sessionKeys.push(d),l.sessionKeys.length>Cn&&l.sessionKeys.splice(0,l.sessionKeys.length-Cn))),u.agents[e]=l,this.save(u)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(me(t))try{return this.cache=JSON.parse(Se(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!me(t))return null;try{return JSON.parse(Se(t,"utf-8"))}catch{return null}}generateDailyReport(e){let t=e||new Date().toISOString().slice(0,10),n=this.getDate(t);if(!n)return null;let s=0,o=0,i=0,a=0,c=0,d=0,u="",l=0,g={},m={},b={};for(let[w,x]of Object.entries(n.agents)){let p=this.cost(x);g[w]=p,s+=x.tasks,o+=(x.inputTokens||0)+(x.tier2InputTokens||0),i+=(x.outputTokens||0)+(x.tier2OutputTokens||0),a+=(x.cacheReadTokens||0)+(x.tier2CacheReadTokens||0),c+=(x.cacheCreateTokens||0)+(x.tier2CacheCreateTokens||0),d+=p,p>l&&(l=p,u=w);let f=x.sessionKeys?.length||0;m[w]={sessions:f,avgTasksPerSession:f>0?x.tasks/f:x.tasks};for(let[D,C]of Object.entries(x.byChannel||{})){let T=this.cost(C,x.model);b[D]=(b[D]||0)+T}}return{date:t,totalTasks:s,totalInput:o,totalOutput:i,totalCacheRead:a,totalCacheCreate:c,totalCost:d,topAgent:u,topCost:l,agentCosts:g,agentSessionStats:m,byChannel:b}}appendToTokenCosts(e,t){let n=t||ye(process.cwd(),".agentx/TOKEN_COSTS.md"),s=d=>d<.01?d.toFixed(4):d.toFixed(2),o=d=>d>=1e6?`${(d/1e6).toFixed(1)}M`:d>=1e3?`${(d/1e3).toFixed(0)}K`:String(d),i=Object.entries(e.agentCosts).sort(([,d],[,u])=>u-d).map(([d,u])=>{let l=e.agentSessionStats[d],g=l&&l.sessions>0?` (${l.sessions}s, ${l.avgTasksPerSession.toFixed(1)}t/s)`:"";return`${d}: $${s(u)}${g}`}).join(", "),a=Object.entries(e.byChannel).sort(([,d],[,u])=>u-d).map(([d,u])=>`${d}: $${s(u)}`).join(", "),c=`| ${e.date} | ${e.totalTasks} | ${o(e.totalInput)} | ${o(e.totalOutput)} | ${o(e.totalCacheRead)} | ${o(e.totalCacheCreate)} | $${s(e.totalCost)} | ${i} | ${a} |`;me(n)?qs(n,c+`
|
|
27
|
-
`):Sn(n,`# Token Costs
|
|
28
|
-
|
|
29
|
-
Daily token cost tracking. Auto-appended at midnight (Africa/Tunis).
|
|
30
|
-
Agent breakdown: \`agent: $cost (Ns, T.Tt/s)\` \u2014 sessions, tasks/session.
|
|
31
|
-
|
|
32
|
-
| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |
|
|
33
|
-
|------|-------|-------|--------|---------|---------|------|-----------|-------------|
|
|
34
|
-
`+c+`
|
|
35
|
-
`)}hasTokenCostsEntry(e,t){let n=t||ye(process.cwd(),".agentx/TOKEN_COSTS.md");if(!me(n))return!1;try{let s=Se(n,"utf-8");return new RegExp(`^\\|\\s*${e}\\s*\\|`,"m").test(s)}catch{return!1}}lastTokenCostsDate(e){let t=e||ye(process.cwd(),".agentx/TOKEN_COSTS.md");if(!me(t))return null;try{let s=Se(t,"utf-8").match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|/gm)??[];if(s.length===0)return null;let o=s.map(i=>i.match(/(\d{4}-\d{2}-\d{2})/)?.[1]).filter(i=>!!i);return o.sort(),o[o.length-1]??null}catch{return null}}catchUpTokenCosts(e,t={}){let n=t.maxDays??30,s=[],o=this.lastTokenCostsDate(t.filePath),i=[],a=new Date(`${e}T00:00:00Z`);for(let c=0;c<n;c++){let d=a.toISOString().slice(0,10);if(o&&d<=o)break;i.push(d),a.setUTCDate(a.getUTCDate()-1)}i.reverse();for(let c of i){if(this.hasTokenCostsEntry(c,t.filePath))continue;let d=this.generateDailyReport(c);!d||d.totalTasks===0||(this.appendToTokenCosts(d,t.filePath),s.push(c))}return s}summary(e=7){let t=0,n=0,s=0,o=0,i=0,a=0,c=0,d={},u={};for(let b=0;b<e;b++){let w=new Date(Date.now()-b*864e5).toISOString().slice(0,10),x=this.getDate(w);if(x)for(let[p,f]of Object.entries(x.agents)){let D=this.cost(f);t+=f.tasks;let C=(f.inputTokens||0)+(f.tier2InputTokens||0),T=(f.outputTokens||0)+(f.tier2OutputTokens||0),$=(f.cacheReadTokens||0)+(f.tier2CacheReadTokens||0),F=(f.cacheCreateTokens||0)+(f.tier2CacheCreateTokens||0);n+=C,s+=T,o+=$,i+=F,a+=f.errors,c+=D;let k=d[p]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0,cost:0,sessions:0};k.tasks+=f.tasks,k.input+=C,k.output+=T,k.cacheRead+=$,k.cacheCreate+=F,k.total=k.input+k.output+k.cacheRead+k.cacheCreate,k.totalDuration+=f.totalDuration,k.avgDuration=k.totalDuration/k.tasks,k.cost+=D,k.sessions+=f.sessionKeys?.length||0,f.model&&(k.model=f.model),d[p]=k;for(let[A,R]of Object.entries(f.byChannel||{})){let S=this.cost(R,f.model),I=u[A]||{tasks:0,cost:0};I.tasks+=R.tasks,I.cost+=S,u[A]=I}}}let l=n+s+o+i,g=o+i>0?o/(o+i):0,m={};for(let[b,w]of Object.entries(d))m[b]={sessions:w.sessions,avgTasksPerSession:w.sessions>0?w.tasks/w.sessions:w.tasks};return{totalTasks:t,totalTokens:l,totalInput:n,totalOutput:s,totalCacheRead:o,totalCacheCreate:i,cacheHitRatio:g,totalErrors:a,totalCost:c,byAgent:d,byChannel:u,sessionStats:m}}filePath(e){return ye(this.dir,`${e}.json`)}save(e){try{Sn(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};function Ys(){let r=JSON.parse(JSON.stringify(vn));try{let e=ye(process.cwd(),Xs);if(!me(e))return r;let t=JSON.parse(Se(e,"utf-8"));for(let[n,s]of Object.entries(t))r[n]||(r[n]={input:0,output:0,cacheRead:0,cacheCreate:0}),Object.assign(r[n],s)}catch{}return r}var Zs={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,references:500,intent:200,artifacts:500,procedures:600,memory:600,history:1200,"cross-chat":800,wiki:1e3}},Mn=4;function Rn(r,e=Zs){let t=Vs(r,e);t.sort((i,a)=>i.priority-a.priority);let n=[],s=0,o=e.totalBudget*Mn;for(let i of t){if(!i.content)continue;let a=i.maxTokens*Mn,c=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(s+c.length>o){let d=o-s;d>100&&n.push(c.slice(0,d)+"...");break}n.push(c),s+=c.length}return n.join(`
|
|
36
|
-
|
|
37
|
-
`)}function Vs(r,e){let t=(i,a)=>e.layerBudgets?.[i]??a,n=[];if(n.push(er(r,t("channel",200))),n.push(tr(r,t("scope",200))),r.landscape&&n.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:r.landscape,tags:["landscape","world-model"]}),r.systemPrompt&&n.push({name:"identity",priority:4,maxTokens:t("identity",200),content:r.systemPrompt.split(`
|
|
38
|
-
`)[0],tags:["identity",r.agentId]}),r.bootstrapContext&&n.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:r.bootstrapContext,tags:["bootstrap","identity","personality"]}),r.references&&n.push({name:"references",priority:4.7,maxTokens:t("references",500),content:r.references,tags:["references","verified","deterministic"]}),r.intent&&r.intent.path.length>0){let i=[`[Intent path: ${r.intent.pathLabel}${r.intent.status==="pending"?" (pending approval)":""}]`],a=r.intent.path[r.intent.path.length-1],c=r.intent.axes?.[a];if(c&&Object.keys(c).length){let d=Object.entries(c).map(([u,l])=>` ${u}: ${l}`).join(`
|
|
39
|
-
`);i.push(d)}r.intent.leaf?.input&&i.push(` input: ${r.intent.leaf.input}`),n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:i.join(`
|
|
40
|
-
`),tags:["intent",...r.intent.path]})}else{let i=nr(r.message);i.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${i.join(", ")}]`,tags:i})}let s=[];r.replyToText&&s.push(`[Replying to]: ${r.replyToText.slice(0,300)}`),r.mediaPath&&(s.push(`[Attached file: ${r.mediaPath}]`),s.push(`[File type: ${r.mediaType||"unknown"}]`),r.mediaType?.startsWith("image/")?s.push("Please view this image and respond to it."):r.mediaType?.startsWith("audio/")&&s.push("Please transcribe this audio and respond.")),r.issueMR&&s.push(`[${r.issueMR.type} #${r.issueMR.iid}: ${r.issueMR.title}]`),s.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:s.join(`
|
|
41
|
-
`),tags:["artifacts",...r.mediaType?["media"]:[]]}),r.skillInjection&&n.push({name:"skills",priority:6.2,maxTokens:t("skills",2e3),content:r.skillInjection,tags:["skills","auto-inject"]}),r.patternContext&&n.push({name:"patterns",priority:6.3,maxTokens:t("patterns",400),content:r.patternContext,tags:["patterns","behavioral","self-improving"]}),r.procedureContext&&n.push({name:"procedures",priority:6.4,maxTokens:t("procedures",600),content:r.procedureContext,tags:["procedures","sop"]}),r.memoryContext&&n.push({name:"memory",priority:6.5,maxTokens:t("memory",600),content:r.memoryContext,tags:["memory","persistent"]});let o=r.groupHistory||r.sessionHistory;if(o&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:o,tags:["history","conversation"]}),r.crossChatContext&&n.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:r.crossChatContext,tags:["history","cross-chat"]}),r.longMemoryRecall&&n.push({name:"long-memory",priority:7,maxTokens:t("long-memory",1500),content:r.longMemoryRecall,tags:["history","long-memory"]}),r.handoverNote){let i=[`[Handover] You are taking over this conversation from ${r.handoverNote.fromAgent}.`];r.handoverNote.summary&&i.push(`Operator summary: ${r.handoverNote.summary}`),i.push(`Handover time: ${r.handoverNote.at}`),n.push({name:"handover",priority:7.5,maxTokens:t("handover",400),content:i.join(`
|
|
42
|
-
`),tags:["handover",r.handoverNote.fromAgent]})}return r.rotationMemo&&n.push({name:"rotation-memo",priority:7.6,maxTokens:t("rotation-memo",800),content:[`[Continuity memo \u2014 your previous session for this chat ended (${r.rotationMemo.reason}, ${r.rotationMemo.capturedAt}). Carry on from these facts; do not claim you lack prior context:]`,r.rotationMemo.memo].join(`
|
|
43
|
-
`),tags:["continuity","rotation-memo"]}),r.wikiContext&&n.push({name:"wiki",priority:8,maxTokens:t("wiki",1e3),content:r.wikiContext,tags:["wiki","knowledge"]}),n}function er(r,e){let t=[`Channel: ${r.channel}`];r.chatId&&t.push(`Chat ID: ${r.chatId} (use this verbatim in /recall, /send)`);let n=[],s=[r.channel];switch(r.channel){case"telegram":r.agentHandle&&t.push(`Your handle: ${r.agentHandle}`),t.push(`From: ${r.sender}`),r.senderId&&t.push(`Telegram user ID: ${r.senderId}`),r.senderUsername&&t.push(`Username: @${r.senderUsername}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),n.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${r.sender}`),n.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only"),n.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${r.sender}`),n.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),n.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),n.push("Never narrate what you are about to do \u2014 just do it and report the result"),s.push("code-review");break;case"discord":t.push(`From: ${r.sender}`),n.push("Use Discord markdown for formatting"),n.push("Be brief \u2014 2-4 sentences for the main point");break;default:r.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),s.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(o=>`- ${o}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
44
|
-
`),tags:s,rules:n}}function tr(r,e){let t=[],n=[];if(r.channelScope==="group"&&r.groupName?(t.push(`Group: ${r.groupName}`),n.push("group",r.groupName)):r.channelScope==="project"&&r.projectPath?(t.push(`Project: ${r.projectPath}`),n.push("project",r.projectPath)):r.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),r.channelMeta){let s=r.channelMeta;if(s.agents?.length&&(t.push(`[Verified bots in this chat: ${s.agents.map(o=>o.handle||o.name||o.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),s.project&&t.push(`Project: ${s.project}`),s.issue&&t.push(`${s.issue.type} #${s.issue.iid}${s.issue.title?`: ${s.issue.title}`:""}`),s.facts?.length)for(let o of s.facts)t.push(`\u2022 ${o}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
45
|
-
`),tags:n}}function nr(r){let e=[],t=r.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}import{readFileSync as sr,writeFileSync as Pn,appendFileSync as rr,mkdirSync as or,existsSync as Dn}from"fs";import{resolve as yt}from"path";var On=200,ir=7,ze=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=yt(e,".agentx/memory"),Dn(this.memoryDir)||or(this.memoryDir,{recursive:!0})}filePath(e){return yt(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};rr(this.filePath(e),JSON.stringify(n)+`
|
|
46
|
-
`)}getAll(e){let t=this.filePath(e);if(!Dn(t))return[];try{return sr(t,"utf-8").split(`
|
|
47
|
-
`).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}findRelevant(e,t,n=8){let s=this.getAll(t);if(s.length===0)return[];let o=s.map(m=>`${m.keywords.join(" ")} ${m.content}`),i=yt(this.memoryDir,`${t}_bm25_cache.json`),a=Fe(o,i),c=Ne(e,a),d=new Map(c.map(m=>[m.docIndex,m.score])),l=s.map((m,b)=>{let w=d.get(b)??0;return m.category==="secret"&&(w+=2),m.category==="commitment"&&(w+=1),{memory:m,score:w}}).filter(m=>m.score>0);if(l.length===0)return s.slice(-n);let g=l.sort((m,b)=>b.score-m.score).slice(0,n).map(m=>m.memory);if(g.length>0)try{this.recordAccess(t,g.map(m=>m.id))}catch{}return g}buildContext(e){if(e.length===0)return"";let t=["[Agent Memory \u2014 persistent facts from past conversations]"],n=t[0].length;for(let s of e){let i=!s.source.chatId.startsWith("-")&&/^\d+$/.test(s.source.chatId)?"DM":s.source.chatId,a=`- [${s.category}] ${s.content} (${i}, ${s.source.date})`;if(n+a.length>2400)break;t.push(a),n+=a.length}return t.push("[End Memory]"),t.join(`
|
|
48
|
-
`)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),s=new Set(t),o=!1;for(let i of n)if(s.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let a=i.intervalDays||1;i.intervalDays=Math.min(a*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),o=!0}o&&Pn(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
49
|
-
`)+`
|
|
50
|
-
`)}getDueForReview(e,t=5){let n=this.getAll(e),s=Date.now();return n.filter(o=>o.category==="task-state"?!1:o.nextReview?new Date(o.nextReview).getTime()<=s:!0).sort((o,i)=>!o.nextReview&&i.nextReview?-1:o.nextReview&&!i.nextReview?1:o.nextReview&&i.nextReview?new Date(o.nextReview).getTime()-new Date(i.nextReview).getTime():(o.accessCount||0)-(i.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let n=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let s of t){let o=Math.round((Date.now()-new Date(s.createdAt).getTime())/864e5);n.push(`- [${s.category}] ${s.content} (${o}d old, accessed ${s.accessCount||0}x)`)}return n.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),n.join(`
|
|
51
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),o=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return n.some(i=>{let a=i.content.toLowerCase();return o.filter(d=>a.includes(d)).length>=o.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let n=Date.now(),s=ir*24*60*60*1e3;t=t.filter(i=>i.category==="task-state"&&i.expiresAt?new Date(i.expiresAt).getTime()>n:i.category==="task-state"&&!i.expiresAt?n-new Date(i.createdAt).getTime()<s:!0),t.length>On&&(t=t.slice(-On));let o=this.filePath(e);Pn(o,t.map(i=>JSON.stringify(i)).join(`
|
|
52
|
-
`)+`
|
|
53
|
-
`)}};import{existsSync as Ce,mkdirSync as ar,readdirSync as cr,readFileSync as dr,unlinkSync as bt,writeFileSync as Qe}from"fs";import{resolve as te}from"path";var ce=["user","feedback","project","reference"],Xe=class{baseDir;constructor(e={}){let t=e.baseDir??te(process.cwd(),".agentx");this.baseDir=te(t,"agent-memory")}dirFor(e){let t=wt(e),n=te(this.baseDir,t);return ar(n,{recursive:!0}),n}fileFor(e,t,n){return te(this.dirFor(e),`${t}_${wt(n)}.md`)}indexPath(e){return te(this.dirFor(e),"MEMORY.md")}save(e){if(!ce.includes(e.type))throw new Error(`invalid memory type: ${e.type}`);if(!e.name.trim())throw new Error("memory name is required");if(!e.description.trim())throw new Error("memory description is required");let t=this.fileFor(e.agentId,e.type,e.name),n=new Date().toISOString(),s=n,o=ve(t);if(o){let a=xt(o);a&&(s=a.createdAt)}let i={name:wt(e.name),type:e.type,description:e.description.trim(),body:e.body.trimEnd(),createdAt:s,updatedAt:n};return Qe(t,ur(i)),this.rewriteIndex(e.agentId),i}get(e,t){for(let n of ce){let s=this.fileFor(e,n,t);if(!Ce(s))continue;let o=xt(ve(s)??"");if(o)return o}return null}list(e){let t=this.dirFor(e);if(!Ce(t))return[];let n=[];for(let s of cr(t,{withFileTypes:!0})){if(!s.isFile()||!s.name.endsWith(".md")||s.name==="MEMORY.md")continue;let o=xt(ve(te(t,s.name))??"");o&&n.push(o)}return n.sort((s,o)=>{let i=ce.indexOf(s.type),a=ce.indexOf(o.type);return i!==a?i-a:s.name.localeCompare(o.name)})}remove(e,t){let n=!1;for(let s of ce){let o=this.fileFor(e,s,t);Ce(o)&&(bt(o),n=!0)}return n&&this.rewriteIndex(e),n}indexMarkdown(e){let t=this.indexPath(e);return ve(t)??""}syncToWorkspace(e,t){if(!t)return;let n=this.indexMarkdown(e).trim(),s=te(t,".agentx-memory.md");n?Qe(s,n+`
|
|
54
|
-
`):Ce(s)&&bt(s);let o=te(t,"CLAUDE.md"),i="<!-- AGENTX-MEMORY-START \u2014 auto-managed by agentx; edit via `agentx memory` -->",a="<!-- AGENTX-MEMORY-END -->",c=n?`${i}
|
|
55
|
-
${n}
|
|
56
|
-
${a}`:"",d=ve(o)??"",u=d.indexOf(i),l=d.indexOf(a),g;if(u>=0&&l>u){let m=d.slice(0,u).replace(/\n+$/,""),b=d.slice(l+a.length).replace(/^\n+/,"");g=c?[m,c,b].filter(Boolean).join(`
|
|
57
|
-
|
|
58
|
-
`)+`
|
|
59
|
-
`:[m,b].filter(Boolean).join(`
|
|
60
|
-
|
|
61
|
-
`)+(m||b?`
|
|
62
|
-
`:"")}else if(c)g=d?d.replace(/\n+$/,"")+`
|
|
63
|
-
|
|
64
|
-
`+c+`
|
|
65
|
-
`:c+`
|
|
66
|
-
`;else return;Qe(o,g)}rewriteIndex(e){let t=this.list(e);if(t.length===0){let o=this.indexPath(e);Ce(o)&&bt(o);return}let n={user:[],feedback:[],project:[],reference:[]};for(let o of t)n[o.type].push(o);let s=[];s.push(`# Memory \u2014 ${e}`,""),s.push("This is the agent's experiential memory: user preferences,"),s.push("feedback, project-specific context, and external references."),s.push("Updated via `agentx memory` CLI or by the agent itself.");for(let o of ce){let i=n[o];if(i.length){s.push("",`## ${pr(o)}`,"");for(let a of i)s.push(`- **${a.name}** \u2014 ${a.description} _(updated ${a.updatedAt.slice(0,10)})_`)}}s.push(""),Qe(this.indexPath(e),s.join(`
|
|
67
|
-
`))}};function ur(r){return["---",`name: ${r.name}`,`description: ${lr(r.description)}`,`type: ${r.type}`,`created: ${r.createdAt}`,`updated: ${r.updatedAt}`,"---",""].join(`
|
|
68
|
-
`)+r.body+`
|
|
69
|
-
`}function xt(r){if(!r.startsWith(`---
|
|
70
|
-
`))return null;let e=r.indexOf(`
|
|
71
|
-
---
|
|
72
|
-
`,4);if(e<0)return null;let t=r.slice(4,e),n=r.slice(e+5).replace(/^\n+/,"").trimEnd(),s={};for(let o of t.split(`
|
|
73
|
-
`)){let i=o.indexOf(":");if(i<0)continue;let a=o.slice(0,i).trim(),c=gr(o.slice(i+1).trim());s[a]=c}return!s.name||!s.type||!s.description||!ce.includes(s.type)?null:{name:s.name,type:s.type,description:s.description,body:n,createdAt:s.created??"",updatedAt:s.updated??s.created??""}}function lr(r){return/[:#\n]/.test(r)?`"${r.replace(/"/g,'\\"')}"`:r}function gr(r){return r.startsWith('"')&&r.endsWith('"')&&r.length>=2?r.slice(1,-1).replace(/\\"/g,'"'):r}function wt(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"unnamed"}function pr(r){return r.charAt(0).toUpperCase()+r.slice(1)}function ve(r){try{return dr(r,"utf-8")}catch{return null}}var Ye=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,n){return`${e}:${t}:${n}`}getOrCreate(e,t,n){let s=this.key(e,t,n);return this.queues.has(s)||this.queues.set(s,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(s)}setMode(e,t,n,s){this.getOrCreate(e,t,n).mode=s}onFlush(e,t,n,s){this.getOrCreate(e,t,n).onFlush=s}isBusy(e,t,n){return this.getOrCreate(e,t,n).running}markRunning(e,t,n){let s=this.getOrCreate(e,t,n);return s.running?!1:(s.running=!0,!0)}enqueue(e,t,n,s){let o=this.getOrCreate(e,t,n);if(!o.running)return null;switch(o.mode){case"drop":return"drop";case"collect":case"followup":return o.pending.push(s),o.mode}}async markDone(e,t,n){let s=this.getOrCreate(e,t,n);if(s.running=!1,s.pending.length===0)return[];let o=[...s.pending];switch(s.pending=[],s.mode){case"collect":{let a={text:o.length===1?o[0].text:o.map(c=>`[${c.sender}, ${new Date(c.timestamp).toISOString().slice(11,16)}]: ${c.text}`).join(`
|
|
74
|
-
`),sender:o[o.length-1].sender,timestamp:Date.now(),channel:o[0].channel,chatId:o[0].chatId,originalContext:o[o.length-1].originalContext};return s.onFlush&&await s.onFlush([a]),[a]}case"followup":return s.onFlush&&await s.onFlush(o),o;case"drop":return[];default:return o}}pendingCount(e,t,n){return this.getOrCreate(e,t,n).pending.length}clear(e,t,n){let s=this.key(e,t,n);this.queues.delete(s)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as fr,writeFileSync as _n,appendFileSync as hr,mkdirSync as mr,existsSync as En}from"fs";import{resolve as Tt}from"path";var Nn=50,yr="claude-haiku-4-20250514",br=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
75
|
-
|
|
76
|
-
Extract patterns like:
|
|
77
|
-
- "When asked about X, the approach that works is Y"
|
|
78
|
-
- "User prefers Z style of communication"
|
|
79
|
-
- "For deployment tasks, always check A before doing B"
|
|
80
|
-
- "This codebase uses pattern X, so generate code following X"
|
|
81
|
-
|
|
82
|
-
SKIP:
|
|
83
|
-
- Factual information (names, dates, URLs)
|
|
84
|
-
- Routine task completions
|
|
85
|
-
- Greetings or small talk
|
|
86
|
-
|
|
87
|
-
Output a JSON array:
|
|
88
|
-
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
89
|
-
|
|
90
|
-
If nothing worth extracting, output: []`,Ze=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Tt(e,".agentx/patterns"),En(this.patternsDir)||mr(this.patternsDir,{recursive:!0})}filePath(e){return Tt(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!En(t))return[];try{return fr(t,"utf-8").split(`
|
|
91
|
-
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}addPattern(e,t){let n={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};hr(this.filePath(e),JSON.stringify(n)+`
|
|
92
|
-
`)}findRelevant(e,t,n=5){let s=this.getAll(t);if(s.length===0)return[];let o=s.map(u=>`${u.context} ${u.pattern}`),i=Tt(this.patternsDir,`${t}_bm25_cache.json`),a=Fe(o,i),d=Ne(e,a).slice(0,n).map(u=>s[u.docIndex]).filter(u=>u.confidence>=.3);return d.length>0&&this.recordAccess(t,d.map(u=>u.id)),d}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let n of e)t.push(`- ${n.pattern} (context: ${n.context}, confidence: ${Math.round(n.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
93
|
-
`)}hasSimilar(e,t){let n=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);return n.some(o=>{let i=o.pattern.toLowerCase();return s.filter(c=>i.includes(c)).length>=s.length*.6})}recordAccess(e,t){let n=this.getAll(e),s=new Set(t),o=!1;for(let i of n)s.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),o=!0);o&&_n(this.filePath(e),n.map(i=>JSON.stringify(i)).join(`
|
|
94
|
-
`)+`
|
|
95
|
-
`)}prune(e){let t=this.getAll(e);t.length<=Nn||(t.sort((n,s)=>s.confidence*s.accessCount-n.confidence*n.accessCount),t=t.slice(0,Nn),_n(this.filePath(e),t.map(n=>JSON.stringify(n)).join(`
|
|
96
|
-
`)+`
|
|
97
|
-
`))}};async function Fn(r,e,t,n,s){if(e.length<30&&t.length<100)return;let{createProvider:o}=await import("./providers-L27BJ5A6.js"),c=(await o("claude").generate([{role:"system",content:br},{role:"user",content:`User: ${e.slice(0,500)}
|
|
98
|
-
|
|
99
|
-
Agent: ${t.slice(0,1e3)}`}],{model:yr,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!c)return;let d=JSON.parse(c[0]);if(!(!Array.isArray(d)||d.length===0)){for(let u of d)s.hasSimilar(r,u.pattern)||s.addPattern(r,{agentId:r,pattern:u.pattern,context:u.context,confidence:u.confidence||.5,source:n});Math.random()<.05&&s.prune(r)}}import{EventEmitter as xr}from"events";var It=class{inner=new xr;constructor(){this.inner.setMaxListeners(50)}on(e,t){return this.inner.on(e,t),this}off(e,t){return this.inner.off(e,t),this}emit(e,t){return this.inner.emit(e,t)}listenerCount(e){return this.inner.listenerCount(e)}removeAllListeners(){return this.inner.removeAllListeners(),this}},kt;function ne(){return kt||(kt=new It),kt}var jn=["manual","notify","auto"];function wr(r){return typeof r=="string"&&jn.includes(r)}var St={claimTimeoutMs:9e4,staleSessionMs:15*6e4,maxDrainPerTurn:5,maxItemChars:4e3};var $e=class{sessions=new Map;items=new Map;waiters=new Map;opts;constructor(e={}){this.opts={...St,...e}}options(){return this.opts}register(e,t={}){let n=t.now??Date.now(),s=this.sessions.get(e);if(s)return s.lastSeenAt=n,t.cwd&&(s.cwd=t.cwd),t.model&&(s.model=t.model),s;let o={sessionId:e,cwd:t.cwd??"",agentIds:[],mode:"notify",lastSeenAt:n,registeredAt:n,model:t.model,drainedThisTurn:0};return this.sessions.set(e,o),o}touch(e,t=Date.now()){let n=this.sessions.get(e);return n&&(n.lastSeenAt=t),n}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()].sort((e,t)=>t.lastSeenAt-e.lastSeenAt)}bind(e,t,n){let s=this.sessions.get(e);if(s){for(let o of this.sessions.values())o.sessionId!==e&&(o.agentIds=o.agentIds.filter(i=>i!==t));return s.agentIds.includes(t)||s.agentIds.push(t),n&&(s.mode=n),s}}unbind(e,t){let n=this.sessions.get(e);if(n)return n.agentIds=t?n.agentIds.filter(s=>s!==t):[],n}setMode(e,t){let n=this.sessions.get(e);if(n)return n.mode=t,n}sessionFor(e){for(let t of this.sessions.values())if(t.agentIds.includes(e))return t}deregister(e,t=Date.now()){this.sessions.delete(e);for(let n of this.items.values())n.sessionId===e&&(n.state==="pending"||n.state==="claimed")&&this.settle(n,"expired",t,"session ended")}offer(e,t=Date.now()){let n=this.sessionFor(e.agentId);if(!n)return null;if(t-n.lastSeenAt>this.opts.staleSessionMs)return this.deregister(n.sessionId,t),null;let s={id:Le(t),agentId:e.agentId,sessionId:n.sessionId,state:"pending",text:Tr(e.text,this.opts.maxItemChars),channel:e.channel,chatId:e.chatId,sender:e.sender,createdAt:t};return this.items.set(s.id,s),new Promise(o=>{this.waiters.set(s.id,{resolve:o})})}pending(e){return[...this.items.values()].filter(t=>t.sessionId===e&&t.state==="pending").sort((t,n)=>t.createdAt-n.createdAt)}pendingCount(e){let t=0;for(let n of this.items.values())n.sessionId===e&&n.state==="pending"&&t++;return t}claim(e,t=Date.now()){let n=this.sessions.get(e);if(!n||n.awaitingAnswer)return;let s=this.pending(e)[0];if(!(!s||s.state!=="pending"))return s.state="claimed",s.claimedAt=t,n.awaitingAnswer=s.id,n.lastSeenAt=t,n.drainedThisTurn++,s}answer(e,t,n=Date.now()){let s=this.sessions.get(e);if(!s?.awaitingAnswer)return;let o=this.items.get(s.awaitingAnswer);if(s.awaitingAnswer=void 0,!(!o||o.state!=="claimed"))return o.answer=t,this.settle(o,"answered",n),o}release(e,t=Date.now()){let n=this.sessions.get(e);if(!n?.awaitingAnswer)return;let s=this.items.get(n.awaitingAnswer);if(n.awaitingAnswer=void 0,!(!s||s.state!=="claimed"))return s.state="pending",s.claimedAt=void 0,n.lastSeenAt=t,s}expire(e,t,n=Date.now()){let s=this.items.get(e);if(!s||s.state!=="pending"&&s.state!=="claimed")return!1;let o=this.sessions.get(s.sessionId);return o?.awaitingAnswer===s.id&&(o.awaitingAnswer=void 0),this.settle(s,"expired",n,t),!0}sweep(e=Date.now()){let t=0;for(let n of this.items.values())n.state==="pending"&&e-n.createdAt>=this.opts.claimTimeoutMs?this.expire(n.id,"not claimed in time",e)&&t++:n.state==="claimed"&&e-(n.claimedAt??n.createdAt)>=this.opts.claimTimeoutMs&&this.expire(n.id,"claimed but never answered",e)&&t++;for(let n of this.sessions.values())e-n.lastSeenAt>this.opts.staleSessionMs&&this.deregister(n.sessionId,e);return t}endTurn(e){let t=this.sessions.get(e);t&&(t.drainedThisTurn=0)}item(e){return this.items.get(e)}prune(e=Date.now(),t=36e5){let n=0;for(let[s,o]of this.items)(o.state==="answered"||o.state==="expired")&&e-(o.settledAt??o.createdAt)>t&&(this.items.delete(s),n++);return n}settle(e,t,n,s){e.state=t,e.settledAt=n;let o=this.waiters.get(e.id);o&&(this.waiters.delete(e.id),o.resolve(t==="answered"?{kind:"answered",text:e.answer??"",sessionId:e.sessionId}:{kind:"expired",reason:s??"expired"}))}};function Tr(r,e){return r.length<=e?r:`${r.slice(0,e)}
|
|
100
|
-
\u2026[truncated ${r.length-e} chars]`}var Ct;function Ln(){return Ct||(Ct=new $e),Ct}import{readFileSync as kr}from"fs";import{homedir as Ir}from"os";import{join as Sr}from"path";var Ae=null,Cr=6e4;function vr(){try{let r=Sr(Ir(),".claude.json"),e=kr(r,"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function $r(r,e=Date.now()){if(!r)return{available:!0,checkedAt:e,unknown:!0};let t=typeof r.cachedExtraUsageDisabledReason=="string"?r.cachedExtraUsageDisabledReason:void 0;return{available:!(t==="org_level_disabled_until"),reason:t,checkedAt:e}}function Ar(r=!1){let e=Date.now();return!r&&Ae&&e-Ae.checkedAt<Cr||(Ae=$r(vr(),e)),Ae}function Hn(r){let e=Ar();return e.available||r?null:{abort:!0,reason:e.reason||"overage_disabled",message:"Claude Max-plan overage is disabled at the org level and this agent has no warm Claude session to cache against. A cold dispatch would pay a fresh cache-create that spills past the regular allotment, producing 'out of extra usage'. Re-enable overage at claude.ai/settings/usage, OR wait until a peer agent has established a warm session this agent can inherit before retrying.",raw:e}}var Un={warnRatio:.8},B={...Un},Mr=5*60*60*1e3,Rr=60*60*1e3,de=[];function Wn(r){B={...Un,...r||{}}}function Kn(r){let e=r-Mr,t=0;for(;t<de.length&&de[t]<e;)t++;t>0&&de.splice(0,t)}function Bn(r=Date.now()){Kn(r),de.push(r)}function Gn(r=Date.now()){Kn(r);let e=r-Rr,t=0;for(let o=de.length-1;o>=0&&de[o]>=e;o--)t++;let n=de.length,s={lastHour:t,last5h:n,maxPerHour:B.maxPerHour,maxPer5h:B.maxPer5h};return B.maxPerHour&&B.maxPerHour>0&&(s.hourlyRatio=t/B.maxPerHour),B.maxPer5h&&B.maxPer5h>0&&(s.fiveHourRatio=n/B.maxPer5h),s}function qn(r,e=Date.now()){let t=Gn(e);return r?null:B.maxPerHour&&t.lastHour>=B.maxPerHour?{abort:!0,reason:"hourly_cap",message:`Claude-code fleet dispatch-budget hit: ${t.lastHour}/${B.maxPerHour} in the last hour. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPerHour in DaemonConfig if this is a false positive.`,usage:t}:B.maxPer5h&&t.last5h>=B.maxPer5h?{abort:!0,reason:"five_hour_cap",message:`Claude-code fleet dispatch-budget hit: ${t.last5h}/${B.maxPer5h} in the last 5h. Cold dispatches are being held back to preserve warm-session headroom. Raise agents.budget.maxPer5h in DaemonConfig if this is a false positive.`,usage:t}:null}function Jn(r=Date.now()){let e=Gn(r),t=B.warnRatio??.8;return e.hourlyRatio!==void 0&&e.hourlyRatio>=t&&e.hourlyRatio<1?`claude-code hourly usage ${e.lastHour}/${e.maxPerHour} (${Math.round(e.hourlyRatio*100)}% of cap)`:e.fiveHourRatio!==void 0&&e.fiveHourRatio>=t&&e.fiveHourRatio<1?`claude-code 5h usage ${e.last5h}/${e.maxPer5h} (${Math.round(e.fiveHourRatio*100)}% of cap)`:null}var vt=new Map;function zn(r,e,t){return t?`${r}:${e}:${t}`:`${r}:${e}`}function Qn(r,e,t,n=Date.now()){let s=vt.get(r);s||(s={key:r,samples:0,baseline:e,current:e,peak:e,lastAt:n,ring:[]},vt.set(r,s)),s.samples+=1,s.baseline=.2*e+(1-.2)*s.baseline,s.current=e,s.peak=Math.max(s.peak,e),s.lastAt=n,s.ring.push({key:r,timestamp:n,total:e,parts:t}),s.ring.length>100&&s.ring.shift()}function Xn(r){let e=vt.get(r);if(!e||e.samples<5)return null;let t=e.baseline*1.5;if(e.current<t)return null;let n=e.current/e.baseline;return`prompt-size drift for ${r}: ${e.current} bytes is ${n.toFixed(2)}x baseline (${Math.round(e.baseline)} bytes over ${e.samples} samples, peak ${e.peak})`}import{existsSync as Q,mkdirSync as Qr,readdirSync as V,readFileSync as Re,rmSync as Xr,writeFileSync as Yr}from"fs";import{resolve as L}from"path";import{existsSync as le,mkdirSync as $t,readFileSync as Pr,readdirSync as Dr,renameSync as Or,unlinkSync as _r,writeFileSync as Ve}from"fs";import{resolve as se,relative as et}from"path";import{z as U}from"zod";var ue=U.object({id:U.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:U.string().min(1),trigger:U.string().min(1,"procedures must describe when they apply"),inputs:U.array(U.string()).default([]),expected:U.string().optional(),kpis:U.array(U.string()).default([]),owner:U.string().optional(),tags:U.array(U.string()).default([]),status:U.enum(["draft","active","deprecated"]).default("active"),source:U.string().optional(),evidence:U.array(U.string()).default([]),created:U.string().optional(),updated:U.string().optional(),related:U.array(U.string()).default([])});function Er(r){let e=r.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)return{meta:{},body:r};let t={};for(let n of e[1].split(`
|
|
101
|
-
`)){let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!s)continue;let o=s[1],i=s[2].trim();if(i.startsWith("[")&&i.endsWith("]")){try{t[o]=JSON.parse(i);continue}catch{}t[o]=i.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),t[o]=i}return{meta:t,body:e[2]}}function tt(r){let e=["---"];return e.push(`id: ${r.id}`),e.push(`title: "${r.title.replace(/"/g,'\\"')}"`),e.push(`trigger: "${r.trigger.replace(/"/g,'\\"')}"`),r.inputs?.length&&e.push(`inputs: ${JSON.stringify(r.inputs)}`),r.expected&&e.push(`expected: "${r.expected.replace(/"/g,'\\"')}"`),r.kpis?.length&&e.push(`kpis: ${JSON.stringify(r.kpis)}`),r.owner&&e.push(`owner: ${r.owner}`),r.tags?.length&&e.push(`tags: ${JSON.stringify(r.tags)}`),e.push(`status: ${r.status}`),r.source&&e.push(`source: "${r.source.replace(/"/g,'\\"')}"`),r.evidence?.length&&e.push(`evidence: ${JSON.stringify(r.evidence)}`),r.related?.length&&e.push(`related: ${JSON.stringify(r.related)}`),r.created&&e.push(`created: ${r.created}`),r.updated&&e.push(`updated: ${r.updated}`),e.push("---"),e.join(`
|
|
102
|
-
`)}var Me=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??se(process.cwd(),".agentx/procedures"),$t(this.baseDir,{recursive:!0})}pathFor(e){return se(this.baseDir,`${e}.md`)}get draftsDir(){return se(this.baseDir,"_drafts")}draftPathFor(e){return se(this.draftsDir,`${e}.md`)}parseFile(e){let t=Pr(e,"utf-8"),{meta:n,body:s}=Er(t),o=ue.safeParse({...n,inputs:n.inputs||[],kpis:n.kpis||[],tags:n.tags||[],related:n.related||[],evidence:n.evidence||[]});return o.success?{meta:o.data,body:s.trim(),path:et(this.baseDir,e)}:null}listDir(e){if(!le(e))return[];let t=[];for(let n of Dr(e,{withFileTypes:!0})){if(!n.isFile()||!n.name.endsWith(".md")||n.name.startsWith("_"))continue;let s=this.parseFile(se(e,n.name));s&&t.push(s)}return t.sort((n,s)=>n.meta.id.localeCompare(s.meta.id))}list(){return this.listDir(this.baseDir)}listDrafts(){return this.listDir(this.draftsDir)}get(e){let t=this.pathFor(e);return le(t)?this.parseFile(t):null}getDraft(e){let t=this.draftPathFor(e);return le(t)?this.parseFile(t):null}add(e,t){let n=ue.parse({...e,created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(n.id);if(le(s))throw new Error(`Procedure already exists: ${n.id}`);return Ve(s,tt(n)+`
|
|
103
|
-
|
|
104
|
-
`+t.trim()+`
|
|
105
|
-
`),{meta:n,body:t.trim(),path:et(this.baseDir,s)}}update(e,t,n){let s=this.get(e);if(!s)throw new Error(`Procedure not found: ${e}`);let o=ue.parse({...s.meta,...t,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),i=n!==void 0?n:s.body;return Ve(this.pathFor(e),tt(o)+`
|
|
106
|
-
|
|
107
|
-
`+i.trim()+`
|
|
108
|
-
`),{meta:o,body:i.trim(),path:s.path}}addDraft(e,t){let n=ue.parse({...e,status:"draft",created:e.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)});if(this.get(n.id))throw new Error(`Procedure already exists: ${n.id}`);let s=this.draftPathFor(n.id);if(le(s))throw new Error(`Draft already exists: ${n.id}`);return $t(this.draftsDir,{recursive:!0}),Ve(s,tt(n)+`
|
|
109
|
-
|
|
110
|
-
`+t.trim()+`
|
|
111
|
-
`),{meta:n,body:t.trim(),path:et(this.baseDir,s)}}promoteDraft(e){let t=this.getDraft(e);if(!t)throw new Error(`Draft not found: ${e}`);if(this.get(e))throw new Error(`Procedure already exists: ${e}`);let n=ue.parse({...t.meta,status:"active",updated:new Date().toISOString().slice(0,10)});return Ve(this.pathFor(e),tt(n)+`
|
|
112
|
-
|
|
113
|
-
`+t.body+`
|
|
114
|
-
`),_r(this.draftPathFor(e)),{meta:n,body:t.body,path:et(this.baseDir,this.pathFor(e))}}rejectDraft(e){let t=this.draftPathFor(e);if(!le(t))throw new Error(`Draft not found: ${e}`);let n=se(this.draftsDir,"_rejected");$t(n,{recursive:!0}),Or(t,se(n,`${e}.md`))}isRejected(e){return le(se(this.draftsDir,"_rejected",`${e}.md`))}deprecate(e){return this.update(e,{status:"deprecated"})}};import{existsSync as Nr,mkdirSync as Fr,readFileSync as jr,writeFileSync as Lr}from"fs";import{dirname as Hr,resolve as Ur}from"path";import{z}from"zod";var Wr=z.object({key:z.string(),count:z.number().int().min(0).default(0),firstSeen:z.string(),lastSeen:z.string(),taskIds:z.array(z.string()).default([]),sampleMessage:z.string().default(""),status:z.enum(["counting","drafted","promoted","rejected"]).default("counting"),procedureId:z.string().optional()}),Kr=z.object({minedThrough:z.string().optional(),candidates:z.array(Wr).default([])});function Yn(r){return Ur(r,"_candidates.json")}function Br(r){let e=Yn(r);if(!Nr(e))return{candidates:[]};try{let t=Kr.safeParse(JSON.parse(jr(e,"utf-8")));if(t.success)return t.data}catch{}return{candidates:[]}}function Gr(r,e){let t=Yn(r);Fr(Hr(t),{recursive:!0}),Lr(t,JSON.stringify(e,null,2)+`
|
|
115
|
-
`)}function qr(r,e,t,n,s){let o=r.candidates.find(i=>i.key===e);return o||(o={key:e,count:0,firstSeen:n,lastSeen:n,taskIds:[],sampleMessage:s,status:"counting"},r.candidates.push(o)),o.taskIds.includes(t)||(o.taskIds.push(t),o.count+=1,n<o.firstSeen&&(o.firstSeen=n),n>o.lastSeen&&(o.lastSeen=n),o.sampleMessage||(o.sampleMessage=s)),o}function Jr(r,e){return r.candidates.filter(t=>t.status==="counting"&&t.count>=e).sort((t,n)=>n.count-t.count)}function zr(r,e,t,n){let s=r.candidates.find(o=>o.key===e);s&&(s.status=t,n&&(s.procedureId=n))}function At(r){return new Set(r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Zn(r,e){if(r.size===0||e.size===0)return 0;let t=0;for(let n of r)e.has(n)&&t++;return t/Math.max(r.size,e.size)}function Mt(r,e,t={}){let n=Math.max(1,t.limit??3),s=t.minScore??.2,o=At(r),i=[];for(let a of e){if(a.meta.status!=="active")continue;let c=[],d=Zn(o,At(a.meta.trigger));d>0&&c.push("trigger");let u=[a.meta.id,a.meta.title,...a.meta.tags,...a.meta.inputs].join(" "),l=Zn(o,At(u));l>0&&c.push("title/tags");let g=Math.min(1,d*.7+l*.5);g>=s&&i.push({procedure:a,score:g,reasons:c})}return i.sort((a,c)=>c.score-a.score).slice(0,n)}function Rt(r){return["The user's request matches an established procedure. Follow its steps unless the user asks otherwise \u2014 they encode the known-good path.",...r.map(t=>{let n=t.procedure,s=[`[Known procedure: ${n.meta.title}]`,n.meta.trigger];return n.meta.inputs.length&&s.push(`Inputs: ${n.meta.inputs.join(", ")}`),s.push(n.body),n.meta.expected&&s.push(`Done when: ${n.meta.expected}`),s.push(`(details: agentx procedure show ${n.meta.id})`),s.join(`
|
|
116
|
-
`)})].join(`
|
|
117
|
-
|
|
118
|
-
`)}function Vn(r,e){return e!=="claude-code"&&e!=="codex-cli"?!1:r==="github"||r==="gitlab"}var os;function Vi(r){os=r}function ea(){return os}var es=64*1024,Zr=5*60*1e3,xe=".agentx/task-history",Vr=30;function Pe(r,e=800){return r.length<=e?r:r.slice(0,e)+` \u2026[+${r.length-e} chars]`}function eo(r,e){let t=0;try{t=r.listArticles(e).length}catch{return""}if(t===0)return"";let n=L(r.baseDir,"_index.md");if(!Q(n))return"";let s=process.argv[1]||"dist/cli.js",o=r.baseDir.replace(new RegExp(`/agents/${e}(/[^/]+)?$`),"");return["[Institutional Wiki \u2014 cross-agent source of truth]",`A curated wiki with ${t} article${t===1?"":"s"} grouped by type: person, project, place, concept, event, decision, pattern.`,"","The wiki is the canonical source for: who people are (team, clients, agents), past events (incidents, deploys), decisions and their reasoning, documented procedures, patterns.","","BEFORE you grep the workspace, search memory, or answer from your own prior context \u2014 if the question is about who / what happened / what we decided / how we do X, call:",` node ${s} wiki query "the user's question" --dir ${o} --agent ${e}`,"","It walks the catalog + wikilink graph and returns a cited answer. Your workspace memory is local to you; the wiki is shared and authoritative. Prefer the wiki for institutional questions; prefer your workspace for code-level questions.","[End Institutional Wiki]"].join(`
|
|
119
|
-
`)}var Pt=8*1024;function ts(r){if(r.length<=Pt)return r;let e=r.length-Pt;return r.slice(0,Pt)+`\u2026[+${e}]`}function ns(r,e){if(!e||typeof e!="object"||e.type!=="assistant")return;let t=e.message?.content;if(Array.isArray(t))for(let n of t){if(n?.type!=="tool_use")continue;let s=typeof n.name=="string"?n.name:"";s&&r.set(s,(r.get(s)??0)+1)}}function to(r,e){if(!r||r.length===0)return null;for(let t of r)if((e.get(t)??0)===0)return t;return null}function ss(r,e,t){if(!t||typeof t!="object")return;let n=t.type,s=new Date().toISOString(),o=ne();if(n==="assistant"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_use"){let a=i.input!=null?JSON.stringify(i.input):"";o.emit("task:step",{taskId:r,agentId:e,name:"tool_use",action:typeof i.name=="string"?i.name:null,status:"in-flight",inputSummary:a?ts(a):null,at:s})}return}if(n==="user"&&t.message?.content){for(let i of t.message.content)if(i.type==="tool_result"){let a=Array.isArray(i.content)?i.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof i.content=="string"?i.content:"";o.emit("task:step",{taskId:r,agentId:e,name:"tool_result",status:i.is_error?"error":"ok",outputSummary:a?ts(a):null,at:s})}return}}function no(){let r="",e="";return t=>{if(!t||typeof t!="object")return"";let n=t.type;if(n==="codex.spawned"){let s=t.model?` model=${t.model}`:"",o=t.resumeSessionId?` resume=${String(t.resumeSessionId).slice(0,8)}`:"";return`. codex started${s}${o}
|
|
120
|
-
`}if(n==="thread.started")return`. codex thread started${t.thread_id?` thread=${String(t.thread_id).slice(0,8)}`:""}
|
|
121
|
-
`;if(n==="turn.started")return`. codex turn started
|
|
122
|
-
`;if(n==="turn.completed"){let s=t.usage||{},o=s.input_tokens??s.inputTokens,i=s.output_tokens??s.outputTokens;return`. codex turn completed${o||i?` input=${o||0} output=${i||0}`:""}
|
|
123
|
-
`}if(n==="item.started"||n==="item.completed"){let s=t.item||{};if(s.type==="agent_message"&&typeof s.text=="string"){let c=s.text,d=c.startsWith(e)?c.slice(e.length):c;return e=c.startsWith(e)?c:e+c,d}let o=s.type||"item",i=s.name||s.command||s.tool_name||s.id||"";if(n==="item.started")return`
|
|
124
|
-
> codex ${o}${i?` ${i}`:""}
|
|
125
|
-
`;let a=s.output||s.result||s.text||s.error||"";return`< codex ${o}${i?` ${i}`:""}${a?`: ${Pe(String(a),800)}`:""}
|
|
126
|
-
`}if(n==="error"||n==="turn.failed"){let s=t.message||t.error||t.reason||JSON.stringify(t);return`[error] ${Pe(String(s),800)}
|
|
127
|
-
`}if(n==="system"&&t.subtype==="init"){let s=t.model?` model=${t.model}`:"",o=t.session_id?` session=${t.session_id.slice(0,8)}`:"";return`\xB7 init${s}${o}
|
|
128
|
-
`}if(n==="assistant"&&t.message?.content){let s="";for(let o of t.message.content)if(o.type==="text"&&typeof o.text=="string")o.text.length>r.length&&(s+=o.text.slice(r.length),r=o.text);else if(o.type==="thinking"&&typeof o.thinking=="string")s+=`
|
|
129
|
-
\u{1F4AD} ${Pe(o.thinking,600)}
|
|
130
|
-
`;else if(o.type==="tool_use"){let i=o.name||"tool",a=o.input?Pe(JSON.stringify(o.input),400):"";s+=`
|
|
131
|
-
\u2192 ${i}(${a})
|
|
132
|
-
`}return s}if(n==="user"&&t.message?.content){let s="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";s+=`${a}${Pe(i,800)}
|
|
133
|
-
`}return s}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
134
|
-
`:""}}var rs=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Xe;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;classifier;graphStore;handoverStore=new zt;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new qe(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Jt(void 0,void 0,"unified"),this.memoryStore=new ze,this.patternStore=new Ze,this.rateLimiter=new Je,this.tokenTracker=new be,this.messageQueue=new Ye,Wn({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Gt({baseDir:L(process.cwd(),e.graph.baseDir),log:(...s)=>t("[graph]",...s)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new qt({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...s)=>t("[classifier]",...s)})}for(let[n,s]of Object.entries(e.agents))this.agents.set(n,{id:n,def:s,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let s=this.handoverStore.get(t,n);if(!s||s.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&s.summaryConsumedAt))return{fromAgent:s.fromAgent,summary:o||s.summary,at:s.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),s,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(s=i,o=d.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(s);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async captureRotationMemoAsync(e,t,n,s,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-B3EXXSEH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let d=o.split(/[:@.]/).filter(Boolean).slice(0,4);this.memoryStore.addMemory(e,{agentId:e,category:"fact",content:`[Rotation memo \xB7 ${i}] ${c.memo}`,keywords:["rotation-memo",s,...d],source:{channel:s,chatId:o,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}}),this.sessions.setRotationMemo(e,s,o,c.memo,i),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[s,o]of this.agents)s!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(s,t),role:o.def.systemPrompt?.split(`
|
|
135
|
-
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(s=>s.startsWith("@")):n.mentions[0]}async execute(e,t,n,s){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,s)}catch(a){i={content:"",error:a?.message??String(a)}}if(e.intentRef)try{let a=i.error?/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";Vt().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,s){let o=Ln().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(o){let y=await o;if(y.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${y.sessionId}`),{content:y.text,viaAttachedSession:y.sessionId};this.log(`[${e.agentId}] attached session did not take it (${y.reason}) \u2014 spawning`)}let i=this.agents.get(e.agentId);if(!i){if(this.meshFallback){let y=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(M=>M.id===e.agentId));if(y){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${y.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(y.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:y.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${y.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let a=e.context?.channel||"api",c=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(i.activeTasks>=i.def.maxConcurrent)if(a==="api"){let y=Date.now(),h=25*6e4,M=500;for(;i.activeTasks>=i.def.maxConcurrent;){if(Date.now()-y>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(N=>setTimeout(N,M))}}else{let y=i.def.queueMode||"collect",h=this.messageQueue.enqueue(e.agentId,a,c,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:a,chatId:c,originalContext:e.context});if(h==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(h){let M=this.messageQueue.pendingCount(e.agentId,a,c);return this.log(`[${e.agentId}] busy, message queued (mode: ${h}, pending: ${M})`),{content:"",error:`__queued__:${h}:${M}`}}}let d=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(y,h)=>{this.log(`[${e.agentId}] ${y} \u2014 queued, resumes in ~${Math.max(1,Math.round(h/1e3))}s`)}});if(!d.ok)return this.log(`[${e.agentId}] ${d.reason}`),{content:"",error:d.reason};i.activeTasks++,i.totalTasks++,i.lastActive=new Date;let u={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};i.runningTasks.push(u);let l=new AbortController;this.taskAborts.set(u.id,{agentId:e.agentId,channel:u.channel,chatId:typeof u.chatId=="string"?u.chatId:"",originalMessage:e.message||"",controller:l});let g={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(u.id,g);let m=y=>{if(y){g.buffer+=y,g.buffer.length>es&&(g.buffer=g.buffer.slice(g.buffer.length-es));for(let h of g.subscribers)try{h(y)}catch{}}},b=Le();e.taskId=b;let w=new Map,x;if(t){let y=no();x=h=>{let M=y(h);if(M&&m(M),ss(b,e.agentId,h),ns(w,h),s)try{s(h)}catch{}}}else x=y=>{if(ss(b,e.agentId,y),ns(w,y),s)try{s(y)}catch{}};this.messageQueue.markRunning(e.agentId,a,c),this.log(`[${e.agentId}] executing task (${i.activeTasks}/${i.def.maxConcurrent})`);let p=e.context?.channel||"api",f=e.context?.chatId||e.context?.group||e.context?.sender||"default",D=e.context?.sender||"User",C=i.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,p,f),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${p}:${f}`),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"stale",at:new Date().toISOString()})),e.freshSession||await this.sessions.seedIfEmpty(e.agentId,p,f),this.sessions.addUserMessage(e.agentId,p,f,D,e.message);let T=Date.now();ne().emit("task:started",{agentId:e.agentId,channel:p,chatId:f,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(T).toISOString(),taskId:b});let $;if(this.classifier&&p!=="a2a"&&!C)try{$=await this.classifier.classify({text:e.message,channel:p,sender:e.context?.sender,agentId:e.agentId})||void 0}catch(y){this.log(`[classifier] classify failed for ${e.agentId}: ${y?.message||y}`)}let F=this.config.workflows?.matching,k;if(this.config.workflows?.enabled&&F?.enabled)try{let y=new nn({baseDir:L(process.cwd(),this.config.workflows.dir)}),h=sn({agentId:e.agentId,channel:p,message:e.message,intentPath:$?.path},y.list());h&&h.confidence>=F.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${h.workflow.id} confidence=${h.confidence.toFixed(2)} mode=${F.mode} reasons=${h.reasons.join(",")||"n/a"}`),F.mode==="auto"&&h.confidence>=F.autoRunThreshold&&(this.workflowAutoRunner?k={workflowId:h.workflow.id,confidence:h.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(y){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${y?.message||y}`)}let A=this.wikiHub.getAgentWiki(e.agentId),R=eo(A,e.agentId),S=this.memoryStore.findRelevant(e.message,e.agentId,C?3:8),I=this.memoryStore.buildContext(S),P=this.patternStore.findRelevant(e.message,e.agentId,5),E=this.patternStore.buildContext(P),W="";if(!C)try{let{loadLocalSkills:y,getAutoInjectSkills:h}=await import("./loader-5CA3O5GM.js"),M=await y(i.def.workspace);W=h(M,e.message)}catch{}let _=i.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,p,f):i.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,p,f):i.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,p,f):void 0;if(_&&this.sessions.isSessionStale(e.agentId,p,f)&&(this.log(`[${e.agentId}] session stale for ${p}:${f}, starting fresh`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,_,p,f,"stale"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"stale",at:new Date().toISOString()}),_=void 0),_&&this.sessions.shouldRotateByTierTwo(e.agentId,p,f)){let y=this.sessions.getLastTurnContextTokens(e.agentId,p,f);this.log(`[${e.agentId}] tier-2 rotation for ${p}:${f} (last turn context: ${y} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,_,p,f,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"tier-2",lastTurnInputTokens:y,at:new Date().toISOString()}),_=void 0}if(_&&this.sessions.shouldRotateByTurns(e.agentId,p,f)){let y=this.sessions.getTurnCount(e.agentId,p,f);this.log(`[${e.agentId}] max-turns rotation for ${p}:${f} (${y} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),i.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,i.def,_,p,f,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,p,f),ne().emit("session:rotated",{agentId:e.agentId,channel:p,chatId:f,reason:"max-turns",at:new Date().toISOString()}),_=void 0}try{let y=await this.sessions.compactIfNeeded(e.agentId,p,f,this.memoryStore);if(y.compacted){let h=y.qualityScore??"?",M=y.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${p}:${f} (quality: ${h}%, ${M} entities lost)`),y.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${y.lostEntities.slice(0,5).join(", ")}`),y.drift){let N=y.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${N.overallScore} (lexicon=${N.lexiconDecay}, tools=${N.toolShift}, semantic=${N.semanticDrift})`),N.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${N.lostWords.slice(0,5).join(", ")}`)}}}catch(y){this.log(`[${e.agentId}] compaction failed (non-fatal): ${y.message}`)}let q=process.env.AGENTX_CONTEXT_SURGERY==="1",O=C?{maxMessages:8,maxChars:2400}:q&&Vn(p,i.def.tier)?{maxMessages:6,maxChars:1800}:void 0,J=_?void 0:this.sessions.buildHistoryContext(e.agentId,p,f,O),is=_?void 0:this.sessions.getRotationMemo(e.agentId,p,f)??void 0,Dt;if(this.config.procedures?.injection?.enabled&&!_&&!C)try{let y=new Me({baseDir:L(process.cwd(),this.config.procedures.dir)}),h=Mt(e.message,y.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(h.length>0){Dt=Rt(h);for(let M of h)this.log(`[${e.agentId}] procedure match ${M.procedure.meta.id} score=${M.score.toFixed(2)} (${M.reasons.join(",")})`)}}catch(y){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${y?.message||y}`)}if(ie&&ie.cat)try{let h=this.sessions.getSession(e.agentId,p,f).messages,M=h[0],N=h[h.length-1],H=J===void 0?`resume=${_?_.slice(0,8):"?"} (no rebuild)`:`fresh history=${J.length}c/${J.split(`
|
|
136
|
-
`).length}L`,Y=`[${e.agentId}] ${p}:${f} ${H} | session.messages=${h.length}`+(h.length>0?` first=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")}) last=${N.timestamp.slice(11,19)}(${N.role}:${(N.content||"").slice(0,40).replace(/\n/g," ")})`:"");ie.cat("context",Y)}catch(y){ie.cat("context",`[${e.agentId}] context-diag error: ${y?.message??y}`)}let Ot;if(i.def.contextReferences&&!_)try{let y=i.def.workspace,h=this.referencesCache.get(y);if(!h){let[N,H]=await Promise.all([ct(i.def.workspace),dt(i.def.workspace)]);if(N.byId.size===0&&H.recipes.length===0){let[Y,v]=await Promise.all([ct(process.cwd()),dt(process.cwd())]);h={refs:Y,recipes:v}}else h={refs:N,recipes:H};this.referencesCache.set(y,h)}let M=en({agentId:e.agentId,intentTags:$?.path,message:e.message},h.recipes,h.refs);M.cards.length>0&&(Ot=Zt(M.cards,500*4)),M.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${M.unresolvedIds.join(", ")}`)}catch(y){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${y?.message||y}`)}let _t=this.sessions.getCrossSessionSummary(e.agentId,p,f,e.message),Et,De=In(e.message);if(De)try{let y=this.sessions.recallTurns({agentId:e.agentId,channel:p,chatId:f,lookbackDays:De.lookbackDays,limit:12});if(y.turns.length>0){let h=[`[Long-memory recall \u2014 last ${De.lookbackDays}d on this chat (cue-triggered)]`],M=[...y.turns].sort((N,H)=>N.ts.localeCompare(H.ts));for(let N of M){let H=N.ts.slice(11,16)+" "+N.day,Y=N.role==="user"?N.senderName||"User":N.senderName||"Agent";h.push(`${H} ${Y}: ${N.content}`)}y.hasMore&&h.push(`[\u2026${y.totalScanned-y.turns.length}+ older turns available \u2014 call /recall with before=${y.oldestTs} to walk further back]`),h.push("[End of long-memory recall \u2014 respond to the latest message above]"),Et=h.join(`
|
|
137
|
-
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${De.lookbackDays}d, turns=${y.turns.length}, scanned=${y.totalScanned}`)}}catch(y){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${y.message}`)}let as=C?"layered":e.contextStrategy??i.def.contextStrategy??this.config.session.contextStrategy??"layered",Nt,Ft,jt=!1;if(as==="planner"){try{let{planContext:y}=await import("./context-planner-45GEWKGL.js"),h=await y({agentId:e.agentId,channel:p,chatId:f,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore});h?(jt=!0,Nt=h.sessionHistory,I=h.memoryContext,_t=h.crossChatContext,Ft=h.debug,this.log(`[${e.agentId}] planner: turns=${h.debug.recentTurns}, mem=${h.debug.memoryIncluded?"yes":"no"}, xchat=${h.debug.crossChatIncluded?"yes":"no"} (${h.debug.planLatencyMs}ms) \u2014 ${h.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(y){this.log(`[${e.agentId}] planner failed (non-fatal): ${y.message} \u2014 falling back to layered (keeping --resume for continuity)`)}jt&&_&&(this.sessions.clearClaudeSessionId(e.agentId,p,f),_=void 0)}let nt=`${e.agentId}:${p}:${f}`,Oe=Yt(e.message);Oe&&(Oe==="default"?(this.activeSouls.delete(nt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(nt,Oe),this.log(`[${e.agentId}] Soul switched to: ${Oe}`)));let cs=this.activeSouls.get(nt),ds=Qt(i.def.workspace,cs),us=Xt(ds),ls=this.agentMemory.indexMarkdown(e.agentId),gs=i.def.tier==="claude-code"||i.def.tier==="codex-cli"?`[Operating principle]
|
|
138
|
-
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",ps=i.def.richMessages!==!1&&(p==="telegram"||p==="whatsapp")?["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text."].join(`
|
|
139
|
-
`):"",Lt="";if(i.def.workspace){let y=L(i.def.workspace,"CLAUDE.md");if(Q(y))try{let h=Re(y,"utf-8");Lt=`[Project CLAUDE.md]
|
|
140
|
-
${h.length>4e3?h.slice(0,4e3)+`
|
|
141
|
-
|
|
142
|
-
[CLAUDE.md truncated to 4KB]`:h}`}catch{}}let _e=e.context?.runbookPath,st=[];if(_e&&Q(_e)){let y=e.context?.runbookFiles&&e.context.runbookFiles.length>0?e.context.runbookFiles:["CLAUDE.md","AGENTS.md","DEPLOY.md","RUNBOOK.md"],h=0,M=4e3,N=16e3;for(let H of y){if(h>=N)break;let Y=L(_e,H);if(Q(Y))try{let v=Re(Y,"utf-8"),X=v.length>M?v.slice(0,M)+`
|
|
143
|
-
|
|
144
|
-
[${H} truncated to ${M} bytes]`:v;st.push(`[Project Runbook \u2014 ${H} from ${_e}]
|
|
145
|
-
${X}`),h+=X.length}catch{}}}let fs=st.length>0?st.join(`
|
|
146
|
-
|
|
147
|
-
`):"",rt=[i.def.systemPrompt||"",gs,ps,Lt,fs,us||"",ls||""].filter(y=>y.trim().length>0).join(`
|
|
148
|
-
|
|
149
|
-
`)||void 0,hs={channel:p,chatId:f,channelScope:e.context?.group?"group":p==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:i.def.name,agentHandle:this.getChannelHandle(e.agentId,p),systemPrompt:i.def.systemPrompt,sender:D,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:C||Vn(p,i.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:C?void 0:E||void 0,procedureContext:Dt,references:Ot,skillInjection:W||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Nt??J,memoryContext:I||void 0,crossChatContext:_t||void 0,longMemoryRecall:Et||void 0,wikiContext:C?void 0:R,handoverNote:this.buildHandoverNote(e.agentId,p,f),rotationMemo:is,intent:$?{path:$.path,pathLabel:$.pathLabel,pathId:$.pathId,axes:$.axes,leaf:$.leaf,status:$.status}:void 0,message:e.message},ot=Rn(hs,C?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),it=(ot?.length??0)+(rt?.length??0)+(e.message?.length??0),Ee={history:ot?.length??0,sysPrompt:rt?.length??0,message:e.message?.length??0},Ht=zn(e.agentId,p,f);Qn(Ht,it,Ee);let Ut=Xn(Ht);Ut&&this.log(`[${e.agentId}] ${Ut}`),it>16e3&&this.log(`[${e.agentId}] large context for ${p}:${f}: ${it} bytes (history=${Ee.history}, sysPrompt=${Ee.sysPrompt}, message=${Ee.message})`);let ms={...e,systemPromptAppend:rt},Z;try{if(k&&this.workflowAutoRunner)try{let j=await this.workflowAutoRunner({workflowId:k.workflowId,agentId:e.agentId,channel:p,chatId:f,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:p,chatId:f,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:$?.path,matchedWorkflowId:k.workflowId,matchConfidence:k.confidence}});return this.log(`[${e.agentId}] workflow auto-run started ${k.workflowId} run=${j.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),Z={content:"",duration:0,metadata:{handledByWorkflow:k.workflowId,workflowRunId:j.runId,workflowMatchConfidence:k.confidence}},Z}catch(j){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${j?.message||j}`)}if(i.def.tier==="claude-code"){let j=i.def.persistentProcess?We():null,G=j!=null&&j.hasLive({agentId:e.agentId,channel:p,chatId:f}),ge=!!_||G,oe=[Hn(ge),qn(ge)].find(we=>we&&we.abort);if(oe){i.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let we={content:"",error:oe.message,duration:0};if(!t){g.buffer=`[error] ${oe.message}`;for(let ys of g.subscribers)try{ys(g.buffer)}catch{}}return Z=we,we}Bn();let Wt=Jn();Wt&&this.log(`[${e.agentId}] ${Wt}`)}let y=i.def.tier==="claude-code",h=y?t:(j,G)=>{j&&m(j),t&&t(j,G)},M=!1,N=y?n:j=>{j&&(M?m(j):(m(`\u{1F4AD} ${j}`),M=!0)),n&&n(j)},H=()=>{M&&(m(`
|
|
150
|
-
`),M=!1)},Y=y?h:h?(j,G)=>{H(),h(j,G)}:void 0,v=await wn(i.def,ms,this.providers,Y,ot,_,x,l.signal,N);if(!v.error){let j=to(i.def.toolUseRequired,w);if(j){let G=Array.from(w.entries()).map(([ge,re])=>`${ge}=${re}`).join(", ")||"none";v.error=`tool_required_not_called: ${j} (invoked: ${G})`,v.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${j}, observed ${G}`)}}Z=v;let X=v.usage?An(v.usage):void 0;if(ne().emit("task:completed",{taskId:b,agentId:e.agentId,channel:p,chatId:f,durationMs:Date.now()-T,error:v.error||void 0,inputTokens:X?.inputTokens,outputTokens:X?.outputTokens,cacheReadTokens:X?.cacheReadTokens,cacheCreateTokens:X?.cacheCreateTokens,tier2InputTokens:X?.tier2InputTokens,tier2OutputTokens:X?.tier2OutputTokens,tier2CacheReadTokens:X?.tier2CacheReadTokens,tier2CacheCreateTokens:X?.tier2CacheCreateTokens,finalResponse:v.content||void 0,billedModel:v.billedModel||i.def.model||void 0,at:new Date().toISOString()}),!t&&(v.content||v.error)){let j=v.error?`[error] ${v.error}`:v.content;g.buffer=j;for(let G of g.subscribers)try{G(j)}catch{}}if(v.error)i.errors++,this.log(`[${e.agentId}] error: ${v.error}`);else{if(this.sessions.addAgentMessage(e.agentId,p,f,v.content),v.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,p,f,v.claudeSessionId),v.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,p,f,v.codexSessionId),v.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,p,f,v.opencodeSessionId),(v.claudeSessionId||v.codexSessionId||v.opencodeSessionId)&&v.usage&&this.sessions.recordTurnUsage(e.agentId,p,f,v.usage,v.contextTokens),v.usage){let re=v.contextTokens,oe=(v.usage.inputTokens||0)+(v.usage.cacheReadTokens||0)+(v.usage.cacheCreateTokens||0);(re??oe)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${p}:${f}: context=${re??"n/a"} tokens (cumulative turn total=${oe}) \u2014 next turn will rotate`)}if(v.content.length>50){try{let re=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:re,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:p,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
151
|
-
|
|
152
|
-
Agent: ${v.content}`,meta:$?.path?.length?{intentPath:$.path,intentPathLabel:$.pathLabel}:void 0})}catch{}Bt(e.agentId,e.message,v.content,{channel:p,chatId:f,sender:D},this.memoryStore).catch(()=>{}),Fn(e.agentId,e.message,v.content,{channel:p,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let j=v.billedModel||e.model||i.def.model,G=e.context?.channel,ge=G&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${G}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,v.duration||0,v.usage,e.message.length,v.content.length,!1,j,G,ge),this.log(`[${e.agentId}] completed in ${v.duration}ms`+(v.tokensUsed?` (${v.tokensUsed} tokens)`:""))}return v}catch(y){i.errors++,this.log(`[${e.agentId}] unexpected error: ${y.message}`);let h=He(y.message);return Z={content:"",error:Ue(h),errorKind:h.kind},Z}finally{i.activeTasks--;let y=i.runningTasks.findIndex(h=>h.id===u.id);y!==-1&&i.runningTasks.splice(y,1),this.taskAborts.delete(u.id),g.done=!0,g.endedAt=new Date;for(let h of g.subscribers)try{h(`
|
|
153
|
-
[task finished]
|
|
154
|
-
`)}catch{}g.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(u.id),Zr).unref?.();try{let h=g.endedAt,M={id:u.id,agentId:e.agentId,channel:u.channel,chatId:u.chatId,sender:u.sender,message:e.message||"",startedAt:u.startedAt.toISOString(),endedAt:h.toISOString(),durationMs:h.getTime()-u.startedAt.getTime(),ok:!Z?.error,error:Z?.error,responseText:Z?.content||"",transcript:g.buffer};this.persistTaskRecord(M);let N=(M.responseText||M.error||"").trim();if(N){let H=N.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:H,at:h,ok:M.ok})}}catch(h){this.log(`[${e.agentId}] task history persist failed: ${h?.message}`)}this.messageQueue.markDone(e.agentId,a,c).then(h=>{if(h.length!==0){this.log(`[${e.agentId}] flushing ${h.length} queued message(s)`);for(let M of h){let N=M.originalContext||{channel:M.channel,sender:M.sender,chatId:M.chatId};this.execute({message:M.text,agentId:e.agentId,context:N}).then(H=>this.postQueuedResponseToChannel(e.agentId,N,H)).catch(H=>{this.log(`[${e.agentId}] queued message failed: ${H.message}`)})}}}).catch(h=>{this.log(`[${e.agentId}] queue flush failed: ${h.message}`)})}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=L(process.cwd(),xe,this.safe(e.agentId),t);Q(n)||Qr(n,{recursive:!0});let s=L(n,`${this.safe(e.id)}.json`);Yr(s,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),s=this.sparklineCache.get(e);if(s&&n-s.at<6e4&&s.hourly.length===t)return s.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=L(process.cwd(),xe,this.safe(e));if(!Q(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let l of[d,c]){let g=L(a,l);if(Q(g))try{for(let m of V(g)){if(!m.endsWith(".json"))continue;let b=m.split("-")[0],w=parseInt(b,10);if(!Number.isFinite(w)||w<i||w>n)continue;let x=Math.floor((n-w)/36e5),p=t-1-x;p>=0&&p<t&&o[p]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=L(process.cwd(),xe);if(!Q(e))return 0;let t=0;for(let n of V(e)){let s=L(e,n),o;try{o=V(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=L(s,i),c;try{c=V(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Re(L(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let g=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:g,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Vr){let t=L(process.cwd(),xe);if(!Q(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=0;for(let o of V(t)){let i=L(t,o),a;try{a=V(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Xr(L(i,c),{recursive:!0,force:!0}),s++}catch{}}}return s}listTaskHistory(e,t=50){let n=L(process.cwd(),xe,this.safe(e));if(!Q(n))return[];let s=V(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of s){if(o.length>=t)break;let a=L(n,i),c;try{c=V(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(Re(L(a,d),"utf-8")),{transcript:l,responseText:g,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let n=L(process.cwd(),xe,this.safe(e));if(!Q(n))return null;let s=this.safe(t),o=V(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=L(n,i,`${s}.json`);if(Q(a))try{return JSON.parse(Re(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let s=tn();if(!s)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&s.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}queueFollowUp(e,t,n,s={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(i,a,c),m=!1;if(s.replace){let b=s.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),m=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:m,edited:l,pending:g}}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{ro as a,on as b,Cs as c,As as d,Ds as e,Os as f,_s as g,wn as h,qe as i,Je as j,Xe as k,ne as l,jn as m,wr as n,Ln as o,Me as p,Br as q,Gr as r,qr as s,Jr as t,zr as u,Mt as v,Vi as w,ea as x,Pt as y,ts as z,ns as A,to as B,ss as C,rs as D};
|
|
155
|
-
//# sourceMappingURL=chunk-E5CXCI33.js.map
|