agentic-qe 3.11.2 → 3.11.3
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/.claude/skills/.validation/templates/eval.template.yaml +36 -0
- package/.claude/skills/qe-quality-assessment/SKILL.md +25 -0
- package/.claude/skills/qe-test-generation/SKILL.md +58 -20
- package/.claude/skills/qe-test-generation/evals/qe-test-generation.yaml +37 -0
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +36 -0
- package/assets/skills/.validation/templates/eval.template.yaml +36 -0
- package/assets/skills/enterprise-integration-testing/SKILL.md +1 -1
- package/assets/skills/pentest-validation/SKILL.md +1 -1
- package/assets/skills/qcsd-development-swarm/SKILL.md +27 -6
- package/assets/skills/qe-quality-assessment/SKILL.md +25 -0
- package/assets/skills/qe-test-generation/SKILL.md +58 -20
- package/assets/skills/qe-test-generation/evals/qe-test-generation.yaml +37 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-IU3H3MD7.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-FNCVODUJ.js → agent-booster-wasm-BFRW7HEU.js} +2 -2
- package/dist/cli/chunks/{agent-handler-JK7VK37B.js → agent-handler-ZVC3VFPC.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-EPVVJNNA.js → agent-memory-branch-3WU3CVSX.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-BGOC63IN.js +2 -0
- package/dist/cli/chunks/{arena-NTHVDZTJ.js → arena-JMVTWWG5.js} +2 -2
- package/dist/cli/chunks/{arena-EH2IMSRW.js → arena-QMRLNQUC.js} +4 -4
- package/dist/cli/chunks/{audit-ODZV2T2B.js → audit-TTWAAV7P.js} +2 -2
- package/dist/cli/chunks/base-DVPRE3WO.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-2KL54YUA.js → better-sqlite3-QNZJOJAB.js} +2 -2
- package/dist/cli/chunks/{brain-handler-NVB6OJ25.js → brain-handler-FXPLJCPV.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-BIXSELMY.js → branch-enumerator-CJJG6X3I.js} +2 -2
- package/dist/cli/chunks/{browser-S2Y2W33Z.js → browser-LI2CDWVR.js} +2 -2
- package/dist/cli/chunks/browser-workflow-MP5P7KZF.js +2 -0
- package/dist/cli/chunks/{chunk-OFUF3APC.js → chunk-22CUJA33.js} +2 -2
- package/dist/cli/chunks/{chunk-CUDGKSFX.js → chunk-242B625Q.js} +2 -2
- package/dist/cli/chunks/{chunk-X36TZXDK.js → chunk-26KHL4VO.js} +1 -1
- package/dist/cli/chunks/{chunk-SE4S23C7.js → chunk-27MMZQ7X.js} +1 -1
- package/dist/cli/chunks/{chunk-Z2QNTRUX.js → chunk-2OUXYSQV.js} +2 -2
- package/dist/cli/chunks/{chunk-K3YM2Z3E.js → chunk-2SZQDTI5.js} +1 -1
- package/dist/cli/chunks/{chunk-AINAWVGD.js → chunk-36HTS4EP.js} +2 -2
- package/dist/cli/chunks/{chunk-ZBJMVWQR.js → chunk-3BREKEL5.js} +2 -2
- package/dist/cli/chunks/{chunk-YGR54EAA.js → chunk-3CBYKKRW.js} +2 -2
- package/dist/cli/chunks/{chunk-XRDPGJNW.js → chunk-3E3PSEC5.js} +2 -2
- package/dist/cli/chunks/{chunk-6VAFRS5N.js → chunk-3FOFPGHH.js} +2 -2
- package/dist/cli/chunks/{chunk-O3IIAIXB.js → chunk-3XLGXCSX.js} +1 -1
- package/dist/cli/chunks/{chunk-HDBJORV7.js → chunk-4ITHKHR5.js} +2 -2
- package/dist/cli/chunks/{chunk-P2RR4SW5.js → chunk-54TDOQAH.js} +3 -3
- package/dist/cli/chunks/{chunk-EDH4H55B.js → chunk-5746QYRF.js} +2 -2
- package/dist/cli/chunks/{chunk-CAUTOCLZ.js → chunk-5EW36WTI.js} +2 -2
- package/dist/cli/chunks/{chunk-ZH6HYT7C.js → chunk-6F43POT6.js} +1 -1
- package/dist/cli/chunks/{chunk-75C5GX7D.js → chunk-6GVRP64A.js} +2 -2
- package/dist/cli/chunks/{chunk-KFE6LB4I.js → chunk-6IHB3T6M.js} +2 -2
- package/dist/cli/chunks/{chunk-BGVEBYV4.js → chunk-6JR2RSY2.js} +2 -2
- package/dist/cli/chunks/{chunk-PFDILSVO.js → chunk-6KKKPVOF.js} +1 -1
- package/dist/cli/chunks/{chunk-KEJEZY2R.js → chunk-6WWNK67C.js} +8 -8
- package/dist/cli/chunks/{chunk-XY2B2BEJ.js → chunk-77QJQRL2.js} +2 -2
- package/dist/cli/chunks/{chunk-Y4M2HMPR.js → chunk-7FVWETN4.js} +2 -2
- package/dist/cli/chunks/{chunk-CZYSCUJ4.js → chunk-7PDUD7FF.js} +2 -2
- package/dist/cli/chunks/{chunk-XNREA3FG.js → chunk-7QIYYYUE.js} +1 -1
- package/dist/cli/chunks/{chunk-NZNXEEZR.js → chunk-7S7QF4HJ.js} +1 -1
- package/dist/cli/chunks/{chunk-IO7ZUP2G.js → chunk-7SBMTSGY.js} +3 -3
- package/dist/cli/chunks/{chunk-5BDVFFYF.js → chunk-7UOH55UT.js} +2 -2
- package/dist/cli/chunks/{chunk-TOGZ37RL.js → chunk-A43MKBSX.js} +2 -2
- package/dist/cli/chunks/{chunk-S6BWEZKK.js → chunk-A4NYOH7P.js} +2 -2
- package/dist/cli/chunks/{chunk-A4ZDKF5F.js → chunk-ABD6JBNO.js} +1 -1
- package/dist/cli/chunks/{chunk-PPD5ZLNA.js → chunk-AC6OZTY4.js} +2 -2
- package/dist/cli/chunks/{chunk-6LQIVIZB.js → chunk-AKOGQT3A.js} +2 -2
- package/dist/cli/chunks/{chunk-WEBHFIWS.js → chunk-ATFADWGD.js} +2 -2
- package/dist/cli/chunks/{chunk-VNFL2TPU.js → chunk-B65CRJN6.js} +1 -1
- package/dist/cli/chunks/{chunk-AYXRT2ND.js → chunk-B6USJW5E.js} +1 -1
- package/dist/cli/chunks/{chunk-3J3QXLWP.js → chunk-B7XPSXK6.js} +2 -2
- package/dist/cli/chunks/{chunk-JCH2FHJ7.js → chunk-BA7PJS3Y.js} +2 -2
- package/dist/cli/chunks/{chunk-42DCMEUM.js → chunk-BFBZFUBP.js} +1 -1
- package/dist/cli/chunks/{chunk-P5SGBQLY.js → chunk-BHZI6PDR.js} +1 -1
- package/dist/cli/chunks/{chunk-JELN5XTK.js → chunk-BQ5EJPK3.js} +1 -1
- package/dist/cli/chunks/{chunk-WZC4HKGZ.js → chunk-CCDGNJZX.js} +2 -2
- package/dist/cli/chunks/{chunk-3ATEYGVD.js → chunk-CGKHG46K.js} +2 -2
- package/dist/cli/chunks/{chunk-RHSUXQNF.js → chunk-CLZ5RQVA.js} +2 -2
- package/dist/cli/chunks/{chunk-YJUJCLXV.js → chunk-CYJ6O5VZ.js} +2 -2
- package/dist/cli/chunks/{chunk-AZQ6HDPM.js → chunk-DNOBN3IR.js} +2 -2
- package/dist/cli/chunks/{chunk-YDPBCN7H.js → chunk-DPYNXEBC.js} +2 -2
- package/dist/cli/chunks/{chunk-LRJWKFGY.js → chunk-DS7AZD26.js} +2 -2
- package/dist/cli/chunks/{chunk-QZ2GQGJX.js → chunk-DZ7PWB6E.js} +2 -2
- package/dist/cli/chunks/{chunk-KO3WB4SU.js → chunk-DZZ4AJQI.js} +2 -2
- package/dist/cli/chunks/{chunk-H5TM4KIB.js → chunk-EBCUWMLX.js} +2 -2
- package/dist/cli/chunks/{chunk-7VM4ZUHT.js → chunk-ECGASTG7.js} +2 -2
- package/dist/cli/chunks/{chunk-LAY35POY.js → chunk-ED7MD6OI.js} +3 -3
- package/dist/cli/chunks/{chunk-CEMROADY.js → chunk-EHEFI6LR.js} +1 -1
- package/dist/cli/chunks/{chunk-XXCSJMSR.js → chunk-EXCU4J7T.js} +1 -1
- package/dist/cli/chunks/{chunk-27KNLVOY.js → chunk-EZ4GKHSI.js} +2 -2
- package/dist/cli/chunks/{chunk-G6LIQFT2.js → chunk-FJRRXCIS.js} +1 -1
- package/dist/cli/chunks/{chunk-ZP2GE6DM.js → chunk-FPKKKUWF.js} +1 -1
- package/dist/cli/chunks/{chunk-XY4JS3IZ.js → chunk-FZLCKIPP.js} +2 -2
- package/dist/cli/chunks/{chunk-LY6PTRVL.js → chunk-G6MPXBCD.js} +2 -2
- package/dist/cli/chunks/{chunk-YWG4LHFU.js → chunk-GBCDJJWH.js} +2 -2
- package/dist/cli/chunks/{chunk-DMUQV2YU.js → chunk-GCIL7PK7.js} +2 -2
- package/dist/cli/chunks/{chunk-H6MBRYA7.js → chunk-H2YOWAEB.js} +2 -2
- package/dist/cli/chunks/{chunk-I7UWFV6N.js → chunk-H6YFMUFG.js} +1 -1
- package/dist/cli/chunks/{chunk-WARFZ626.js → chunk-H7Y43HBQ.js} +1 -1
- package/dist/cli/chunks/{chunk-FV53RMVB.js → chunk-HRD5I7ES.js} +1 -1
- package/dist/cli/chunks/{chunk-C6UTRG66.js → chunk-IJHPZMEQ.js} +2 -2
- package/dist/cli/chunks/{chunk-4PYJCIRO.js → chunk-JVXPKHND.js} +2 -2
- package/dist/cli/chunks/{chunk-ZQYEBLTL.js → chunk-JWTMVC6E.js} +2 -2
- package/dist/cli/chunks/{chunk-NPT7BYGF.js → chunk-KHUN65Q3.js} +1 -1
- package/dist/cli/chunks/{chunk-CMVNYVKL.js → chunk-KTYESESI.js} +2 -2
- package/dist/cli/chunks/{chunk-AKZK46TQ.js → chunk-KULBMV6K.js} +2 -2
- package/dist/cli/chunks/{chunk-DU4GQKTH.js → chunk-KXRI4MR3.js} +2 -2
- package/dist/cli/chunks/{chunk-7XIQR6VU.js → chunk-L44XXD3X.js} +2 -2
- package/dist/cli/chunks/{chunk-WKIYYF3G.js → chunk-L6PH7JIE.js} +2 -2
- package/dist/cli/chunks/{chunk-FYY7OJ6Y.js → chunk-LGEZ3ZJX.js} +2 -2
- package/dist/cli/chunks/{chunk-I3AD523O.js → chunk-LKLWIP4Z.js} +1 -1
- package/dist/cli/chunks/{chunk-JDFF2QMZ.js → chunk-LMA6KEZH.js} +1 -1
- package/dist/cli/chunks/{chunk-QFJDR4HC.js → chunk-LW5TUN5F.js} +2 -2
- package/dist/cli/chunks/{chunk-FPZLOVEF.js → chunk-MU36VPXV.js} +1 -1
- package/dist/cli/chunks/{chunk-JSZNI3AO.js → chunk-MX5FMAY5.js} +1 -1
- package/dist/cli/chunks/{chunk-UQ6WB4N2.js → chunk-N2K2EQFH.js} +2 -2
- package/dist/cli/chunks/{chunk-P7MIOTVP.js → chunk-NBOEXSV2.js} +1 -1
- package/dist/cli/chunks/{chunk-2Q65LTJN.js → chunk-NJ2RY4OL.js} +2 -2
- package/dist/cli/chunks/{chunk-7KHZZVF2.js → chunk-NWUVXLBB.js} +4 -4
- package/dist/cli/chunks/{chunk-P3VRXQ3H.js → chunk-O7ZDQ5FF.js} +3 -3
- package/dist/cli/chunks/{chunk-7HYO76F2.js → chunk-OCACCUFO.js} +2 -2
- package/dist/cli/chunks/{chunk-MAXOIEUG.js → chunk-OFMVC6P3.js} +1 -1
- package/dist/cli/chunks/{chunk-NGE5YNKC.js → chunk-OQGELUM2.js} +2 -2
- package/dist/cli/chunks/{chunk-NIW4CLN2.js → chunk-OVEG5MEL.js} +2 -2
- package/dist/cli/chunks/{chunk-H3LGBH4Y.js → chunk-P4UGVVVX.js} +1 -1
- package/dist/cli/chunks/{chunk-UCXW24HY.js → chunk-PLQADRA6.js} +2 -2
- package/dist/cli/chunks/{chunk-5AFO7ZZG.js → chunk-PMHSTMHV.js} +3 -3
- package/dist/cli/chunks/{chunk-K426HTEQ.js → chunk-PSL53AQ4.js} +10 -10
- package/dist/cli/chunks/{chunk-LIEA5EON.js → chunk-PUK5NE47.js} +1 -1
- package/dist/cli/chunks/{chunk-K6IQBVD7.js → chunk-PUUGIBFF.js} +2 -2
- package/dist/cli/chunks/{chunk-G4CQBQBV.js → chunk-PW4GGJMP.js} +1 -1
- package/dist/cli/chunks/{chunk-527U4AHC.js → chunk-PY2Q6MN3.js} +6 -6
- package/dist/cli/chunks/{chunk-YGRY2TVI.js → chunk-Q2A2XQGF.js} +2 -2
- package/dist/cli/chunks/{chunk-OU52V67H.js → chunk-QCCXH5DK.js} +4 -4
- package/dist/cli/chunks/{chunk-UQBGA4UA.js → chunk-QPMISAWB.js} +1 -1
- package/dist/cli/chunks/{chunk-QZLTIGLB.js → chunk-REZ2GZQ3.js} +1 -1
- package/dist/cli/chunks/{chunk-3NCVUFAL.js → chunk-RRSUW2TK.js} +2 -2
- package/dist/cli/chunks/{chunk-LI3T5YNC.js → chunk-RWUGXU2K.js} +3 -3
- package/dist/cli/chunks/{chunk-H4ZPPHOI.js → chunk-RXN5DWVM.js} +2 -2
- package/dist/cli/chunks/{chunk-26ZMIYSK.js → chunk-S2T2BXUL.js} +2 -2
- package/dist/cli/chunks/{chunk-5KMGG3QW.js → chunk-S7KDHA6P.js} +4 -4
- package/dist/cli/chunks/{chunk-CAVBEZV4.js → chunk-SFDBIO64.js} +2 -2
- package/dist/cli/chunks/{chunk-ZWMXF6AX.js → chunk-SFGBC5RP.js} +2 -2
- package/dist/cli/chunks/{chunk-AK5Q2WCJ.js → chunk-SIAJP3YA.js} +2 -2
- package/dist/cli/chunks/{chunk-IQOCTGA2.js → chunk-SLU35IDJ.js} +2 -2
- package/dist/cli/chunks/{chunk-ZU3V4CJ4.js → chunk-SMHYPPO6.js} +2 -2
- package/dist/cli/chunks/{chunk-DPFLJMEI.js → chunk-SWRGPCZ2.js} +3 -3
- package/dist/cli/chunks/{chunk-76RO2RHG.js → chunk-UFZCHVLH.js} +1 -1
- package/dist/cli/chunks/{chunk-3KTOM7NN.js → chunk-UMWYL37S.js} +2 -2
- package/dist/cli/chunks/chunk-UNH2DE2G.js +2 -0
- package/dist/cli/chunks/{chunk-IXYF5BZY.js → chunk-UTGW75AZ.js} +2 -2
- package/dist/cli/chunks/{chunk-OC2W7KIW.js → chunk-VFEU4JM4.js} +2 -2
- package/dist/cli/chunks/{chunk-AAVUZVM6.js → chunk-VTDWQ7WI.js} +2 -2
- package/dist/cli/chunks/{chunk-XN4G3SRU.js → chunk-VUEYLW5P.js} +2 -2
- package/dist/cli/chunks/{chunk-JC4Z2ADP.js → chunk-WCVZHXWL.js} +2 -2
- package/dist/cli/chunks/{chunk-MN6W7ZNL.js → chunk-WLLGPGQY.js} +1 -1
- package/dist/cli/chunks/{chunk-7MKF52GT.js → chunk-WTKT2AD3.js} +2 -2
- package/dist/cli/chunks/{chunk-6SOGYNJG.js → chunk-WV66MXJI.js} +2 -2
- package/dist/cli/chunks/{chunk-4FTVTAMN.js → chunk-WYJFVSEB.js} +2 -2
- package/dist/cli/chunks/{chunk-ZRU3OZEU.js → chunk-XCSEJQXR.js} +2 -2
- package/dist/cli/chunks/{chunk-EIWZDVMT.js → chunk-XKUN5PDH.js} +3 -3
- package/dist/cli/chunks/{chunk-IMPSB5WW.js → chunk-YPRM6ZFL.js} +2 -2
- package/dist/cli/chunks/{chunk-ARUXFZDY.js → chunk-ZDPQB67L.js} +1 -1
- package/dist/cli/chunks/{chunk-LFXXA325.js → chunk-ZM7WOA3K.js} +1 -1
- package/dist/cli/chunks/{ci-SM3EVLZ4.js → ci-JW4O2J3W.js} +2 -2
- package/dist/cli/chunks/{ci-output-YYXICZBC.js → ci-output-JNXJV4B2.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-CV5UGKXT.js → circuit-breaker-XDD4KUGR.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-BSBUZ4B7.js → claude-flow-setup-L6IZOGYZ.js} +2 -2
- package/dist/cli/chunks/client-ADCDBTEE.js +2 -0
- package/dist/cli/chunks/{cline-installer-P2O6STIC.js → cline-installer-PK5SMN2B.js} +2 -2
- package/dist/cli/chunks/{code-M7DDLBGS.js → code-ZDVX3SQH.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-3QZIUYOG.js → code-index-extractor-VXZNKEU5.js} +2 -2
- package/dist/cli/chunks/{codex-installer-5JVZCCTC.js → codex-installer-OXKSIX7H.js} +2 -2
- package/dist/cli/chunks/{completions-EM7IL2BJ.js → completions-VRFFK223.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-VJXVB2CV.js → complexity-analyzer-FTIMV74J.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-RCKJIAEC.js → continuedev-installer-KTYBBPN4.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-DZ7LTDOZ.js → copilot-installer-WDC3YNUR.js} +2 -2
- package/dist/cli/chunks/core-handlers-HCACMLUW.js +2 -0
- package/dist/cli/chunks/{cost-tracker-QLOLXVAM.js → cost-tracker-6MH4H33B.js} +2 -2
- package/dist/cli/chunks/{coverage-LYHTLWRV.js → coverage-NHATLNS4.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-HXFQAU4M.js +2 -0
- package/dist/cli/chunks/{cursor-installer-PSIZ3Y53.js → cursor-installer-VQSUJDFB.js} +2 -2
- package/dist/cli/chunks/{daemon-YLOAXM4X.js → daemon-3VAOEKQW.js} +3 -3
- package/dist/cli/chunks/{daemon-IYDTMA5M.js → daemon-ZSK6CLQR.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-I2UIO3Z7.js → dag-attention-scheduler-HZ6OGYIH.js} +2 -2
- package/dist/cli/chunks/{detect-ZXQ7X7GZ.js → detect-CGU3SC63.js} +2 -2
- package/dist/cli/chunks/{dist-node-GK6OZX4H.js → dist-node-DIBQ7PTA.js} +2 -2
- package/dist/cli/chunks/{domain-handler-NS3IBLRQ.js → domain-handler-DCMGAYXS.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-5G4RZEWF.js → domain-transfer-UWFKBZTJ.js} +2 -2
- package/dist/cli/chunks/dream-SVWQH62A.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-V4JJUFR6.js → embed-and-insert-pattern-7247LAU3.js} +2 -2
- package/dist/cli/chunks/{eval-7Q6PPYKR.js → eval-6KR7TFOK.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-DUBKSYFM.js → experience-capture-middleware-IIOR6RVV.js} +3 -3
- package/dist/cli/chunks/{fast-paths-IDPPMBUW.js → fast-paths-M7OGD4ZI.js} +2 -2
- package/dist/cli/chunks/{feature-flags-EPTMAAKA.js → feature-flags-GGUXHRJI.js} +2 -2
- package/dist/cli/chunks/{feature-flags-KXI6FDY7.js → feature-flags-U75KFIGH.js} +2 -2
- package/dist/cli/chunks/{file-discovery-EDX2OJO7.js → file-discovery-V52AYEB7.js} +2 -2
- package/dist/cli/chunks/{fleet-67BO3LJ4.js → fleet-2UH72CK4.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-YARORYT7.js → gnn-wrapper-J2GDLT3P.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-K3JGPBYR.js → heartbeat-handler-QIDQHRXT.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-QW5TW5QS.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-D6EJWYAL.js +2 -0
- package/dist/cli/chunks/hnsw-index-4MWR4U5W.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-CDDRSV5E.js → hnsw-legacy-bridge-IU62PIY5.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-5JTP47LA.js → hnswlib-node-EBRXKEX5.js} +2 -2
- package/dist/cli/chunks/{hooks-6SCAE6LC.js → hooks-ZI4D3ATS.js} +10 -10
- package/dist/cli/chunks/hybrid-router-BYVUBHER.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-I3LUMO7I.js → hypergraph-engine-6JEERAGA.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-YAKAIVCN.js → hypergraph-handler-YMDGYCB6.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-OK2UIMSG.js +2 -0
- package/dist/cli/chunks/{init-handler-NBKCZD7Q.js → init-handler-N57NW3QI.js} +6 -6
- package/dist/cli/chunks/init-wizard-6NNPNS6J.js +2 -0
- package/dist/cli/chunks/kernel-F4A4GRNO.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-YGPJCPU3.js → kilocode-installer-7ABTGXJ5.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-JV3ONVMN.js → kiro-installer-2JFOHLVI.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-MSJDEZCF.js +2 -0
- package/dist/cli/chunks/{learning-2FEZJ5CX.js → learning-3P3ZXRGD.js} +3 -3
- package/dist/cli/chunks/{llm-router-SILI4KLU.js → llm-router-AWB2KHDW.js} +4 -4
- package/dist/cli/chunks/llm-router-service-27IQAO7G.js +2 -0
- package/dist/cli/chunks/{load-EGXLQVR3.js → load-GGVBCBGX.js} +2 -2
- package/dist/cli/chunks/load-test-TT5VLAN7.js +2 -0
- package/dist/cli/chunks/{mcp-OJH775TL.js → mcp-33NHIBN3.js} +2 -2
- package/dist/cli/chunks/{memory-FNEOK4FW.js → memory-IVAQS4OW.js} +5 -5
- package/dist/cli/chunks/memory-backend-FVSK53IM.js +2 -0
- package/dist/cli/chunks/{memory-handlers-6LDUH3JZ.js → memory-handlers-OPUDOZNT.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-ORTFWLLE.js → multi-model-executor-NWQY6IN2.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-UAQLW6XX.js → opencode-installer-FBB4JOEV.js} +2 -2
- package/dist/cli/chunks/{orchestrator-VE5KJ2V4.js → orchestrator-GDAXR7DH.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-7MVEDWCY.js +2 -0
- package/dist/cli/chunks/{pipeline-FNMDRWTU.js → pipeline-VIKAOIBE.js} +2 -2
- package/dist/cli/chunks/{platform-MGAKRUQN.js → platform-FFVP36LH.js} +2 -2
- package/dist/cli/chunks/{plugin-YX7THX3I.js → plugin-TI6QOLXH.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-XJV4RLMK.js → prime-radiant-advanced-wasm-AZRNI2OL.js} +2 -2
- package/dist/cli/chunks/protocol-executor-BLDDYEJ4.js +2 -0
- package/dist/cli/chunks/{protocol-handler-QFET442Y.js → protocol-handler-J4EA34B3.js} +2 -2
- package/dist/cli/chunks/{prove-QBAESCOC.js → prove-ADVRMAWS.js} +2 -2
- package/dist/cli/chunks/provider-manager-ZYCFRYZQ.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-P66CCPHM.js +2 -0
- package/dist/cli/chunks/{quality-ZTNRL6EG.js → quality-GB5SJFSD.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-LPHT3SX5.js +2 -0
- package/dist/cli/chunks/{real-embeddings-ZFFDV6HC.js → real-embeddings-GDRJ4XSH.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-J4LFL4AE.js → roocode-installer-Q6EISUDV.js} +2 -2
- package/dist/cli/chunks/router-XQ2TERUT.js +2 -0
- package/dist/cli/chunks/routing-feedback-K52O752B.js +2 -0
- package/dist/cli/chunks/{routing-handler-A5QG2TP2.js → routing-handler-RO4RTRAG.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-J5JL5WX5.js → ruvector-commands-FFIHCGVQ.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-H7442GMO.js → rvf-dual-writer-JGEK3A5Y.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-PTFQUYKC.js → rvf-migration-adapter-OVYC4QM6.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-RSNROYRX.js → rvf-migration-coordinator-U6L77QTS.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-G4DV7FK3.js +2 -0
- package/dist/cli/chunks/safe-db-TMSEITES.js +2 -0
- package/dist/cli/chunks/schedule-RWFLA43O.js +2 -0
- package/dist/cli/chunks/scheduler-2V55MJJR.js +2 -0
- package/dist/cli/chunks/{security-LHHLMCBA.js → security-QPQIDAIL.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-NPSHVUTM.js → shared-rvf-adapter-JRJTI4UD.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-INQDY5WE.js → shared-rvf-dual-writer-DSHGURDA.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-L7QM6IWF.js +2 -0
- package/dist/cli/chunks/{status-handler-R2KIAMAE.js → status-handler-SBT3MZTX.js} +2 -2
- package/dist/cli/chunks/{structural-health-2VPPIOZX.js → structural-health-UVECCN7U.js} +2 -2
- package/dist/cli/chunks/{sync-ASZ3T5GT.js → sync-XXIGTGCG.js} +2 -2
- package/dist/cli/chunks/{sync-NLASP7AK.js → sync-ZLZ4CZFJ.js} +2 -2
- package/dist/cli/chunks/{task-handler-UV5R6LJG.js → task-handler-73YAVOKJ.js} +2 -2
- package/dist/cli/chunks/{task-handlers-I6YJXPYP.js → task-handlers-PKECV27D.js} +3 -3
- package/dist/cli/chunks/{test-TE43TNTI.js → test-U3SXW4SV.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-WWWWF2TZ.js → test-scheduling-POJND3GV.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-HEWP7KKS.js → token-bootstrap-ICX6SIXJ.js} +2 -2
- package/dist/cli/chunks/{token-usage-3FVHUAW6.js → token-usage-WCHJUVGT.js} +2 -2
- package/dist/cli/chunks/{transformers-O5OFM4XM.js → transformers-L77UIHIY.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-YOYWFW63.js → tree-sitter-wasm-parser-CVAXURQP.js} +2 -2
- package/dist/cli/chunks/{types-42GR6PLO.js → types-LNVJBDM2.js} +2 -2
- package/dist/cli/chunks/unified-memory-ZSULA46X.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-SQEWFUBN.js +2 -0
- package/dist/cli/chunks/unified-persistence-EDCTT6SE.js +2 -0
- package/dist/cli/chunks/{upgrade-BU6DJ4LT.js → upgrade-4ND5RQFY.js} +2 -2
- package/dist/cli/chunks/{validate-MPTBARGN.js → validate-ZA4XT6K2.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-5LUQYHPP.js → validate-swarm-FNK3GCJ4.js} +2 -2
- package/dist/cli/chunks/{vibium-MJJDANDL.js → vibium-E2CK2GBQ.js} +2 -2
- package/dist/cli/chunks/visual-security-SOGAETFP.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-5TF4UGB3.js → web-tree-sitter-63VRNKZV.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-NQAOSVCN.js → windsurf-installer-5BTCVOLH.js} +2 -2
- package/dist/cli/chunks/{witness-chain-23UWK2JT.js → witness-chain-6CUUGISD.js} +2 -2
- package/dist/cli/chunks/witness-chain-AJCECBH5.js +2 -0
- package/dist/cli/chunks/{workflow-3QOLXRJC.js → workflow-V7ED22XT.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-UXRUCOZR.js +2 -0
- package/dist/cli/chunks/{wrappers-S6EUZBCX.js → wrappers-7S3NTTLW.js} +2 -2
- package/dist/feedback/regenerability-gate.d.ts +70 -0
- package/dist/feedback/regenerability-gate.js +91 -0
- package/dist/mcp/bundle.js +5 -5
- package/dist/shared/llm/providers/gemini.js +16 -10
- package/dist/shared/llm/providers/openrouter.js +20 -20
- package/dist/validation/conservation-guard.d.ts +39 -0
- package/dist/validation/conservation-guard.js +54 -0
- package/dist/validation/oracle-eval.d.ts +46 -0
- package/dist/validation/oracle-eval.js +108 -0
- package/dist/validation/skill-parity.d.ts +58 -0
- package/dist/validation/skill-parity.js +94 -0
- package/dist/validation/test-gen-prompt.d.ts +10 -0
- package/dist/validation/test-gen-prompt.js +26 -0
- package/package.json +8 -1
- package/dist/cli/chunks/adapter-LDNYC4GH.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-CA4CT5Q7.js +0 -2
- package/dist/cli/chunks/base-TSDAEMT4.js +0 -2
- package/dist/cli/chunks/browser-workflow-3HCTJBLR.js +0 -2
- package/dist/cli/chunks/chunk-72VVTMEL.js +0 -2
- package/dist/cli/chunks/client-WRDYZGM2.js +0 -2
- package/dist/cli/chunks/core-handlers-O6E5DNHT.js +0 -2
- package/dist/cli/chunks/cross-domain-router-EV7LQMDO.js +0 -2
- package/dist/cli/chunks/dream-E4C236UL.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-WMADLDKT.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-STRDGJ65.js +0 -2
- package/dist/cli/chunks/hnsw-index-DBHX3TSC.js +0 -2
- package/dist/cli/chunks/hybrid-router-L2K55I4T.js +0 -2
- package/dist/cli/chunks/impact-analyzer-WMO7ZGS7.js +0 -2
- package/dist/cli/chunks/init-wizard-ZAB7UZZS.js +0 -2
- package/dist/cli/chunks/kernel-4MUFDEQI.js +0 -2
- package/dist/cli/chunks/knowledge-graph-GZRFGXLX.js +0 -2
- package/dist/cli/chunks/llm-router-service-5ODLU5U5.js +0 -2
- package/dist/cli/chunks/load-test-ZDQFS5XS.js +0 -2
- package/dist/cli/chunks/memory-backend-UK7SQ6ZM.js +0 -2
- package/dist/cli/chunks/pattern-null-store-LO2QTIBU.js +0 -2
- package/dist/cli/chunks/protocol-executor-JWMYQEOI.js +0 -2
- package/dist/cli/chunks/provider-manager-PEXOHGNB.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-7B2G4UGQ.js +0 -2
- package/dist/cli/chunks/queen-coordinator-6OF4HT3S.js +0 -2
- package/dist/cli/chunks/router-GMWRF6DU.js +0 -2
- package/dist/cli/chunks/routing-feedback-XKJSQK3I.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-YEA6TMXB.js +0 -2
- package/dist/cli/chunks/safe-db-5DOP2J3V.js +0 -2
- package/dist/cli/chunks/schedule-SUWTOBHP.js +0 -2
- package/dist/cli/chunks/scheduler-P4VTC5SQ.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-5Z2RAXH7.js +0 -2
- package/dist/cli/chunks/unified-memory-HCKOPFAY.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-6NQPYA5C.js +0 -2
- package/dist/cli/chunks/unified-persistence-NIMKNAFR.js +0 -2
- package/dist/cli/chunks/visual-security-HFGHA57Z.js +0 -2
- package/dist/cli/chunks/witness-chain-VZGGJ7TJ.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-45L7D4SN.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v as L,w as M,x as N}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.3");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v as L,w as M,x as N}from"./chunk-6IHB3T6M.js";import{a as v,b as w,c as x,d as y,e as z,f as A,g as B,h as C,i as D,j as E,k as F,l as G,m as H,n as I,o as J,p as K}from"./chunk-22CUJA33.js";import"./chunk-JVXPKHND.js";import"./chunk-7FVWETN4.js";import"./chunk-UNH2DE2G.js";import"./chunk-7UOH55UT.js";import"./chunk-BA7PJS3Y.js";import"./chunk-G6MPXBCD.js";import"./chunk-UTGW75AZ.js";import"./chunk-LGEZ3ZJX.js";import"./chunk-DNOBN3IR.js";import"./chunk-2OUXYSQV.js";import"./chunk-WV66MXJI.js";import"./chunk-WTKT2AD3.js";import"./chunk-77QJQRL2.js";import"./chunk-36HTS4EP.js";import"./chunk-OVEG5MEL.js";import"./chunk-PLQADRA6.js";import"./chunk-L6PH7JIE.js";import"./chunk-PUK5NE47.js";export{z as GNNLayerFactory,i as QEFlashAttention,x as QEGNNEmbeddingIndex,y as QEGNNIndexFactory,a as QESONA,e as QE_FLASH_ATTENTION_CONFIG,g as QE_PERFORMANCE_TARGETS,f as QE_SONA_CONFIG,A as TensorCompressionFactory,u as batchComputeAttention,K as batchDifferentiableSearch,M as checkRuvectorPackagesAvailable,c as createDomainQESONA,j as createQEFlashAttention,b as createQESONA,D as getDifferentiableSearch,F as getGetCompressionLevel,E as getHierarchicalForward,G as getInit,h as getOptimalBlockConfig,k as getQEFlashAttentionConfig,n as getRuvectorDotProductAttention,m as getRuvectorFlashAttention,p as getRuvectorHyperbolicAttention,B as getRuvectorLayer,q as getRuvectorLinearAttention,r as getRuvectorMoEAttention,o as getRuvectorMultiHeadAttention,L as getRuvectorPackageVersions,C as getTensorCompress,l as getWorkloadTypes,N as initAllRuvectorPackages,w as initGNN,d as isAttentionAvailable,v as isGNNAvailable,s as toFloat32Array,H as toFloat32ArrayGNN,J as toIEmbedding,t as toNumberArrayAttn,I as toNumberArrayGNN};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regenerability Gate (ADR-113)
|
|
3
|
+
*
|
|
4
|
+
* Answers the Deletion Test per module: "if I deleted this module and
|
|
5
|
+
* regenerated it, how confident am I that a wrong rebuild would be caught?"
|
|
6
|
+
* Confidence comes from the oracle tier backing the module (durable > live >
|
|
7
|
+
* ephemeral > none) scaled by its mutation kill rate. The gate is warn-by-default
|
|
8
|
+
* and opt-in blocking so it never breaks an existing pipeline on adoption.
|
|
9
|
+
*
|
|
10
|
+
* Pure functions only — no I/O. Inputs (tier presence + mutation score) are
|
|
11
|
+
* produced upstream by the oracle eval runner and test-tier tagging.
|
|
12
|
+
*/
|
|
13
|
+
/** Which durability tier of test backs a module (see qe-test-generation SKILL.md). */
|
|
14
|
+
export type RegenerabilityTier = 'durable' | 'live' | 'ephemeral' | 'none';
|
|
15
|
+
export interface ModuleTestProfile {
|
|
16
|
+
module: string;
|
|
17
|
+
/** Mutation kill rate of the module's tests, 0..1. */
|
|
18
|
+
mutationScore: number;
|
|
19
|
+
/** Has >=1 durable test (invariant / contract / property at the boundary). */
|
|
20
|
+
hasDurable: boolean;
|
|
21
|
+
/** Has live checks (monitoring / drift / cost assertions). */
|
|
22
|
+
hasLive?: boolean;
|
|
23
|
+
/** Has ephemeral tests (example-based / mock-call). */
|
|
24
|
+
hasEphemeral?: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface RegenerabilityResult {
|
|
27
|
+
module: string;
|
|
28
|
+
tier: RegenerabilityTier;
|
|
29
|
+
/** 0..1 confidence that deleting + regenerating this module is safe. */
|
|
30
|
+
score: number;
|
|
31
|
+
reason: string;
|
|
32
|
+
}
|
|
33
|
+
export interface RegenerabilityGateConfig {
|
|
34
|
+
/** Minimum mutation kill rate per module. */
|
|
35
|
+
mutationScoreMin: number;
|
|
36
|
+
/** Minimum regenerability score per module. */
|
|
37
|
+
regenerabilityMin: number;
|
|
38
|
+
/** 'warn' reports but never fails CI; 'block' fails CI when thresholds are unmet. */
|
|
39
|
+
mode: 'warn' | 'block';
|
|
40
|
+
}
|
|
41
|
+
/** Non-blocking by default — adoption must not break existing pipelines. */
|
|
42
|
+
export declare const DEFAULT_REGENERABILITY_GATE: RegenerabilityGateConfig;
|
|
43
|
+
export interface RegenerabilityGateVerdict {
|
|
44
|
+
/** True when every module meets both thresholds. */
|
|
45
|
+
passed: boolean;
|
|
46
|
+
/** True only when the gate should fail CI: mode === 'block' AND not passed. */
|
|
47
|
+
blocking: boolean;
|
|
48
|
+
mode: 'warn' | 'block';
|
|
49
|
+
results: RegenerabilityResult[];
|
|
50
|
+
failures: Array<{
|
|
51
|
+
module: string;
|
|
52
|
+
reasons: string[];
|
|
53
|
+
}>;
|
|
54
|
+
summary: string;
|
|
55
|
+
}
|
|
56
|
+
/** Highest tier of test present on the module. Durable wins because it survives a rewrite. */
|
|
57
|
+
export declare function classifyTier(profile: ModuleTestProfile): RegenerabilityTier;
|
|
58
|
+
/**
|
|
59
|
+
* Regenerability = fault-detection (mutation score) discounted by how well the
|
|
60
|
+
* backing tests survive a reimplementation. Ephemeral tests are coupled to the
|
|
61
|
+
* current code, so even a high mutation score earns limited regeneration
|
|
62
|
+
* confidence; durable tests earn full confidence for their kill rate.
|
|
63
|
+
*/
|
|
64
|
+
export declare function regenerabilityScore(profile: ModuleTestProfile): RegenerabilityResult;
|
|
65
|
+
/**
|
|
66
|
+
* Evaluate the regenerability gate over a set of modules.
|
|
67
|
+
* `passed` reflects thresholds; `blocking` reflects whether CI should fail.
|
|
68
|
+
*/
|
|
69
|
+
export declare function evaluateRegenerabilityGate(profiles: ModuleTestProfile[], config?: RegenerabilityGateConfig): RegenerabilityGateVerdict;
|
|
70
|
+
//# sourceMappingURL=regenerability-gate.d.ts.map
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regenerability Gate (ADR-113)
|
|
3
|
+
*
|
|
4
|
+
* Answers the Deletion Test per module: "if I deleted this module and
|
|
5
|
+
* regenerated it, how confident am I that a wrong rebuild would be caught?"
|
|
6
|
+
* Confidence comes from the oracle tier backing the module (durable > live >
|
|
7
|
+
* ephemeral > none) scaled by its mutation kill rate. The gate is warn-by-default
|
|
8
|
+
* and opt-in blocking so it never breaks an existing pipeline on adoption.
|
|
9
|
+
*
|
|
10
|
+
* Pure functions only — no I/O. Inputs (tier presence + mutation score) are
|
|
11
|
+
* produced upstream by the oracle eval runner and test-tier tagging.
|
|
12
|
+
*/
|
|
13
|
+
/** Non-blocking by default — adoption must not break existing pipelines. */
|
|
14
|
+
export const DEFAULT_REGENERABILITY_GATE = {
|
|
15
|
+
mutationScoreMin: 0.6,
|
|
16
|
+
regenerabilityMin: 0.5,
|
|
17
|
+
mode: 'warn',
|
|
18
|
+
};
|
|
19
|
+
const round = (n) => Math.round(n * 10000) / 10000;
|
|
20
|
+
const clamp01 = (n) => Math.max(0, Math.min(1, n));
|
|
21
|
+
/** Highest tier of test present on the module. Durable wins because it survives a rewrite. */
|
|
22
|
+
export function classifyTier(profile) {
|
|
23
|
+
if (profile.hasDurable)
|
|
24
|
+
return 'durable';
|
|
25
|
+
if (profile.hasLive)
|
|
26
|
+
return 'live';
|
|
27
|
+
if (profile.hasEphemeral)
|
|
28
|
+
return 'ephemeral';
|
|
29
|
+
return 'none';
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Regenerability = fault-detection (mutation score) discounted by how well the
|
|
33
|
+
* backing tests survive a reimplementation. Ephemeral tests are coupled to the
|
|
34
|
+
* current code, so even a high mutation score earns limited regeneration
|
|
35
|
+
* confidence; durable tests earn full confidence for their kill rate.
|
|
36
|
+
*/
|
|
37
|
+
export function regenerabilityScore(profile) {
|
|
38
|
+
const tier = classifyTier(profile);
|
|
39
|
+
const mutation = clamp01(profile.mutationScore);
|
|
40
|
+
let score;
|
|
41
|
+
let reason;
|
|
42
|
+
switch (tier) {
|
|
43
|
+
case 'durable':
|
|
44
|
+
score = mutation;
|
|
45
|
+
reason = `durable tests kill ${(mutation * 100).toFixed(0)}% of mutants and survive a reimplementation`;
|
|
46
|
+
break;
|
|
47
|
+
case 'live':
|
|
48
|
+
score = mutation * 0.7;
|
|
49
|
+
reason = `live checks only; ${(mutation * 100).toFixed(0)}% mutation — add durable boundary tests for full confidence`;
|
|
50
|
+
break;
|
|
51
|
+
case 'ephemeral':
|
|
52
|
+
score = mutation * 0.4;
|
|
53
|
+
reason = `only ephemeral (example/mock) tests — coupled to the current implementation, would not survive a rewrite`;
|
|
54
|
+
break;
|
|
55
|
+
case 'none':
|
|
56
|
+
default:
|
|
57
|
+
score = 0;
|
|
58
|
+
reason = `no tests — deleting this module is unrecoverable (fails the Deletion Test)`;
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
return { module: profile.module, tier, score: round(score), reason };
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Evaluate the regenerability gate over a set of modules.
|
|
65
|
+
* `passed` reflects thresholds; `blocking` reflects whether CI should fail.
|
|
66
|
+
*/
|
|
67
|
+
export function evaluateRegenerabilityGate(profiles, config = DEFAULT_REGENERABILITY_GATE) {
|
|
68
|
+
const results = profiles.map(regenerabilityScore);
|
|
69
|
+
const failures = [];
|
|
70
|
+
for (let i = 0; i < profiles.length; i++) {
|
|
71
|
+
const p = profiles[i];
|
|
72
|
+
const r = results[i];
|
|
73
|
+
const reasons = [];
|
|
74
|
+
if (clamp01(p.mutationScore) < config.mutationScoreMin) {
|
|
75
|
+
reasons.push(`mutation score ${(clamp01(p.mutationScore) * 100).toFixed(0)}% < ${(config.mutationScoreMin * 100).toFixed(0)}%`);
|
|
76
|
+
}
|
|
77
|
+
if (r.score < config.regenerabilityMin) {
|
|
78
|
+
reasons.push(`regenerability ${(r.score * 100).toFixed(0)}% < ${(config.regenerabilityMin * 100).toFixed(0)}% (${r.tier})`);
|
|
79
|
+
}
|
|
80
|
+
if (reasons.length > 0)
|
|
81
|
+
failures.push({ module: p.module, reasons });
|
|
82
|
+
}
|
|
83
|
+
const passed = failures.length === 0;
|
|
84
|
+
const blocking = config.mode === 'block' && !passed;
|
|
85
|
+
const verb = passed ? 'PASS' : config.mode === 'block' ? 'FAIL (blocking)' : 'WARN (non-blocking)';
|
|
86
|
+
const summary = profiles.length === 0
|
|
87
|
+
? 'regenerability gate: no modules evaluated'
|
|
88
|
+
: `regenerability gate: ${verb} — ${profiles.length - failures.length}/${profiles.length} modules meet thresholds`;
|
|
89
|
+
return { passed, blocking, mode: config.mode, results, failures, summary };
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=regenerability-gate.js.map
|
package/dist/mcp/bundle.js
CHANGED
|
@@ -1466,13 +1466,13 @@ ${a.join(" | ")}`}function At(o){return`$${o.toFixed(2)}`}var HH,WH,Rle,Fv,pe,Cr
|
|
|
1466
1466
|
|
|
1467
1467
|
${e}`:e;if(l=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,prompt:y,stream:!1,options:{temperature:i,num_predict:n,stop:t?.stopSequences}})},t?.timeoutMs??this.config.timeoutMs??12e4),!l.ok)throw await this.handleApiError(l,r);let b=await l.json();u=b.response,d=b.prompt_eval_count??this.estimateTokens(y),p=b.eval_count??this.estimateTokens(u)}let m=Date.now()-a,g={promptTokens:d,completionTokens:p,totalTokens:d+p},h=st.calculateCost(r,g);return pe.recordTokenUsage(s,"ollama-provider","llm","generate",{inputTokens:d,outputTokens:p,totalTokens:d+p,estimatedCostUsd:h.totalCost}),{content:u,model:r,provider:"ollama",usage:g,cost:h,latencyMs:m,finishReason:"stop",cached:!1,requestId:s}}catch(l){throw l instanceof Error&&"code"in l?l:O(l instanceof Error?l.message:"Request failed","NETWORK_ERROR",{provider:"ollama",model:r,retryable:!0,cause:l})}}async embed(e,t){let r=t?.model??"all-MiniLM-L6-v2",n=Date.now();try{let i=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,prompt:e})},t?.timeoutMs??3e4),s=Date.now()-n;if(!i.ok)throw await this.handleApiError(i,r);return{embedding:(await i.json()).embedding,model:r,provider:"ollama",tokenCount:this.estimateTokens(e),latencyMs:s,cached:!1}}catch(i){throw i instanceof Error&&"code"in i?i:O(i instanceof Error?i.message:"Embedding request failed","NETWORK_ERROR",{provider:"ollama",model:r,retryable:!0,cause:i})}}async complete(e,t){let r=t?.model??this.selectCodeModel(),n=await this.generate(e,{model:r,temperature:t?.temperature??.1,maxTokens:t?.maxTokens??256,stopSequences:t?.stopSequences??[`
|
|
1468
1468
|
|
|
1469
|
-
`,"```","// ","# "]});return{completion:n.content,model:n.model,provider:"ollama",usage:n.usage,latencyMs:n.latencyMs,cached:n.cached}}getConfig(){return{...this.config}}getSupportedModels(){let e=["llama3","llama3.1","llama3.2","codellama","mistral","mixtral","phi3","qwen2","gemma","nomic-embed-text"],t=new Set([...e,...this.availableModels]);return Array.from(t)}getCostPerToken(){return{input:0,output:0}}async dispose(){}async pullModel(e){try{let t=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,stream:!1})},6e5);if(!t.ok){let r=await t.text();throw new Error(`Failed to pull model: ${r}`)}}catch(t){throw O(`Failed to pull model ${e}: ${t instanceof Error?t.message:"Unknown"}`,"MODEL_NOT_FOUND",{provider:"ollama",model:e,retryable:!0})}}getBaseUrl(){return(this.config.baseUrl??"http://localhost:11434").replace(/\/$/,"")}formatMessages(e,t){let r=[];t&&r.push({role:"system",content:t});for(let n of e)r.push({role:n.role,content:n.content});return r}selectCodeModel(){let e=["codellama","llama3.1","llama3","mistral"];for(let t of e)if(this.availableModels.some(r=>r===t||r.startsWith(t)))return t;return this.config.model}estimateTokens(e){return Math.ceil(e.length/4)}async handleApiError(e,t){let r=await e.text().catch(()=>"Unknown error");throw e.status===404?O(`Model '${t}' not found. Pull it with: ollama pull ${t}`,"MODEL_NOT_FOUND",{provider:"ollama",model:t,retryable:!1}):e.status===500?O(`Ollama server error: ${r}`,"PROVIDER_UNAVAILABLE",{provider:"ollama",model:t,retryable:!0,retryAfterMs:1e3}):O(`Ollama API error (${e.status}): ${r}`,"UNKNOWN",{provider:"ollama",model:t,retryable:!1})}async fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?O("Request timed out","TIMEOUT",{provider:"ollama",retryable:!0}):s}finally{clearTimeout(i)}}}});var Fle,Gv,Hv,n2=v(()=>{"use strict";$r();Cr();x();ma();B();Fle={model:"anthropic/claude-3.5-sonnet",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,baseUrl:"https://openrouter.ai/api/v1",allowFallback:!1},Gv={"anthropic/claude-3.5-sonnet":{input:3,output:15},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15},"anthropic/claude-3-opus":{input:15,output:75},"anthropic/claude-3-sonnet":{input:3,output:15},"anthropic/claude-3-haiku":{input:.25,output:1.25},"openai/gpt-4o":{input:5,output:15},"openai/gpt-4o-mini":{input:.15,output:.6},"openai/gpt-4-turbo":{input:10,output:30},"openai/gpt-3.5-turbo":{input:.5,output:1.5},"google/gemini-pro":{input:.125,output:.375},"google/gemini-pro-1.5":{input:3.5,output:10.5},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06},"mistralai/mistral-large":{input:2,output:6},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24},"mistralai/mistral-7b-instruct":{input:.06,output:.06},default:{input:1,output:3}},Hv=class{type="
|
|
1470
|
-
`);b=z.pop()||"";for(let q of z){let ee=q.trim();if(!(!ee||ee==="data: [DONE]")&&ee.startsWith("data: "))try{let te=k(ee.slice(6)),xe=te.choices[0]?.delta;xe?.content&&(p+=xe.content,yield xe.content),te.choices[0]?.finish_reason&&(m=this.mapFinishReason(te.choices[0].finish_reason)),te.model&&(g=te.model)}catch{}}}}finally{h.releaseLock()}let C=Date.now()-l,E=Math.ceil(JSON.stringify(n).length/4),A=Math.ceil(p.length/4),P={promptTokens:E,completionTokens:A,totalTokens:E+A},M=this.calculateCost(i,P);return pe.recordTokenUsage(c,"openrouter-provider","llm","generate-stream",{inputTokens:P.promptTokens,outputTokens:P.completionTokens,totalTokens:P.totalTokens,estimatedCostUsd:M.totalCost}),{content:p,model:g,provider:"
|
|
1469
|
+
`,"```","// ","# "]});return{completion:n.content,model:n.model,provider:"ollama",usage:n.usage,latencyMs:n.latencyMs,cached:n.cached}}getConfig(){return{...this.config}}getSupportedModels(){let e=["llama3","llama3.1","llama3.2","codellama","mistral","mixtral","phi3","qwen2","gemma","nomic-embed-text"],t=new Set([...e,...this.availableModels]);return Array.from(t)}getCostPerToken(){return{input:0,output:0}}async dispose(){}async pullModel(e){try{let t=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,stream:!1})},6e5);if(!t.ok){let r=await t.text();throw new Error(`Failed to pull model: ${r}`)}}catch(t){throw O(`Failed to pull model ${e}: ${t instanceof Error?t.message:"Unknown"}`,"MODEL_NOT_FOUND",{provider:"ollama",model:e,retryable:!0})}}getBaseUrl(){return(this.config.baseUrl??"http://localhost:11434").replace(/\/$/,"")}formatMessages(e,t){let r=[];t&&r.push({role:"system",content:t});for(let n of e)r.push({role:n.role,content:n.content});return r}selectCodeModel(){let e=["codellama","llama3.1","llama3","mistral"];for(let t of e)if(this.availableModels.some(r=>r===t||r.startsWith(t)))return t;return this.config.model}estimateTokens(e){return Math.ceil(e.length/4)}async handleApiError(e,t){let r=await e.text().catch(()=>"Unknown error");throw e.status===404?O(`Model '${t}' not found. Pull it with: ollama pull ${t}`,"MODEL_NOT_FOUND",{provider:"ollama",model:t,retryable:!1}):e.status===500?O(`Ollama server error: ${r}`,"PROVIDER_UNAVAILABLE",{provider:"ollama",model:t,retryable:!0,retryAfterMs:1e3}):O(`Ollama API error (${e.status}): ${r}`,"UNKNOWN",{provider:"ollama",model:t,retryable:!1})}async fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?O("Request timed out","TIMEOUT",{provider:"ollama",retryable:!0}):s}finally{clearTimeout(i)}}}});var Fle,Gv,Hv,n2=v(()=>{"use strict";$r();Cr();x();ma();B();Fle={model:"anthropic/claude-3.5-sonnet",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,baseUrl:"https://openrouter.ai/api/v1",allowFallback:!1},Gv={"anthropic/claude-3.5-sonnet":{input:3,output:15},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15},"anthropic/claude-3-opus":{input:15,output:75},"anthropic/claude-3-sonnet":{input:3,output:15},"anthropic/claude-3-haiku":{input:.25,output:1.25},"openai/gpt-4o":{input:5,output:15},"openai/gpt-4o-mini":{input:.15,output:.6},"openai/gpt-4-turbo":{input:10,output:30},"openai/gpt-3.5-turbo":{input:.5,output:1.5},"google/gemini-pro":{input:.125,output:.375},"google/gemini-pro-1.5":{input:3.5,output:10.5},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06},"mistralai/mistral-large":{input:2,output:6},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24},"mistralai/mistral-7b-instruct":{input:.06,output:.06},default:{input:1,output:3}},Hv=class{type="openrouter";name="OpenRouter";config;requestId=0;cachedModels=null;constructor(e={}){this.config={...Fle,...e}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set OPENROUTER_API_KEY environment variable."};let t=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/models`,{method:"GET",headers:this.getHeaders()},5e3),n=Date.now()-t;if(!r.ok){let a=await r.text();return{healthy:!1,latencyMs:n,error:`API error: ${r.status} - ${a}`}}let s=(await r.json()).data?.map(a=>a.id)||[];return this.cachedModels=s,{healthy:!0,latencyMs:n,models:s.slice(0,20),details:{totalModels:s.length,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(e,t){if(!this.getApiKey())throw O("OpenRouter API key not configured","API_KEY_MISSING",{provider:"openrouter",retryable:!1});let n=this.formatMessages(e,t?.systemPrompt),i=t?.model??this.config.model,s=t?.maxTokens??this.config.maxTokens??4096,a=t?.temperature??this.config.temperature??.7,c=`openrouter-${++this.requestId}-${Date.now()}`,l=Date.now(),u={model:i,max_tokens:s,temperature:a,messages:n};t?.stopSequences&&t.stopSequences.length>0&&(u.stop=t.stopSequences),this.config.allowFallback!==void 0&&(u.route=this.config.allowFallback?"fallback":void 0),this.config.forceProvider&&(u.provider={order:[this.config.forceProvider]});try{let d=await this.fetchWithRetry(`${this.getBaseUrl()}/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(u)},t?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),p=Date.now()-l;if(!d.ok){let b=await d.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(d.status,b,i)}let m=await d.json(),g={promptTokens:m.usage?.prompt_tokens??0,completionTokens:m.usage?.completion_tokens??0,totalTokens:m.usage?.total_tokens??0},h=this.calculateCost(i,g);return pe.recordTokenUsage(c,"openrouter-provider","llm","generate",{inputTokens:g.promptTokens,outputTokens:g.completionTokens,totalTokens:g.totalTokens,estimatedCostUsd:h.totalCost}),{content:m.choices[0]?.message?.content??"",model:m.model,provider:"openrouter",usage:g,cost:h,latencyMs:p,finishReason:this.mapFinishReason(m.choices[0]?.finish_reason),cached:!1,requestId:c}}catch(d){throw d instanceof Error&&"code"in d?d:O(d instanceof Error?d.message:"Request failed","NETWORK_ERROR",{provider:"openrouter",model:i,retryable:!0,cause:d})}}async*generateStream(e,t){if(!this.getApiKey())throw O("OpenRouter API key not configured","API_KEY_MISSING",{provider:"openrouter",retryable:!1});let n=this.formatMessages(e,t?.systemPrompt),i=t?.model??this.config.model,s=t?.maxTokens??this.config.maxTokens??4096,a=t?.temperature??this.config.temperature??.7,c=`openrouter-stream-${++this.requestId}-${Date.now()}`,l=Date.now(),u={model:i,max_tokens:s,temperature:a,messages:n,stream:!0};t?.stopSequences&&t.stopSequences.length>0&&(u.stop=t.stopSequences);let d=await this.fetchWithTimeout(`${this.getBaseUrl()}/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(u)},t?.timeoutMs??this.config.timeoutMs??6e4);if(!d.ok){let D=await d.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(d.status,D,i)}if(!d.body)throw O("No response body for streaming","NETWORK_ERROR",{provider:"openrouter",model:i,retryable:!0});let p="",m="stop",g=i,h=d.body.getReader(),y=new TextDecoder,b="";try{for(;;){let{done:D,value:$}=await h.read();if(D)break;b+=y.decode($,{stream:!0});let z=b.split(`
|
|
1470
|
+
`);b=z.pop()||"";for(let q of z){let ee=q.trim();if(!(!ee||ee==="data: [DONE]")&&ee.startsWith("data: "))try{let te=k(ee.slice(6)),xe=te.choices[0]?.delta;xe?.content&&(p+=xe.content,yield xe.content),te.choices[0]?.finish_reason&&(m=this.mapFinishReason(te.choices[0].finish_reason)),te.model&&(g=te.model)}catch{}}}}finally{h.releaseLock()}let C=Date.now()-l,E=Math.ceil(JSON.stringify(n).length/4),A=Math.ceil(p.length/4),P={promptTokens:E,completionTokens:A,totalTokens:E+A},M=this.calculateCost(i,P);return pe.recordTokenUsage(c,"openrouter-provider","llm","generate-stream",{inputTokens:P.promptTokens,outputTokens:P.completionTokens,totalTokens:P.totalTokens,estimatedCostUsd:M.totalCost}),{content:p,model:g,provider:"openrouter",usage:P,cost:M,latencyMs:C,finishReason:m,cached:!1,requestId:c}}async embed(e,t){if(!this.getApiKey())throw O("OpenRouter API key not configured","API_KEY_MISSING",{provider:"openrouter",retryable:!1});let n=t?.model??"openai/text-embedding-3-small",i=Date.now();try{let s=await this.fetchWithTimeout(`${this.getBaseUrl()}/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:n,input:e})},t?.timeoutMs??this.config.timeoutMs??3e4),a=Date.now()-i;if(!s.ok){let l=await s.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(s.status,l,n)}let c=await s.json();return{embedding:c.data[0].embedding,model:c.model,provider:"openrouter",tokenCount:c.usage.total_tokens,latencyMs:a,cached:!1}}catch(s){throw s instanceof Error&&"code"in s?s:O(s instanceof Error?s.message:"Embedding request failed","NETWORK_ERROR",{provider:"openrouter",model:n,retryable:!0,cause:s})}}async complete(e,t){let r=await this.generate(e,{model:t?.model,temperature:t?.temperature??.2,maxTokens:t?.maxTokens??256,stopSequences:t?.stopSequences??[`
|
|
1471
1471
|
|
|
1472
|
-
`]});return{completion:r.content,model:r.model,provider:"
|
|
1472
|
+
`]});return{completion:r.content,model:r.model,provider:"openrouter",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return this.cachedModels?this.cachedModels:["anthropic/claude-3.5-sonnet","anthropic/claude-3-opus","anthropic/claude-3-sonnet","anthropic/claude-3-haiku","openai/gpt-4o","openai/gpt-4o-mini","openai/gpt-4-turbo","openai/gpt-3.5-turbo","google/gemini-pro","google/gemini-pro-1.5","meta-llama/llama-3.1-70b-instruct","meta-llama/llama-3.1-8b-instruct","mistralai/mistral-large","mistralai/mixtral-8x7b-instruct"]}getCostPerToken(){let e=Gv[this.config.model]||Gv.default;return{input:e.input/1e6,output:e.output/1e6}}async dispose(){this.cachedModels=null}calculateCost(e,t){let r=Gv[e]||Gv.default,n=t.promptTokens/1e6*r.input,i=t.completionTokens/1e6*r.output;return{inputCost:n,outputCost:i,totalCost:n+i,currency:"USD"}}getApiKey(){return this.config.apiKey??process.env.OPENROUTER_API_KEY}getBaseUrl(){return(this.config.baseUrl??"https://openrouter.ai/api/v1").replace(/\/$/,"")}getHeaders(){let e={"Content-Type":"application/json",Authorization:`Bearer ${this.getApiKey()}`};return this.config.siteUrl&&(e["HTTP-Referer"]=this.config.siteUrl),this.config.siteName&&(e["X-Title"]=this.config.siteName),e}formatMessages(e,t){let r=[];if(typeof e=="string")t&&r.push({role:"system",content:t}),r.push({role:"user",content:e});else{let n=e.some(i=>i.role==="system");t&&!n&&r.push({role:"system",content:t});for(let i of e)r.push({role:i.role,content:i.content})}return r}mapFinishReason(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content_filter";case"tool_calls":return"stop";default:return"stop"}}handleApiError(e,t,r){let n=t.error?.message??"Unknown API error",i=t.error?.type??"",s=t.error?.code;switch(e){case 401:throw O(n,"API_KEY_INVALID",{provider:"openrouter",model:r,retryable:!1});case 402:throw O(n,"COST_LIMIT_EXCEEDED",{provider:"openrouter",model:r,retryable:!1});case 429:throw O(n,"RATE_LIMITED",{provider:"openrouter",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw s==="context_length_exceeded"||i==="invalid_request_error"?O(n,"CONTEXT_LENGTH_EXCEEDED",{provider:"openrouter",model:r,retryable:!1}):O(n,"UNKNOWN",{provider:"openrouter",model:r,retryable:!1});case 404:throw O(n,"MODEL_NOT_FOUND",{provider:"openrouter",model:r,retryable:!1});case 500:case 502:case 503:throw O(n,"PROVIDER_UNAVAILABLE",{provider:"openrouter",model:r,retryable:!0,retryAfterMs:5e3});default:throw O(n,"UNKNOWN",{provider:"openrouter",model:r,retryable:!1})}}async fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?O("Request timed out","TIMEOUT",{provider:"openrouter",retryable:!0}):s}finally{clearTimeout(i)}}async fetchWithRetry(e,t,r,n){let i;for(let s=0;s<n;s++)try{let a=await this.fetchWithTimeout(e,t,r);if(a.status>=400&&a.status<500&&a.status!==429)return a;if((a.status>=500||a.status===429)&&s<n-1){let c=at(s);await this.sleep(c);continue}return a}catch(a){if(i=S(a),s<n-1){let c=at(s);await this.sleep(c)}}throw i??new Error("Request failed after retries")}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var Nle,Wv,jv,i2=v(()=>{"use strict";$r();Cr();x();ma();B();Nle={model:"gemini-2.5-flash",maxTokens:8192,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,baseUrl:"https://generativelanguage.googleapis.com/v1beta",safetyThreshold:"BLOCK_MEDIUM_AND_ABOVE"},Wv={"gemini-pro":{input:.5,output:1.5},"gemini-1.0-pro":{input:.5,output:1.5},"gemini-1.5-pro":{input:3.5,output:10.5},"gemini-1.5-pro-latest":{input:3.5,output:10.5},"gemini-1.5-flash":{input:.075,output:.3},"gemini-1.5-flash-latest":{input:.075,output:.3},"gemini-2.0-flash-exp":{input:.075,output:.3},"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.3,output:2.5},"gemini-flash-latest":{input:.3,output:2.5},"gemini-ultra":{input:7,output:21},"gemini-1.0-ultra":{input:7,output:21},default:{input:1,output:3}},jv=class{type="gemini";name="Google Gemini";config;requestId=0;cachedModels=null;constructor(e={}){this.config={...Nle,...e}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){let e=this.getApiKey();if(!e)return{healthy:!1,error:"API key not configured. Set GOOGLE_AI_API_KEY, GEMINI_API_KEY, or GOOGLE_API_KEY environment variable."};let t=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/models?key=${e}`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3),n=Date.now()-t;if(!r.ok){let a=await r.text();return{healthy:!1,latencyMs:n,error:`API error: ${r.status} - ${a}`}}let s=(await r.json()).models?.filter(a=>a.supportedGenerationMethods?.includes("generateContent")).map(a=>a.name.replace("models/",""))||[];return this.cachedModels=s,{healthy:!0,latencyMs:n,models:s.slice(0,20),details:{totalModels:s.length,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(e,t){let r=this.getApiKey();if(!r)throw O("Gemini API key not configured","API_KEY_MISSING",{provider:"gemini",retryable:!1});let n=this.formatContents(e),i=t?.model??this.config.model,s=t?.maxTokens??this.config.maxTokens??8192,a=t?.temperature??this.config.temperature??.7,c=`gemini-${++this.requestId}-${Date.now()}`,l=Date.now(),u={contents:n,generationConfig:{maxOutputTokens:s,temperature:a,topP:this.config.topP}};t?.systemPrompt&&(u.systemInstruction={parts:[{text:t.systemPrompt}]}),t?.stopSequences&&t.stopSequences.length>0&&(u.generationConfig.stopSequences=t.stopSequences);try{let d=await this.fetchWithRetry(`${this.getBaseUrl()}/models/${i}:generateContent?key=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)},t?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),p=Date.now()-l;if(!d.ok){let b=await d.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(d.status,b,i)}let m=await d.json(),g={promptTokens:m.usageMetadata?.promptTokenCount??0,completionTokens:m.usageMetadata?.candidatesTokenCount??0,totalTokens:m.usageMetadata?.totalTokenCount??0},h=this.calculateCost(i,g);return pe.recordTokenUsage(c,"gemini-provider","llm","generate",{inputTokens:g.promptTokens,outputTokens:g.completionTokens,totalTokens:g.totalTokens,estimatedCostUsd:h.totalCost}),{content:m.candidates[0]?.content?.parts?.map(b=>b.text??"").join("")??"",model:m.modelVersion??i,provider:"gemini",usage:g,cost:h,latencyMs:p,finishReason:this.mapFinishReason(m.candidates[0]?.finishReason),cached:!1,requestId:c}}catch(d){throw d instanceof Error&&"code"in d?d:O(d instanceof Error?d.message:"Request failed","NETWORK_ERROR",{provider:"gemini",model:i,retryable:!0,cause:d})}}async*generateStream(e,t){let r=this.getApiKey();if(!r)throw O("Gemini API key not configured","API_KEY_MISSING",{provider:"gemini",retryable:!1});let n=this.formatContents(e),i=t?.model??this.config.model,s=t?.maxTokens??this.config.maxTokens??8192,a=t?.temperature??this.config.temperature??.7,c=`gemini-stream-${++this.requestId}-${Date.now()}`,l=Date.now(),u={contents:n,generationConfig:{maxOutputTokens:s,temperature:a}};t?.systemPrompt&&(u.systemInstruction={parts:[{text:t.systemPrompt}]});let d=await this.fetchWithTimeout(`${this.getBaseUrl()}/models/${i}:streamGenerateContent?key=${r}&alt=sse`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)},t?.timeoutMs??this.config.timeoutMs??6e4);if(!d.ok){let P=await d.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(d.status,P,i)}if(!d.body)throw O("No response body for streaming","NETWORK_ERROR",{provider:"gemini",model:i,retryable:!0});let p="",m="stop",g={promptTokens:0,completionTokens:0,totalTokens:0},h=d.body.getReader(),y=new TextDecoder,b="";try{for(;;){let{done:P,value:M}=await h.read();if(P)break;b+=y.decode(M,{stream:!0});let D=b.split(`
|
|
1473
1473
|
`);b=D.pop()||"";for(let $ of D){let z=$.trim();if(!(!z||!z.startsWith("data: ")))try{let q=k(z.slice(6)),ee=q.candidates?.[0]?.content?.parts?.map(te=>te.text??"").join("")??"";ee&&(p+=ee,yield ee),q.candidates?.[0]?.finishReason&&(m=this.mapFinishReason(q.candidates[0].finishReason)),q.usageMetadata&&(g={promptTokens:q.usageMetadata.promptTokenCount,completionTokens:q.usageMetadata.candidatesTokenCount,totalTokens:q.usageMetadata.totalTokenCount})}catch{}}}}finally{h.releaseLock()}let C=Date.now()-l,E=g.totalTokens>0?g:{promptTokens:Math.ceil(JSON.stringify(n).length/4),completionTokens:Math.ceil(p.length/4),totalTokens:0};E.totalTokens=E.promptTokens+E.completionTokens;let A=this.calculateCost(i,E);return pe.recordTokenUsage(c,"gemini-provider","llm","generate-stream",{inputTokens:E.promptTokens,outputTokens:E.completionTokens,totalTokens:E.totalTokens,estimatedCostUsd:A.totalCost}),{content:p,model:i,provider:"gemini",usage:E,cost:A,latencyMs:C,finishReason:m,cached:!1,requestId:c}}async embed(e,t){let r=this.getApiKey();if(!r)throw O("Gemini API key not configured","API_KEY_MISSING",{provider:"gemini",retryable:!1});let n=t?.model??"text-embedding-004",i=Date.now();try{let s=await this.fetchWithTimeout(`${this.getBaseUrl()}/models/${n}:embedContent?key=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:{parts:[{text:e}]}})},t?.timeoutMs??this.config.timeoutMs??3e4),a=Date.now()-i;if(!s.ok){let l=await s.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(s.status,l,n)}return{embedding:(await s.json()).embedding.values,model:n,provider:"gemini",tokenCount:Math.ceil(e.length/4),latencyMs:a,cached:!1}}catch(s){throw s instanceof Error&&"code"in s?s:O(s instanceof Error?s.message:"Embedding request failed","NETWORK_ERROR",{provider:"gemini",model:n,retryable:!0,cause:s})}}async complete(e,t){let r=await this.generate(e,{model:t?.model,temperature:t?.temperature??.2,maxTokens:t?.maxTokens??256,stopSequences:t?.stopSequences??[`
|
|
1474
1474
|
|
|
1475
|
-
`]});return{completion:r.content,model:r.model,provider:"gemini",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return this.cachedModels?this.cachedModels:["gemini-pro","gemini-
|
|
1475
|
+
`]});return{completion:r.content,model:r.model,provider:"gemini",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return this.cachedModels?this.cachedModels:["gemini-flash-latest","gemini-pro-latest","gemini-flash-lite-latest","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-3.5-flash"]}getCostPerToken(){let e=Wv[this.config.model]||Wv.default;return{input:e.input/1e6,output:e.output/1e6}}async dispose(){this.cachedModels=null}calculateCost(e,t){let r=Wv[e]||Wv.default,n=t.promptTokens/1e6*r.input,i=t.completionTokens/1e6*r.output;return{inputCost:n,outputCost:i,totalCost:n+i,currency:"USD"}}getApiKey(){return this.config.apiKey??process.env.GOOGLE_AI_API_KEY??process.env.GEMINI_API_KEY??process.env.GOOGLE_API_KEY}getBaseUrl(){return(this.config.baseUrl??"https://generativelanguage.googleapis.com/v1beta").replace(/\/$/,"")}formatContents(e){return typeof e=="string"?[{role:"user",parts:[{text:e}]}]:e.filter(t=>t.role!=="system").map(t=>({role:t.role==="assistant"?"model":"user",parts:[{text:t.content}]}))}mapFinishReason(e){switch(e){case"STOP":return"stop";case"MAX_TOKENS":return"length";case"SAFETY":return"content_filter";case"RECITATION":return"content_filter";default:return"stop"}}handleApiError(e,t,r){let n=t.error?.message??"Unknown API error";switch(e){case 400:throw n.includes("token")||n.includes("length")||n.includes("exceeds")?O(n,"CONTEXT_LENGTH_EXCEEDED",{provider:"gemini",model:r,retryable:!1}):n.includes("API key")?O(n,"API_KEY_INVALID",{provider:"gemini",model:r,retryable:!1}):O(n,"UNKNOWN",{provider:"gemini",model:r,retryable:!1});case 401:case 403:throw O(n,"API_KEY_INVALID",{provider:"gemini",model:r,retryable:!1});case 404:throw O(n,"MODEL_NOT_FOUND",{provider:"gemini",model:r,retryable:!1});case 429:throw O(n,"RATE_LIMITED",{provider:"gemini",model:r,retryable:!0,retryAfterMs:6e4});case 500:case 502:case 503:throw O(n,"PROVIDER_UNAVAILABLE",{provider:"gemini",model:r,retryable:!0,retryAfterMs:5e3});default:throw O(n,"UNKNOWN",{provider:"gemini",model:r,retryable:!1})}}async fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?O("Request timed out","TIMEOUT",{provider:"gemini",retryable:!0}):s}finally{clearTimeout(i)}}async fetchWithRetry(e,t,r,n){let i;for(let s=0;s<n;s++)try{let a=await this.fetchWithTimeout(e,t,r);if(a.status>=400&&a.status<500&&a.status!==429)return a;if((a.status>=500||a.status===429)&&s<n-1){let c=at(s);await this.sleep(c);continue}return a}catch(a){if(i=S(a),s<n-1){let c=at(s);await this.sleep(c)}}throw i??new Error("Request failed after retries")}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var $le,Qv,s2=v(()=>{"use strict";$r();vn();Cr();x();ma();$le={model:"gpt-4o",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,apiVersion:"2024-02-15-preview"},Qv=class{type="azure-openai";name="Azure OpenAI";config;requestId=0;constructor(e){this.config={...$le,...e}}async isAvailable(){let e=this.getEndpoint(),t=this.getApiKey()||this.getAzureAdToken();if(!e||!t||!this.config.deploymentId)return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){let e=this.getEndpoint(),t=this.getApiKey()||this.getAzureAdToken();if(!e)return{healthy:!1,error:"Azure endpoint not configured. Set AZURE_OPENAI_ENDPOINT environment variable."};if(!t)return{healthy:!1,error:"Azure authentication not configured. Set AZURE_OPENAI_API_KEY or provide azureAdToken."};if(!this.config.deploymentId)return{healthy:!1,error:"Deployment ID not configured. Set AZURE_OPENAI_DEPLOYMENT or provide deploymentId."};let r=Date.now();try{let n=await this.fetchWithTimeout(this.buildUrl("chat/completions"),{method:"POST",headers:this.getHeaders(),body:JSON.stringify({max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),i=Date.now()-r;if(!n.ok){let s=await n.text();return{healthy:!1,latencyMs:i,error:`API error: ${n.status} - ${s}`}}return{healthy:!0,latencyMs:i,models:this.getSupportedModels(),details:{endpoint:this.getEndpoint(),deploymentId:this.config.deploymentId,apiVersion:this.config.apiVersion,authType:this.getAzureAdToken()?"Azure AD":"API Key"}}}catch(n){return{healthy:!1,error:n instanceof Error?n.message:"Unknown error"}}}async generate(e,t){let r=this.getEndpoint(),n=this.getApiKey()||this.getAzureAdToken();if(!r||!n)throw O("Azure OpenAI not configured","API_KEY_MISSING",{provider:"azure-openai",retryable:!1});let i=this.formatMessages(e,t?.systemPrompt),s=t?.model??this.config.model??"gpt-4o",a=t?.maxTokens??this.config.maxTokens??4096,c=t?.temperature??this.config.temperature??.7,l=`azure-openai-${++this.requestId}-${Date.now()}`,u=Date.now(),d={max_tokens:a,temperature:c,messages:i};t?.stopSequences&&t.stopSequences.length>0&&(d.stop=t.stopSequences),this.config.presencePenalty!==void 0&&(d.presence_penalty=this.config.presencePenalty),this.config.frequencyPenalty!==void 0&&(d.frequency_penalty=this.config.frequencyPenalty);try{let p=await this.fetchWithRetry(this.buildUrl("chat/completions"),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(d)},t?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),m=Date.now()-u;if(!p.ok){let C=await p.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(p.status,C,s)}let g=await p.json(),h={promptTokens:g.usage.prompt_tokens,completionTokens:g.usage.completion_tokens,totalTokens:g.usage.total_tokens},y=st.calculateCost(s,h);return pe.recordTokenUsage(l,"azure-openai-provider","llm","generate",{inputTokens:g.usage.prompt_tokens,outputTokens:g.usage.completion_tokens,totalTokens:g.usage.total_tokens,estimatedCostUsd:y.totalCost}),{content:g.choices[0]?.message?.content??"",model:g.model,provider:"azure-openai",usage:h,cost:y,latencyMs:m,finishReason:this.mapFinishReason(g.choices[0]?.finish_reason),cached:!1,requestId:l}}catch(p){throw p instanceof Error&&"code"in p?p:O(p instanceof Error?p.message:"Request failed","NETWORK_ERROR",{provider:"azure-openai",model:s,retryable:!0,cause:p})}}async embed(e,t){let r=this.getEndpoint(),n=this.getApiKey()||this.getAzureAdToken();if(!r||!n)throw O("Azure OpenAI not configured","API_KEY_MISSING",{provider:"azure-openai",retryable:!1});let i=t?.model??this.config.deploymentId,s=Date.now();try{let a=await this.fetchWithTimeout(this.buildUrl("embeddings",i),{method:"POST",headers:this.getHeaders(),body:JSON.stringify({input:e})},t?.timeoutMs??this.config.timeoutMs??3e4),c=Date.now()-s;if(!a.ok){let u=await a.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(a.status,u,i)}let l=await a.json();return{embedding:l.data[0].embedding,model:l.model,provider:"azure-openai",tokenCount:l.usage.total_tokens,latencyMs:c,cached:!1}}catch(a){throw a instanceof Error&&"code"in a?a:O(a instanceof Error?a.message:"Embedding request failed","NETWORK_ERROR",{provider:"azure-openai",model:i,retryable:!0,cause:a})}}async complete(e,t){let r=await this.generate(e,{model:t?.model,temperature:t?.temperature??.2,maxTokens:t?.maxTokens??256,stopSequences:t?.stopSequences??[`
|
|
1476
1476
|
|
|
1477
1477
|
`]});return{completion:r.content,model:r.model,provider:"azure-openai",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-4","gpt-35-turbo","text-embedding-ada-002","text-embedding-3-small","text-embedding-3-large"]}getCostPerToken(){return st.getCostPerToken(this.config.model??"gpt-4o")}async dispose(){}getApiKey(){return this.config.apiKey??process.env.AZURE_OPENAI_API_KEY}getAzureAdToken(){return this.config.azureAdToken}getEndpoint(){return(this.config.endpoint??process.env.AZURE_OPENAI_ENDPOINT)?.replace(/\/$/,"")}getApiVersion(){return this.config.apiVersion??process.env.AZURE_OPENAI_API_VERSION??"2024-02-15-preview"}buildUrl(e,t){let r=this.getEndpoint(),n=t??this.config.deploymentId,i=this.getApiVersion();return`${r}/openai/deployments/${n}/${e}?api-version=${i}`}getHeaders(){let e={"Content-Type":"application/json"},t=this.getAzureAdToken();if(t)e.Authorization=`Bearer ${t}`;else{let r=this.getApiKey();r&&(e["api-key"]=r)}return e}formatMessages(e,t){let r=[];if(typeof e=="string")t&&r.push({role:"system",content:t}),r.push({role:"user",content:e});else{let n=e.some(i=>i.role==="system");t&&!n&&r.push({role:"system",content:t});for(let i of e)r.push({role:i.role,content:i.content})}return r}mapFinishReason(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content_filter";default:return"stop"}}handleApiError(e,t,r){let n=t.error?.message??"Unknown API error",i=t.error?.code??"",s=t.error?.innererror?.code??"";switch(e){case 401:throw O(n,"API_KEY_INVALID",{provider:"azure-openai",model:r,retryable:!1});case 403:throw O(n,"API_KEY_INVALID",{provider:"azure-openai",model:r,retryable:!1});case 429:throw O(n,"RATE_LIMITED",{provider:"azure-openai",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw i==="context_length_exceeded"||s==="context_length_exceeded"?O(n,"CONTEXT_LENGTH_EXCEEDED",{provider:"azure-openai",model:r,retryable:!1}):s==="content_filter"?O(n,"CONTENT_FILTERED",{provider:"azure-openai",model:r,retryable:!1}):O(n,"UNKNOWN",{provider:"azure-openai",model:r,retryable:!1});case 404:throw O(`Deployment not found: ${r}`,"MODEL_NOT_FOUND",{provider:"azure-openai",model:r,retryable:!1});case 500:case 502:case 503:throw O(n,"PROVIDER_UNAVAILABLE",{provider:"azure-openai",model:r,retryable:!0,retryAfterMs:5e3});default:throw O(n,"UNKNOWN",{provider:"azure-openai",model:r,retryable:!1})}}async fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?O("Request timed out","TIMEOUT",{provider:"azure-openai",retryable:!0}):s}finally{clearTimeout(i)}}async fetchWithRetry(e,t,r,n){let i;for(let s=0;s<n;s++)try{let a=await this.fetchWithTimeout(e,t,r);if(a.status>=400&&a.status<500&&a.status!==429)return a;if((a.status>=500||a.status===429)&&s<n-1){let c=at(s);await this.sleep(c);continue}return a}catch(a){if(i=S(a),s<n-1){let c=at(s);await this.sleep(c)}}throw i??new Error("Request failed after retries")}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var qle,jk,QVe,Kv,a2=v(()=>{"use strict";$r();vn();Cr();x();ma();qle={model:"anthropic.claude-3-5-sonnet-20241022-v2:0",region:"us-east-1",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0},jk={"claude-opus-4-7":"anthropic.claude-opus-4-7-v1:0","claude-sonnet-4-6":"anthropic.claude-sonnet-4-6-v1:0","claude-haiku-4-5-20251001":"anthropic.claude-haiku-4-5-v1:0","claude-haiku-4-5":"anthropic.claude-haiku-4-5-v1:0","claude-opus-4-5-20251101":"anthropic.claude-opus-4-5-v1:0","claude-opus-4-5":"anthropic.claude-opus-4-5-v1:0","claude-opus-4-20250514":"anthropic.claude-opus-4-v1:0","claude-opus-4":"anthropic.claude-opus-4-v1:0","claude-sonnet-4-20250514":"anthropic.claude-sonnet-4-v1:0","claude-sonnet-4":"anthropic.claude-sonnet-4-v1:0","claude-3-5-haiku-20241022":"anthropic.claude-3-5-haiku-v1:0","claude-haiku-3-5":"anthropic.claude-3-5-haiku-v1:0","claude-sonnet-4-5-20250929":"anthropic.claude-sonnet-4-5-v2:0","claude-sonnet-4-5":"anthropic.claude-sonnet-4-5-v2:0","claude-3-opus-20240229":"anthropic.claude-3-opus-20240229-v1:0","claude-3-sonnet-20240229":"anthropic.claude-3-sonnet-20240229-v1:0","claude-3-haiku-20240307":"anthropic.claude-3-haiku-20240307-v1:0","claude-3-5-sonnet-20241022":"anthropic.claude-3-5-sonnet-20241022-v2:0"},QVe=Object.fromEntries(Object.entries(jk).map(([o,e])=>[e,o])),Kv=class{type="bedrock";name="AWS Bedrock";config;requestId=0;constructor(e={}){this.config={...qle,...e}}async isAvailable(){if(!this.getCredentials())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getCredentials())return{healthy:!1,error:"AWS credentials not configured. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or use IAM role."};let t=Date.now();try{let r=this.mapToBedrockModel(this.config.model),n=await this.invokeModel(r,{anthropic_version:"bedrock-2023-05-31",max_tokens:1,messages:[{role:"user",content:"Hi"}]},5e3),i=Date.now()-t;if(!n.ok){let s=await n.text();return{healthy:!1,latencyMs:i,error:`API error: ${n.status} - ${s}`}}return{healthy:!0,latencyMs:i,models:this.getSupportedModels(),details:{region:this.getRegion(),defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(e,t){if(!this.getCredentials())throw O("AWS credentials not configured","API_KEY_MISSING",{provider:"bedrock",retryable:!1});let n=this.formatMessages(e),i=t?.model??this.config.model,s=this.mapToBedrockModel(i),a=t?.maxTokens??this.config.maxTokens??4096,c=t?.temperature??this.config.temperature??.7,l=`bedrock-${++this.requestId}-${Date.now()}`,u=Date.now(),d={anthropic_version:"bedrock-2023-05-31",max_tokens:a,messages:n};c!==void 0&&(d.temperature=Math.min(Math.max(c,0),1)),t?.systemPrompt&&(d.system=t.systemPrompt),t?.stopSequences&&t.stopSequences.length>0&&(d.stop_sequences=t.stopSequences);try{let p=await this.invokeModelWithRetry(s,d,t?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),m=Date.now()-u;if(!p.ok){let C=await p.json().catch(()=>({message:"Unknown error"}));throw this.handleApiError(p.status,C,i)}let g=await p.json(),h={promptTokens:g.usage.input_tokens,completionTokens:g.usage.output_tokens,totalTokens:g.usage.input_tokens+g.usage.output_tokens},y=st.calculateCost(s,h);return pe.recordTokenUsage(l,"bedrock-provider","llm","generate",{inputTokens:g.usage.input_tokens,outputTokens:g.usage.output_tokens,totalTokens:g.usage.input_tokens+g.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:g.content.filter(C=>C.type==="text").map(C=>C.text).join(""),model:s,provider:"bedrock",usage:h,cost:y,latencyMs:m,finishReason:this.mapFinishReason(g.stop_reason),cached:!1,requestId:l}}catch(p){throw p instanceof Error&&"code"in p?p:O(p instanceof Error?p.message:"Request failed","NETWORK_ERROR",{provider:"bedrock",model:i,retryable:!0,cause:p})}}async embed(e,t){throw O("Bedrock Claude models do not support native embeddings. Use Bedrock Titan or Cohere for embeddings.","MODEL_NOT_FOUND",{provider:"bedrock",retryable:!1})}async complete(e,t){let r=await this.generate(e,{model:t?.model,temperature:t?.temperature??.2,maxTokens:t?.maxTokens??256,stopSequences:t?.stopSequences??[`
|
|
1478
1478
|
|
|
@@ -5995,7 +5995,7 @@ ${i.errors.join(`
|
|
|
5995
5995
|
ORDER BY ended_at DESC
|
|
5996
5996
|
LIMIT ?
|
|
5997
5997
|
`).all(_Re);if(i.length===0)return;let s=r.prepare("UPDATE qe_trajectories SET feedback = ? WHERE id = ?");for(let a of i)try{let c=await LRe(a,o,e);c&&s.run(JSON.stringify(c),a.id)}catch{}}async function LRe(o,e,t){let r=["You are a quality engineering judge scoring a completed task trajectory.","",`Task: ${o.task.slice(0,400)}`,`Agent: ${o.agent??"unknown"}`,`Domain: ${o.domain??"general"}`,`Outcome: ${o.success?"success":"failure"}`,"",'Respond ONLY with JSON: {"quality": 0..1, "reasoning": "\u2264120 chars", "improvement": "\u2264120 chars or omit"}.'].join(`
|
|
5998
|
-
`),n=await fetch(`${t}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:IRe,max_tokens:DRe,messages:[{role:"user",content:r}]})});if(!n.ok)return null;let s=(await n.json()).content?.[0]?.text;if(!s)return null;let a=s.match(/\{[\s\S]*\}/);if(!a)return null;try{let c=JSON.parse(a[0]);return typeof c.quality!="number"||typeof c.reasoning!="string"?null:{quality:Math.max(0,Math.min(1,c.quality)),reasoning:c.reasoning.slice(0,200),improvement:typeof c.improvement=="string"?c.improvement.slice(0,200):void 0}}catch{return null}}var IRe,DRe,_Re,q7=v(()=>{"use strict";Y();IRe="claude-haiku-4-5-20251001",DRe=200,_Re=5});var l$={};Q(l$,{handleModelRoute:()=>IR,handleReasoningBankStats:()=>qRe,handleRoutingEconomics:()=>_R,handleRoutingMetrics:()=>DR,handleTaskCancel:()=>PR,handleTaskList:()=>xR,handleTaskOrchestrate:()=>MR,handleTaskOutcomeRecord:()=>$Re,handleTaskStatus:()=>kR,handleTaskStatusWithLearning:()=>BRe,handleTaskSubmit:()=>AR,subscribeTrajectoryEvents:()=>URe,unsubscribeTrajectoryEvents:()=>z7});async function AR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=await e.submitTask({type:o.type,priority:o.priority||"p1",targetDomains:o.targetDomains||[],payload:o.payload||{},timeout:o.timeout||3e5});if(!t.success)return{success:!1,error:t.error.message};let r=e.getTaskStatus(t.value);return{success:!0,data:{taskId:t.value,type:o.type,priority:o.priority||"p1",status:r?.status==="running"?"pending":"queued",assignedDomain:r?.assignedDomain}}}catch(t){return{success:!1,error:`Failed to submit task: ${w(t)}`}}}async function xR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=e.listTasks({status:o.status,priority:o.priority,domain:o.domain});return{success:!0,data:(typeof o.limit=="number"?t.slice(0,o.limit):t).map(i=>({taskId:i.taskId,type:i.task.type,status:i.status,priority:i.task.priority,assignedDomain:i.assignedDomain,assignedAgents:i.assignedAgents,result:i.result,error:i.error,createdAt:i.task.createdAt.toISOString(),startedAt:i.startedAt?.toISOString(),completedAt:i.completedAt?.toISOString(),duration:i.completedAt&&i.startedAt?i.completedAt.getTime()-i.startedAt.getTime():void 0}))}}catch(t){return{success:!1,error:`Failed to list tasks: ${w(t)}`}}}async function kR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=e.getTaskStatus(o.taskId);return t?{success:!0,data:{taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0}}:{success:!1,error:`Task not found: ${o.taskId}`}}catch(t){return{success:!1,error:`Failed to get task status: ${w(t)}`}}}async function PR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=await e.cancelTask(o.taskId);return t.success?{success:!0,data:{taskId:o.taskId,cancelled:!0}}:{success:!1,error:t.error.message}}catch(t){return{success:!1,error:`Failed to cancel task: ${w(t)}`}}}async function MR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e,workflowOrchestrator:t}=he();try{let r=o.context?.project||U7(o.task),n=o.priority==="critical"||/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),s=await(await Fs()).routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:n,agentType:`qe-${r}`,domain:r,metadata:{inferredDomain:r,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}}),a=await _n(),c=await a.getExperienceGuidance(o.task,o.context?.project),l=await a.searchPatterns(o.task,{limit:5,domain:o.context?.project??r}).catch(()=>[]),u=FRe(o.task),d=NRe(o.priority||"medium"),p=ORe[u];if(p&&t){console.log(`[TaskOrchestrate] Task type '${u}' has workflow '${p}' - executing workflow`);let y=o.task.match(/https?:\/\/[^\s]+/i),b=y?y[0]:void 0;b&&console.log(`[TaskOrchestrate] Detected URL for analysis: ${b}`);let C={targetId:o.context?.project||b||`task-${Date.now()}`,targetType:b?"website":"epic",description:o.task,acceptanceCriteria:o.context?.requirements||[],url:b,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall},patternHints:l.length>0?l.map(A=>({patternId:A.id,name:A.name,description:A.description,confidence:A.confidence,similarity:A.qualityScore,canReuse:A.tier==="long-term"})):void 0},E=await t.executeWorkflow(p,C);return E.success?{success:!0,data:{taskId:E.value,type:u,priority:d,strategy:o.strategy||"adaptive",status:"workflow-started",message:`Workflow '${p}' started for task: ${o.task}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}:{success:!1,error:`Workflow execution failed: ${E.error.message}`}}let m={description:o.task,strategy:o.strategy||"adaptive",maxAgents:o.maxAgents,context:o.context};u==="generate-tests"&&(m.sourceFiles=o.filePaths||[],m.sourceCode=o.codeContext||"",m.language=m.language||"typescript",m.testType=m.testType||"unit");let g=await e.submitTask({type:u,priority:d,targetDomains:[],payload:{...m,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,useAgentBooster:s.useAgentBooster,agentBoosterTransform:s.decision.agentBoosterTransform,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence},experienceGuidance:c?{strategy:c.recommendedStrategy,actions:c.suggestedActions,confidence:c.confidence,tokenSavings:c.estimatedTokenSavings}:void 0,patternHints:l.length>0?l.map(y=>({patternId:y.id,name:y.name,description:y.description,confidence:y.confidence,similarity:y.qualityScore,canReuse:y.tier==="long-term"})):void 0},timeout:6e5});if(!g.success)return{success:!1,error:g.error.message};let h=g.value;return await a$(h,o.task,{agent:"queen-coordinator",domain:o.context?.project}),process.env.AQE_TRAJECTORY_JUDGE==="1"&&process.env.ANTHROPIC_API_KEY&&$7().catch(y=>{console.warn("[TrajectoryJudge] failed:",y instanceof Error?y.message:y)}),{success:!0,data:{taskId:h,type:u,priority:d,strategy:o.strategy||"adaptive",status:"submitted",message:`Task orchestrated: ${o.task}${c?" (with experience guidance)":""}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}}catch(r){return{success:!1,error:`Failed to orchestrate task: ${w(r)}`}}}async function IR(o){try{let e=await Fs(),t=o.domain||U7(o.task),r=o.isCritical??/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),n=await e.routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:r,agentType:o.agentType||`qe-${t}`,domain:t,metadata:{inferredDomain:t,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}});return{success:!0,data:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,useAgentBooster:n.useAgentBooster,agentBoosterTransform:n.decision.agentBoosterTransform,complexity:{overall:n.decision.complexityAnalysis.overall,code:n.decision.complexityAnalysis.codeComplexity,reasoning:n.decision.complexityAnalysis.reasoningComplexity,scope:n.decision.complexityAnalysis.scopeComplexity},confidence:n.decision.confidence,rationale:n.decision.rationale,warnings:n.decision.warnings,budget:{allowed:n.decision.budgetDecision.allowed,wasDowngraded:n.decision.budgetDecision.wasDowngraded,estimatedCostUsd:n.decision.budgetDecision.estimatedCostUsd},decisionTimeMs:n.decision.metadata.decisionTimeMs}}}catch(e){return{success:!1,error:`Failed to route task: ${w(e)}`}}}async function DR(o){try{let e=await Fs(),t=e.getRoutingStats(),r=e.getMetrics(),n={stats:t,modelRouterMetrics:{totalDecisions:r.totalDecisions,avgDecisionTimeMs:r.avgDecisionTimeMs,agentBoosterStats:r.agentBoosterStats,budgetStats:r.budgetStats}};return o.includeLog&&(n.log=e.getRoutingLog(o.logLimit||100)),{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get routing metrics: ${w(e)}`}}}async function _R(o){try{let{createRoutingFeedbackCollector:e}=await Promise.resolve().then(()=>(hm(),$Q)),{getGlobalCostTracker:t}=await Promise.resolve().then(()=>(vn(),VH)),r=e(100);await r.initialize(),r.enableEconomicRouting({...o.taskComplexity!=null?{}:{}},t());let n=r.getEconomicReport();return n?{success:!0,data:{tierEfficiency:n.tierEfficiency.map(s=>({...s,qualityPerDollar:isFinite(s.qualityPerDollar)?s.qualityPerDollar:"Infinity"})),currentHourlyCostUsd:n.currentHourlyCostUsd,currentDailyCostUsd:n.currentDailyCostUsd,budgetRemaining:n.budgetRemaining,recommendation:n.recommendation,savingsOpportunity:n.savingsOpportunity}}:{success:!1,error:"Economic routing is not available"}}catch(e){return{success:!1,error:`Failed to get economic routing report: ${w(e)}`}}}function U7(o){let e=o.toLowerCase();return/\b(security|vulnerabilit|cve|owasp|secret|credential|injection|xss|csrf)\b/.test(e)?"security-compliance":/\b(chaos|resilience|fault.?inject|disaster|failover)\b/.test(e)?"chaos-resilience":/\b(defect|bug.?predict|risk.?assess|mutation)\b/.test(e)?"defect-intelligence":/\b(coverage|uncovered|gap.?analy)\b/.test(e)?"coverage-analysis":/\b(quality|code.?review|maintain|tech.?debt)\b/.test(e)?"quality-assessment":/\b(contract|api.?compat|breaking.?change|pact)\b/.test(e)?"contract-testing":/\b(index|knowledge.?graph|semantic|code.?intel)\b/.test(e)?"code-intelligence":/\b(accessib|a11y|wcag|screen.?read)\b/.test(e)?"visual-accessibility":/\b(requirement|bdd|acceptance|user.?stor)\b/.test(e)?"requirements-validation":/\b(generat.*test|test.*generat|write.*test|create.*test)\b/.test(e)?"test-generation":/\b(run.*test|execut.*test)\b/.test(e)?"test-execution":"test-generation"}function FRe(o){let e=o.toLowerCase();return/run\s+(?:\w+\s+)*tests?/.test(e)||/execute\s+(?:\w+\s+)*tests?/.test(e)||e.includes("run tests")||e.includes("execute tests")?"execute-tests":e.includes("generate test")||e.includes("create test")||e.includes("write test")?"generate-tests":e.includes("coverage")||e.includes("uncovered")?"analyze-coverage":e.includes("quality")||e.includes("code quality")?"assess-quality":e.includes("defect")||e.includes("bug")||e.includes("predict")?"predict-defects":e.includes("requirement")||e.includes("bdd")||e.includes("acceptance")?"validate-requirements":e.includes("index")||e.includes("knowledge graph")||e.includes("semantic")?"index-code":e.includes("security")||e.includes("vulnerability")||e.includes("owasp")?"scan-security":e.includes("contract")||e.includes("api contract")||e.includes("pact")?"validate-contracts":e.includes("accessibility")||e.includes("a11y")||e.includes("wcag")?"test-accessibility":e.includes("chaos")||e.includes("resilience")||e.includes("fault")?"run-chaos":e.includes("learn")||e.includes("optimize")||e.includes("improve")?"optimize-learning":e.includes("ideation")||e.includes("quality criteria")||e.includes("htsm")||e.includes("qcsd")||e.includes("testability")||e.includes("pi planning")||e.includes("sprint planning")?"ideation-assessment":"generate-tests"}function NRe(o){switch(o){case"critical":return"p0";case"high":return"p1";case"medium":return"p2";case"low":return"p3";default:return"p1"}}async function $Re(o){try{let e=await _n(),t={taskId:o.taskId,task:o.task,taskType:o.taskType,success:o.success,executionTimeMs:o.executionTimeMs,agentId:o.agentId,domain:o.domain,modelTier:o.modelTier,qualityScore:o.qualityScore,error:o.error,metrics:o.metrics};await e.recordTaskOutcome(t);let r=o.success&&(o.qualityScore||.5)>=.6;return{success:!0,data:{recorded:!0,patternStored:r,message:r?`Outcome recorded and pattern stored for task ${o.taskId}`:`Outcome recorded for task ${o.taskId}`}}}catch(e){return{success:!1,error:`Failed to record task outcome: ${w(e)}`}}}async function qRe(){try{let e=await(await _n()).getStats();return{success:!0,data:{service:e.service,patterns:{totalPatterns:e.reasoningBank.totalPatterns,byDomain:e.reasoningBank.byDomain,byTier:e.reasoningBank.byTier,learningOutcomes:e.reasoningBank.learningOutcomes,patternSuccessRate:e.reasoningBank.patternSuccessRate},embeddings:{cacheSize:e.reasoningBank.embeddingCacheSize,dimension:e.reasoningBank.embeddingDimension,transformerAvailable:e.reasoningBank.transformerAvailable},performance:{avgRoutingLatencyMs:e.reasoningBank.avgRoutingLatencyMs,p95RoutingLatencyMs:e.reasoningBank.p95RoutingLatencyMs}}}}catch(o){return{success:!1,error:`Failed to get ReasoningBank stats: ${w(o)}`}}}async function BRe(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=e.getTaskStatus(o.taskId);if(!t)return{success:!1,error:`Task not found: ${o.taskId}`};let r={taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0};if((t.status==="completed"||t.status==="failed")&&!B7.has(o.taskId)){B7.add(o.taskId);try{let n=await _n(),i=r.duration||0,s=t.status==="completed",a=t.task.payload||{},c=typeof a.description=="string"?a.description:t.task.type,l=a.routing,u=await Jh(o.taskId,s,t.error),d=u?.metrics.averageQuality??(s?.7:.3);await n.recordTaskOutcome({taskId:o.taskId,task:c,taskType:t.task.type,success:s,executionTimeMs:i,agentId:t.assignedAgents?.[0],domain:t.assignedDomain,modelTier:l?.tier,qualityScore:d,error:t.error,metrics:{testsGenerated:typeof t.result=="object"&&t.result?t.result.testsGenerated:void 0,testsPassed:typeof t.result=="object"&&t.result?t.result.testsPassed:void 0}}),console.error(`[TaskHandler] Recorded learning outcome: task=${o.taskId} success=${s} quality=${d.toFixed(2)} trajectorySteps=${u?.steps.length??0}`)}catch(n){console.error("[TaskHandler] Failed to record outcome:",n)}}return{success:!0,data:r}}catch(t){return{success:!1,error:`Failed to get task status: ${w(t)}`}}}function URe(o){z7(o);let e=o.subscribeToEventType("TaskCompleted",async r=>{let{taskId:n}=r.payload;n&&await Jh(n,!0).catch(()=>{})}),t=o.subscribeToEventType("TaskFailed",async r=>{let{taskId:n,error:i}=r.payload;n&&await Jh(n,!1,i).catch(()=>{})});c$=[e,t]}function z7(o){for(let e of c$)o.unsubscribe(e);c$=[]}var ORe,B7,c$,LR=v(()=>{"use strict";$s();fE();o$();q7();x();ORe={"ideation-assessment":"qcsd-ideation-swarm"};B7=new Set;c$=[]});var G7={};Q(G7,{DEFAULT_STRUCTURAL_HEALTH_CONFIG:()=>V7,StructuralHealthMonitor:()=>OR,createStructuralHealthMonitor:()=>zRe});function zRe(o){return new OR(o)}var V7,OR,H7=v(()=>{"use strict";aN();V7={healthyThreshold:.4,warningThreshold:.2,maxHistoryEntries:100,enableLogging:!1},OR=class{config;minCutService;history=[];constructor(e){this.config={...V7,...e},this.minCutService=cE()}computeFleetHealth(e){if(e.length===0)return this.emptyFleetResult();let t=this.minCutService.buildTaskGraphFromTopology(e);return this.computeFleetHealthFromGraph(t,e.length)}computeFleetHealthFromGraph(e,t){if(e.nodes.length===0)return this.emptyFleetResult();let r=this.minCutService.getStructuralHealth(e),n=this.determineStatus(r.normalizedLambda),i={lambda:r.lambda,healthy:r.healthy,weakPoints:r.weakPoints,normalizedLambda:r.normalizedLambda,riskScore:r.riskScore,status:n,suggestions:r.suggestions,measuredAt:new Date};return this.addHistoryEntry({lambda:r.lambda,healthy:r.healthy,weakPointCount:r.weakPoints.length,agentCount:t??e.nodes.length,timestamp:i.measuredAt}),this.config.enableLogging&&this.logHealth(i),i}getTrend(){if(this.history.length<2)return"stable";let e=Math.min(5,this.history.length),t=this.history.slice(-e),r=t[0].lambda,i=t[t.length-1].lambda-r;return Math.abs(i)<.05?"stable":i>0?"improving":"degrading"}getHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}clearHistory(){this.history.length=0}getMinCutService(){return this.minCutService}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}addHistoryEntry(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}emptyFleetResult(){return{lambda:0,healthy:!1,weakPoints:[],normalizedLambda:0,riskScore:1,status:"empty",suggestions:["No agents in fleet. Spawn agents to build a topology."],measuredAt:new Date}}logHealth(e){console.error(`[StructuralHealth] Status: ${e.status} | Lambda: ${e.normalizedLambda.toFixed(3)} | Weak points: ${e.weakPoints.length} | Risk: ${(e.riskScore*100).toFixed(0)}%`)}}});function he(){return G}function fe(){return G.initialized&&G.kernel!==null&&G.queen!==null}function j7(o,e){if(G.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return G.agentLevels.set(o,i),"worker"}let r=Array.from(G.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",n={agentId:o,domain:e,level:r,spawnedAt:new Date};return G.agentLevels.set(o,n),r}function Q7(o){return G.agentLevels.get(o)}async function Yh(o){try{if(G.initialized&&G.kernel&&G.queen)return{success:!0,data:{fleetId:G.fleetId,topology:o.topology||"hierarchical",maxAgents:o.maxAgents||15,enabledDomains:o.enabledDomains||W7,status:"ready"}};G.fleetId=`fleet-${R().slice(0,8)}`;let e=o.enabledDomains||[...re],t=e.filter(l=>l!=="coordination"),r=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";G.kernel=new iw({maxConcurrentAgents:o.maxAgents||15,memoryBackend:r,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await G.kernel.initialize(),G.router=new qw(G.kernel.eventBus),await G.router.initialize();let n=l=>G.kernel.getDomainAPI(l),i=new hR(G.kernel.eventBus,G.kernel.memory,n),s=G.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let u=s.getPlugin(l);u&&a.set(l,u)}try{let{getDaemon:l}=await Promise.resolve().then(()=>(ER(),wR)),u=l().getWorkerManager();u.setKernel(G.kernel),u.setMemory(G.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${w(l)}`)}G.queen=Z8(G.kernel,G.router,i,void 0,a),await G.queen.initialize(),G.workflowOrchestrator=new Sg(G.kernel.eventBus,G.kernel.memory,G.kernel.coordinator),await G.workflowOrchestrator.initialize(),VRe(G.kernel,G.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await Promise.resolve().then(()=>(LR(),l$));return c(G.router),G.initialized=!0,G.initTime=new Date,G.topology=o.topology||"hierarchical",G.agentLevels.clear(),{success:!0,data:{fleetId:G.fleetId,topology:G.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${w(e)}`}}}async function u$(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=G.queen.getHealth(),t=G.queen.getMetrics(),r={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:G.queen.getDomainLoad(s)});r.domains=i}let n=G.queen.getDomainTeamManager?.();if(n){let i=n.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,n.getTeamHealth(c.domain)?.healthy&&a++;r.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(r.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await Promise.resolve().then(()=>(Y(),Ir)),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();r.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:r}}catch(e){return{success:!1,error:`Failed to get fleet status: ${w(e)}`}}}async function d$(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let r=G.queen.getDomainHealth(o.domain);return r?{success:!0,data:{domain:o.domain,status:r.status,agents:r.agents,errors:r.errors,lastActivity:r.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=G.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let r={};for(let[n,i]of e.domainHealth)r[n]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=r,t.issues=e.issues.map(n=>({severity:n.severity,message:n.message,domain:n.domain,timestamp:n.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:r}=await Promise.resolve().then(()=>(H7(),G7)),n=new r,i=[];for(let[c]of e.domainHealth){let l=G.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=n.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${w(e)}`}}}async function p$(){if(l9(),SE(),c7(),G.workflowOrchestrator&&(await G.workflowOrchestrator.dispose(),G.workflowOrchestrator=null),G.queen&&(await G.queen.dispose(),G.queen=null),G.router){try{let{unsubscribeTrajectoryEvents:o}=await Promise.resolve().then(()=>(LR(),l$));o(G.router)}catch{}await G.router.dispose(),G.router=null}G.kernel&&(await G.kernel.dispose(),G.kernel=null),G.initialized=!1,G.fleetId=null,G.initTime=null,G.topology="hierarchical",G.agentLevels.clear()}async function m$(){let o=performance.now();try{let e=fe(),t=G.initTime?Date.now()-G.initTime.getTime():0,r={connected:!1,totalEntries:0,namespaces:0},n={enabled:!1,vectorCount:0},i=0;if(e&&G.kernel){let u=G.kernel.memory;try{r.connected=!0;let d=await u.count("default"),p=await u.count("learning"),m=await u.count("patterns");r.totalEntries=d+p+m;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await u.count(h)>0&&g++;r.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";n.enabled=d;let p=u;d&&typeof p.vectorCount=="function"&&(n.vectorCount=await p.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let s=e&&G.kernel?(G.kernel.getLoadedDomains?.()??W7).length:0,a=null;try{let{getSharedRvfDualWriterSync:u}=await Promise.resolve().then(()=>(Qi(),va)),d=u();if(d){let p=d.status(),m=d.getDivergenceReport();a={mode:p.mode,vectorCount:p.rvf?.totalVectors??0,divergences:m.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await Promise.resolve().then(()=>(uc(),Wx)),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.11.2",loadedDomains:s,memory:r,hnsw:n,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:R(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:w(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:R(),toolName:"aqe_health"}}}}function VRe(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let r=o.getDomainAPI("visual-accessibility");r?.registerWorkflowActions&&(r.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}var W7,G,$s=v(()=>{"use strict";N();M6();L();eX();oO();tX();RN();wE();G1();l7();x();W7=re.filter(o=>o!=="coordination"),G={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map}});B();import*as RB from"readline";var rn={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,SERVER_ERROR:-32e3},Po=class extends Error{constructor(t,r,n){super(r);this.code=t;this.data=n;this.name="McpError"}code;data};function z0(o){return typeof o=="object"&&o!==null&&typeof o.code=="number"&&typeof o.message=="string"}var U0=class{inputStream;outputStream;maxMessageSize;rl=null;requestHandler=null;notificationHandler=null;errorHandler=null;closeHandler=null;running=!1;metrics={messagesReceived:0,messagesSent:0,errors:0,bytesReceived:0,bytesSent:0};constructor(e={}){this.inputStream=e.inputStream??process.stdin,this.outputStream=e.outputStream??process.stdout,this.maxMessageSize=e.maxMessageSize??10*1024*1024}onRequest(e){this.requestHandler=e}onNotification(e){this.notificationHandler=e}start(){this.running||(this.running=!0,this.rl=RB.createInterface({input:this.inputStream,crlfDelay:1/0}),this.rl.on("line",e=>{this.handleLine(e).catch(t=>{this.metrics.errors++,console.error("[StdioTransport] Error handling line:",t)})}),this.rl.on("close",()=>{let e=this.running;if(this.running=!1,!e)return;if(this.inputStream.readableEnded===!0){this.closeHandler&&this.closeHandler();return}this.errorHandler&&this.errorHandler(new Error("Transport connection closed unexpectedly"))}),this.rl.on("error",e=>{this.metrics.errors++,console.error("[StdioTransport] Readline error:",e),this.errorHandler&&this.errorHandler(e)}))}stop(){this.running=!1,this.rl&&(this.rl.close(),this.rl=null)}async sendResponse(e){await this.write(JSON.stringify(e))}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t};await this.write(JSON.stringify(r))}onError(e){this.errorHandler=e}onClose(e){this.closeHandler=e}reconnect(){if(this.inputStream.readableEnded===!0){this.running=!1,this.closeHandler&&this.closeHandler();return}this.rl&&(this.rl.close(),this.rl=null),this.running=!1,this.start()}getMetrics(){return{...this.metrics}}isRunning(){return this.running}async handleLine(e){if(!e.trim())return;if(this.metrics.bytesReceived+=Buffer.byteLength(e,"utf-8"),Buffer.byteLength(e,"utf-8")>this.maxMessageSize){this.metrics.errors++,await this.sendError(null,rn.INVALID_REQUEST,"Message too large");return}let t;try{t=k(e)}catch{this.metrics.errors++,await this.sendError(null,rn.PARSE_ERROR,"Parse error");return}if(t.jsonrpc!=="2.0"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Invalid JSON-RPC version");return}if(!t.method||typeof t.method!="string"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Missing or invalid method");return}this.metrics.messagesReceived++,t.id!==void 0?await this.handleRequest(t):await this.handleNotification(t)}async handleRequest(e){if(!this.requestHandler){await this.sendError(e.id,rn.INTERNAL_ERROR,"No request handler registered");return}try{let t=await this.requestHandler(e);await this.sendResponse({jsonrpc:"2.0",id:e.id,result:t})}catch(t){if(z0(t))await this.sendError(e.id,t.code,t.message,t.data);else{let r=t;await this.sendError(e.id,rn.INTERNAL_ERROR,r.message||"Internal error")}}}async handleNotification(e){if(this.notificationHandler)try{await this.notificationHandler(e)}catch(t){this.metrics.errors++,console.error("[StdioTransport] Notification handler error:",t)}}async sendError(e,t,r,n){let i={jsonrpc:"2.0",id:e,error:{code:t,message:r,data:n}};await this.sendResponse(i)}async write(e){let r=[0,500,1e3];for(let n=0;n<3;n++)try{await this.writeOnce(e);return}catch(i){if(n<2)console.error(`[StdioTransport] Write attempt ${n+1} failed, retrying in ${r[n+1]}ms...`),await new Promise(s=>setTimeout(s,r[n+1]));else throw i}}async writeOnce(e){let t=e+`
|
|
5998
|
+
`),n=await fetch(`${t}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:IRe,max_tokens:DRe,messages:[{role:"user",content:r}]})});if(!n.ok)return null;let s=(await n.json()).content?.[0]?.text;if(!s)return null;let a=s.match(/\{[\s\S]*\}/);if(!a)return null;try{let c=JSON.parse(a[0]);return typeof c.quality!="number"||typeof c.reasoning!="string"?null:{quality:Math.max(0,Math.min(1,c.quality)),reasoning:c.reasoning.slice(0,200),improvement:typeof c.improvement=="string"?c.improvement.slice(0,200):void 0}}catch{return null}}var IRe,DRe,_Re,q7=v(()=>{"use strict";Y();IRe="claude-haiku-4-5-20251001",DRe=200,_Re=5});var l$={};Q(l$,{handleModelRoute:()=>IR,handleReasoningBankStats:()=>qRe,handleRoutingEconomics:()=>_R,handleRoutingMetrics:()=>DR,handleTaskCancel:()=>PR,handleTaskList:()=>xR,handleTaskOrchestrate:()=>MR,handleTaskOutcomeRecord:()=>$Re,handleTaskStatus:()=>kR,handleTaskStatusWithLearning:()=>BRe,handleTaskSubmit:()=>AR,subscribeTrajectoryEvents:()=>URe,unsubscribeTrajectoryEvents:()=>z7});async function AR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=await e.submitTask({type:o.type,priority:o.priority||"p1",targetDomains:o.targetDomains||[],payload:o.payload||{},timeout:o.timeout||3e5});if(!t.success)return{success:!1,error:t.error.message};let r=e.getTaskStatus(t.value);return{success:!0,data:{taskId:t.value,type:o.type,priority:o.priority||"p1",status:r?.status==="running"?"pending":"queued",assignedDomain:r?.assignedDomain}}}catch(t){return{success:!1,error:`Failed to submit task: ${w(t)}`}}}async function xR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=e.listTasks({status:o.status,priority:o.priority,domain:o.domain});return{success:!0,data:(typeof o.limit=="number"?t.slice(0,o.limit):t).map(i=>({taskId:i.taskId,type:i.task.type,status:i.status,priority:i.task.priority,assignedDomain:i.assignedDomain,assignedAgents:i.assignedAgents,result:i.result,error:i.error,createdAt:i.task.createdAt.toISOString(),startedAt:i.startedAt?.toISOString(),completedAt:i.completedAt?.toISOString(),duration:i.completedAt&&i.startedAt?i.completedAt.getTime()-i.startedAt.getTime():void 0}))}}catch(t){return{success:!1,error:`Failed to list tasks: ${w(t)}`}}}async function kR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=e.getTaskStatus(o.taskId);return t?{success:!0,data:{taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0}}:{success:!1,error:`Task not found: ${o.taskId}`}}catch(t){return{success:!1,error:`Failed to get task status: ${w(t)}`}}}async function PR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=await e.cancelTask(o.taskId);return t.success?{success:!0,data:{taskId:o.taskId,cancelled:!0}}:{success:!1,error:t.error.message}}catch(t){return{success:!1,error:`Failed to cancel task: ${w(t)}`}}}async function MR(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e,workflowOrchestrator:t}=he();try{let r=o.context?.project||U7(o.task),n=o.priority==="critical"||/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),s=await(await Fs()).routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:n,agentType:`qe-${r}`,domain:r,metadata:{inferredDomain:r,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}}),a=await _n(),c=await a.getExperienceGuidance(o.task,o.context?.project),l=await a.searchPatterns(o.task,{limit:5,domain:o.context?.project??r}).catch(()=>[]),u=FRe(o.task),d=NRe(o.priority||"medium"),p=ORe[u];if(p&&t){console.log(`[TaskOrchestrate] Task type '${u}' has workflow '${p}' - executing workflow`);let y=o.task.match(/https?:\/\/[^\s]+/i),b=y?y[0]:void 0;b&&console.log(`[TaskOrchestrate] Detected URL for analysis: ${b}`);let C={targetId:o.context?.project||b||`task-${Date.now()}`,targetType:b?"website":"epic",description:o.task,acceptanceCriteria:o.context?.requirements||[],url:b,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall},patternHints:l.length>0?l.map(A=>({patternId:A.id,name:A.name,description:A.description,confidence:A.confidence,similarity:A.qualityScore,canReuse:A.tier==="long-term"})):void 0},E=await t.executeWorkflow(p,C);return E.success?{success:!0,data:{taskId:E.value,type:u,priority:d,strategy:o.strategy||"adaptive",status:"workflow-started",message:`Workflow '${p}' started for task: ${o.task}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}:{success:!1,error:`Workflow execution failed: ${E.error.message}`}}let m={description:o.task,strategy:o.strategy||"adaptive",maxAgents:o.maxAgents,context:o.context};u==="generate-tests"&&(m.sourceFiles=o.filePaths||[],m.sourceCode=o.codeContext||"",m.language=m.language||"typescript",m.testType=m.testType||"unit");let g=await e.submitTask({type:u,priority:d,targetDomains:[],payload:{...m,routing:{tier:s.decision.tier,modelId:s.modelId,executionStrategy:s.executionStrategy,useAgentBooster:s.useAgentBooster,agentBoosterTransform:s.decision.agentBoosterTransform,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence},experienceGuidance:c?{strategy:c.recommendedStrategy,actions:c.suggestedActions,confidence:c.confidence,tokenSavings:c.estimatedTokenSavings}:void 0,patternHints:l.length>0?l.map(y=>({patternId:y.id,name:y.name,description:y.description,confidence:y.confidence,similarity:y.qualityScore,canReuse:y.tier==="long-term"})):void 0},timeout:6e5});if(!g.success)return{success:!1,error:g.error.message};let h=g.value;return await a$(h,o.task,{agent:"queen-coordinator",domain:o.context?.project}),process.env.AQE_TRAJECTORY_JUDGE==="1"&&process.env.ANTHROPIC_API_KEY&&$7().catch(y=>{console.warn("[TrajectoryJudge] failed:",y instanceof Error?y.message:y)}),{success:!0,data:{taskId:h,type:u,priority:d,strategy:o.strategy||"adaptive",status:"submitted",message:`Task orchestrated: ${o.task}${c?" (with experience guidance)":""}`,routing:{tier:s.decision.tier,tierName:s.tierInfo.name,modelId:s.modelId,executionStrategy:s.executionStrategy,complexity:s.decision.complexityAnalysis.overall,confidence:s.decision.confidence,useAgentBooster:s.useAgentBooster,rationale:s.decision.rationale,decisionTimeMs:s.decision.metadata.decisionTimeMs}}}}catch(r){return{success:!1,error:`Failed to orchestrate task: ${w(r)}`}}}async function IR(o){try{let e=await Fs(),t=o.domain||U7(o.task),r=o.isCritical??/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(o.task),n=await e.routeTask({task:o.task,codeContext:o.codeContext,filePaths:o.filePaths,manualTier:o.manualTier,isCritical:r,agentType:o.agentType||`qe-${t}`,domain:t,metadata:{inferredDomain:t,hasCodeContext:!!o.codeContext,fileCount:o.filePaths?.length}});return{success:!0,data:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,useAgentBooster:n.useAgentBooster,agentBoosterTransform:n.decision.agentBoosterTransform,complexity:{overall:n.decision.complexityAnalysis.overall,code:n.decision.complexityAnalysis.codeComplexity,reasoning:n.decision.complexityAnalysis.reasoningComplexity,scope:n.decision.complexityAnalysis.scopeComplexity},confidence:n.decision.confidence,rationale:n.decision.rationale,warnings:n.decision.warnings,budget:{allowed:n.decision.budgetDecision.allowed,wasDowngraded:n.decision.budgetDecision.wasDowngraded,estimatedCostUsd:n.decision.budgetDecision.estimatedCostUsd},decisionTimeMs:n.decision.metadata.decisionTimeMs}}}catch(e){return{success:!1,error:`Failed to route task: ${w(e)}`}}}async function DR(o){try{let e=await Fs(),t=e.getRoutingStats(),r=e.getMetrics(),n={stats:t,modelRouterMetrics:{totalDecisions:r.totalDecisions,avgDecisionTimeMs:r.avgDecisionTimeMs,agentBoosterStats:r.agentBoosterStats,budgetStats:r.budgetStats}};return o.includeLog&&(n.log=e.getRoutingLog(o.logLimit||100)),{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get routing metrics: ${w(e)}`}}}async function _R(o){try{let{createRoutingFeedbackCollector:e}=await Promise.resolve().then(()=>(hm(),$Q)),{getGlobalCostTracker:t}=await Promise.resolve().then(()=>(vn(),VH)),r=e(100);await r.initialize(),r.enableEconomicRouting({...o.taskComplexity!=null?{}:{}},t());let n=r.getEconomicReport();return n?{success:!0,data:{tierEfficiency:n.tierEfficiency.map(s=>({...s,qualityPerDollar:isFinite(s.qualityPerDollar)?s.qualityPerDollar:"Infinity"})),currentHourlyCostUsd:n.currentHourlyCostUsd,currentDailyCostUsd:n.currentDailyCostUsd,budgetRemaining:n.budgetRemaining,recommendation:n.recommendation,savingsOpportunity:n.savingsOpportunity}}:{success:!1,error:"Economic routing is not available"}}catch(e){return{success:!1,error:`Failed to get economic routing report: ${w(e)}`}}}function U7(o){let e=o.toLowerCase();return/\b(security|vulnerabilit|cve|owasp|secret|credential|injection|xss|csrf)\b/.test(e)?"security-compliance":/\b(chaos|resilience|fault.?inject|disaster|failover)\b/.test(e)?"chaos-resilience":/\b(defect|bug.?predict|risk.?assess|mutation)\b/.test(e)?"defect-intelligence":/\b(coverage|uncovered|gap.?analy)\b/.test(e)?"coverage-analysis":/\b(quality|code.?review|maintain|tech.?debt)\b/.test(e)?"quality-assessment":/\b(contract|api.?compat|breaking.?change|pact)\b/.test(e)?"contract-testing":/\b(index|knowledge.?graph|semantic|code.?intel)\b/.test(e)?"code-intelligence":/\b(accessib|a11y|wcag|screen.?read)\b/.test(e)?"visual-accessibility":/\b(requirement|bdd|acceptance|user.?stor)\b/.test(e)?"requirements-validation":/\b(generat.*test|test.*generat|write.*test|create.*test)\b/.test(e)?"test-generation":/\b(run.*test|execut.*test)\b/.test(e)?"test-execution":"test-generation"}function FRe(o){let e=o.toLowerCase();return/run\s+(?:\w+\s+)*tests?/.test(e)||/execute\s+(?:\w+\s+)*tests?/.test(e)||e.includes("run tests")||e.includes("execute tests")?"execute-tests":e.includes("generate test")||e.includes("create test")||e.includes("write test")?"generate-tests":e.includes("coverage")||e.includes("uncovered")?"analyze-coverage":e.includes("quality")||e.includes("code quality")?"assess-quality":e.includes("defect")||e.includes("bug")||e.includes("predict")?"predict-defects":e.includes("requirement")||e.includes("bdd")||e.includes("acceptance")?"validate-requirements":e.includes("index")||e.includes("knowledge graph")||e.includes("semantic")?"index-code":e.includes("security")||e.includes("vulnerability")||e.includes("owasp")?"scan-security":e.includes("contract")||e.includes("api contract")||e.includes("pact")?"validate-contracts":e.includes("accessibility")||e.includes("a11y")||e.includes("wcag")?"test-accessibility":e.includes("chaos")||e.includes("resilience")||e.includes("fault")?"run-chaos":e.includes("learn")||e.includes("optimize")||e.includes("improve")?"optimize-learning":e.includes("ideation")||e.includes("quality criteria")||e.includes("htsm")||e.includes("qcsd")||e.includes("testability")||e.includes("pi planning")||e.includes("sprint planning")?"ideation-assessment":"generate-tests"}function NRe(o){switch(o){case"critical":return"p0";case"high":return"p1";case"medium":return"p2";case"low":return"p3";default:return"p1"}}async function $Re(o){try{let e=await _n(),t={taskId:o.taskId,task:o.task,taskType:o.taskType,success:o.success,executionTimeMs:o.executionTimeMs,agentId:o.agentId,domain:o.domain,modelTier:o.modelTier,qualityScore:o.qualityScore,error:o.error,metrics:o.metrics};await e.recordTaskOutcome(t);let r=o.success&&(o.qualityScore||.5)>=.6;return{success:!0,data:{recorded:!0,patternStored:r,message:r?`Outcome recorded and pattern stored for task ${o.taskId}`:`Outcome recorded for task ${o.taskId}`}}}catch(e){return{success:!1,error:`Failed to record task outcome: ${w(e)}`}}}async function qRe(){try{let e=await(await _n()).getStats();return{success:!0,data:{service:e.service,patterns:{totalPatterns:e.reasoningBank.totalPatterns,byDomain:e.reasoningBank.byDomain,byTier:e.reasoningBank.byTier,learningOutcomes:e.reasoningBank.learningOutcomes,patternSuccessRate:e.reasoningBank.patternSuccessRate},embeddings:{cacheSize:e.reasoningBank.embeddingCacheSize,dimension:e.reasoningBank.embeddingDimension,transformerAvailable:e.reasoningBank.transformerAvailable},performance:{avgRoutingLatencyMs:e.reasoningBank.avgRoutingLatencyMs,p95RoutingLatencyMs:e.reasoningBank.p95RoutingLatencyMs}}}}catch(o){return{success:!1,error:`Failed to get ReasoningBank stats: ${w(o)}`}}}async function BRe(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=he();try{let t=e.getTaskStatus(o.taskId);if(!t)return{success:!1,error:`Task not found: ${o.taskId}`};let r={taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:o.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0};if((t.status==="completed"||t.status==="failed")&&!B7.has(o.taskId)){B7.add(o.taskId);try{let n=await _n(),i=r.duration||0,s=t.status==="completed",a=t.task.payload||{},c=typeof a.description=="string"?a.description:t.task.type,l=a.routing,u=await Jh(o.taskId,s,t.error),d=u?.metrics.averageQuality??(s?.7:.3);await n.recordTaskOutcome({taskId:o.taskId,task:c,taskType:t.task.type,success:s,executionTimeMs:i,agentId:t.assignedAgents?.[0],domain:t.assignedDomain,modelTier:l?.tier,qualityScore:d,error:t.error,metrics:{testsGenerated:typeof t.result=="object"&&t.result?t.result.testsGenerated:void 0,testsPassed:typeof t.result=="object"&&t.result?t.result.testsPassed:void 0}}),console.error(`[TaskHandler] Recorded learning outcome: task=${o.taskId} success=${s} quality=${d.toFixed(2)} trajectorySteps=${u?.steps.length??0}`)}catch(n){console.error("[TaskHandler] Failed to record outcome:",n)}}return{success:!0,data:r}}catch(t){return{success:!1,error:`Failed to get task status: ${w(t)}`}}}function URe(o){z7(o);let e=o.subscribeToEventType("TaskCompleted",async r=>{let{taskId:n}=r.payload;n&&await Jh(n,!0).catch(()=>{})}),t=o.subscribeToEventType("TaskFailed",async r=>{let{taskId:n,error:i}=r.payload;n&&await Jh(n,!1,i).catch(()=>{})});c$=[e,t]}function z7(o){for(let e of c$)o.unsubscribe(e);c$=[]}var ORe,B7,c$,LR=v(()=>{"use strict";$s();fE();o$();q7();x();ORe={"ideation-assessment":"qcsd-ideation-swarm"};B7=new Set;c$=[]});var G7={};Q(G7,{DEFAULT_STRUCTURAL_HEALTH_CONFIG:()=>V7,StructuralHealthMonitor:()=>OR,createStructuralHealthMonitor:()=>zRe});function zRe(o){return new OR(o)}var V7,OR,H7=v(()=>{"use strict";aN();V7={healthyThreshold:.4,warningThreshold:.2,maxHistoryEntries:100,enableLogging:!1},OR=class{config;minCutService;history=[];constructor(e){this.config={...V7,...e},this.minCutService=cE()}computeFleetHealth(e){if(e.length===0)return this.emptyFleetResult();let t=this.minCutService.buildTaskGraphFromTopology(e);return this.computeFleetHealthFromGraph(t,e.length)}computeFleetHealthFromGraph(e,t){if(e.nodes.length===0)return this.emptyFleetResult();let r=this.minCutService.getStructuralHealth(e),n=this.determineStatus(r.normalizedLambda),i={lambda:r.lambda,healthy:r.healthy,weakPoints:r.weakPoints,normalizedLambda:r.normalizedLambda,riskScore:r.riskScore,status:n,suggestions:r.suggestions,measuredAt:new Date};return this.addHistoryEntry({lambda:r.lambda,healthy:r.healthy,weakPointCount:r.weakPoints.length,agentCount:t??e.nodes.length,timestamp:i.measuredAt}),this.config.enableLogging&&this.logHealth(i),i}getTrend(){if(this.history.length<2)return"stable";let e=Math.min(5,this.history.length),t=this.history.slice(-e),r=t[0].lambda,i=t[t.length-1].lambda-r;return Math.abs(i)<.05?"stable":i>0?"improving":"degrading"}getHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}clearHistory(){this.history.length=0}getMinCutService(){return this.minCutService}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}addHistoryEntry(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}emptyFleetResult(){return{lambda:0,healthy:!1,weakPoints:[],normalizedLambda:0,riskScore:1,status:"empty",suggestions:["No agents in fleet. Spawn agents to build a topology."],measuredAt:new Date}}logHealth(e){console.error(`[StructuralHealth] Status: ${e.status} | Lambda: ${e.normalizedLambda.toFixed(3)} | Weak points: ${e.weakPoints.length} | Risk: ${(e.riskScore*100).toFixed(0)}%`)}}});function he(){return G}function fe(){return G.initialized&&G.kernel!==null&&G.queen!==null}function j7(o,e){if(G.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return G.agentLevels.set(o,i),"worker"}let r=Array.from(G.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",n={agentId:o,domain:e,level:r,spawnedAt:new Date};return G.agentLevels.set(o,n),r}function Q7(o){return G.agentLevels.get(o)}async function Yh(o){try{if(G.initialized&&G.kernel&&G.queen)return{success:!0,data:{fleetId:G.fleetId,topology:o.topology||"hierarchical",maxAgents:o.maxAgents||15,enabledDomains:o.enabledDomains||W7,status:"ready"}};G.fleetId=`fleet-${R().slice(0,8)}`;let e=o.enabledDomains||[...re],t=e.filter(l=>l!=="coordination"),r=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";G.kernel=new iw({maxConcurrentAgents:o.maxAgents||15,memoryBackend:r,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await G.kernel.initialize(),G.router=new qw(G.kernel.eventBus),await G.router.initialize();let n=l=>G.kernel.getDomainAPI(l),i=new hR(G.kernel.eventBus,G.kernel.memory,n),s=G.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let u=s.getPlugin(l);u&&a.set(l,u)}try{let{getDaemon:l}=await Promise.resolve().then(()=>(ER(),wR)),u=l().getWorkerManager();u.setKernel(G.kernel),u.setMemory(G.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${w(l)}`)}G.queen=Z8(G.kernel,G.router,i,void 0,a),await G.queen.initialize(),G.workflowOrchestrator=new Sg(G.kernel.eventBus,G.kernel.memory,G.kernel.coordinator),await G.workflowOrchestrator.initialize(),VRe(G.kernel,G.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await Promise.resolve().then(()=>(LR(),l$));return c(G.router),G.initialized=!0,G.initTime=new Date,G.topology=o.topology||"hierarchical",G.agentLevels.clear(),{success:!0,data:{fleetId:G.fleetId,topology:G.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${w(e)}`}}}async function u$(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=G.queen.getHealth(),t=G.queen.getMetrics(),r={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:G.queen.getDomainLoad(s)});r.domains=i}let n=G.queen.getDomainTeamManager?.();if(n){let i=n.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,n.getTeamHealth(c.domain)?.healthy&&a++;r.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(r.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await Promise.resolve().then(()=>(Y(),Ir)),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();r.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:r}}catch(e){return{success:!1,error:`Failed to get fleet status: ${w(e)}`}}}async function d$(o){if(!fe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let r=G.queen.getDomainHealth(o.domain);return r?{success:!0,data:{domain:o.domain,status:r.status,agents:r.agents,errors:r.errors,lastActivity:r.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=G.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let r={};for(let[n,i]of e.domainHealth)r[n]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=r,t.issues=e.issues.map(n=>({severity:n.severity,message:n.message,domain:n.domain,timestamp:n.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:r}=await Promise.resolve().then(()=>(H7(),G7)),n=new r,i=[];for(let[c]of e.domainHealth){let l=G.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=n.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${w(e)}`}}}async function p$(){if(l9(),SE(),c7(),G.workflowOrchestrator&&(await G.workflowOrchestrator.dispose(),G.workflowOrchestrator=null),G.queen&&(await G.queen.dispose(),G.queen=null),G.router){try{let{unsubscribeTrajectoryEvents:o}=await Promise.resolve().then(()=>(LR(),l$));o(G.router)}catch{}await G.router.dispose(),G.router=null}G.kernel&&(await G.kernel.dispose(),G.kernel=null),G.initialized=!1,G.fleetId=null,G.initTime=null,G.topology="hierarchical",G.agentLevels.clear()}async function m$(){let o=performance.now();try{let e=fe(),t=G.initTime?Date.now()-G.initTime.getTime():0,r={connected:!1,totalEntries:0,namespaces:0},n={enabled:!1,vectorCount:0},i=0;if(e&&G.kernel){let u=G.kernel.memory;try{r.connected=!0;let d=await u.count("default"),p=await u.count("learning"),m=await u.count("patterns");r.totalEntries=d+p+m;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await u.count(h)>0&&g++;r.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";n.enabled=d;let p=u;d&&typeof p.vectorCount=="function"&&(n.vectorCount=await p.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let s=e&&G.kernel?(G.kernel.getLoadedDomains?.()??W7).length:0,a=null;try{let{getSharedRvfDualWriterSync:u}=await Promise.resolve().then(()=>(Qi(),va)),d=u();if(d){let p=d.status(),m=d.getDivergenceReport();a={mode:p.mode,vectorCount:p.rvf?.totalVectors??0,divergences:m.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await Promise.resolve().then(()=>(uc(),Wx)),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.11.3",loadedDomains:s,memory:r,hnsw:n,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:R(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:w(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:R(),toolName:"aqe_health"}}}}function VRe(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let r=o.getDomainAPI("visual-accessibility");r?.registerWorkflowActions&&(r.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}var W7,G,$s=v(()=>{"use strict";N();M6();L();eX();oO();tX();RN();wE();G1();l7();x();W7=re.filter(o=>o!=="coordination"),G={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map}});B();import*as RB from"readline";var rn={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,SERVER_ERROR:-32e3},Po=class extends Error{constructor(t,r,n){super(r);this.code=t;this.data=n;this.name="McpError"}code;data};function z0(o){return typeof o=="object"&&o!==null&&typeof o.code=="number"&&typeof o.message=="string"}var U0=class{inputStream;outputStream;maxMessageSize;rl=null;requestHandler=null;notificationHandler=null;errorHandler=null;closeHandler=null;running=!1;metrics={messagesReceived:0,messagesSent:0,errors:0,bytesReceived:0,bytesSent:0};constructor(e={}){this.inputStream=e.inputStream??process.stdin,this.outputStream=e.outputStream??process.stdout,this.maxMessageSize=e.maxMessageSize??10*1024*1024}onRequest(e){this.requestHandler=e}onNotification(e){this.notificationHandler=e}start(){this.running||(this.running=!0,this.rl=RB.createInterface({input:this.inputStream,crlfDelay:1/0}),this.rl.on("line",e=>{this.handleLine(e).catch(t=>{this.metrics.errors++,console.error("[StdioTransport] Error handling line:",t)})}),this.rl.on("close",()=>{let e=this.running;if(this.running=!1,!e)return;if(this.inputStream.readableEnded===!0){this.closeHandler&&this.closeHandler();return}this.errorHandler&&this.errorHandler(new Error("Transport connection closed unexpectedly"))}),this.rl.on("error",e=>{this.metrics.errors++,console.error("[StdioTransport] Readline error:",e),this.errorHandler&&this.errorHandler(e)}))}stop(){this.running=!1,this.rl&&(this.rl.close(),this.rl=null)}async sendResponse(e){await this.write(JSON.stringify(e))}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t};await this.write(JSON.stringify(r))}onError(e){this.errorHandler=e}onClose(e){this.closeHandler=e}reconnect(){if(this.inputStream.readableEnded===!0){this.running=!1,this.closeHandler&&this.closeHandler();return}this.rl&&(this.rl.close(),this.rl=null),this.running=!1,this.start()}getMetrics(){return{...this.metrics}}isRunning(){return this.running}async handleLine(e){if(!e.trim())return;if(this.metrics.bytesReceived+=Buffer.byteLength(e,"utf-8"),Buffer.byteLength(e,"utf-8")>this.maxMessageSize){this.metrics.errors++,await this.sendError(null,rn.INVALID_REQUEST,"Message too large");return}let t;try{t=k(e)}catch{this.metrics.errors++,await this.sendError(null,rn.PARSE_ERROR,"Parse error");return}if(t.jsonrpc!=="2.0"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Invalid JSON-RPC version");return}if(!t.method||typeof t.method!="string"){this.metrics.errors++,await this.sendError(t.id??null,rn.INVALID_REQUEST,"Missing or invalid method");return}this.metrics.messagesReceived++,t.id!==void 0?await this.handleRequest(t):await this.handleNotification(t)}async handleRequest(e){if(!this.requestHandler){await this.sendError(e.id,rn.INTERNAL_ERROR,"No request handler registered");return}try{let t=await this.requestHandler(e);await this.sendResponse({jsonrpc:"2.0",id:e.id,result:t})}catch(t){if(z0(t))await this.sendError(e.id,t.code,t.message,t.data);else{let r=t;await this.sendError(e.id,rn.INTERNAL_ERROR,r.message||"Internal error")}}}async handleNotification(e){if(this.notificationHandler)try{await this.notificationHandler(e)}catch(t){this.metrics.errors++,console.error("[StdioTransport] Notification handler error:",t)}}async sendError(e,t,r,n){let i={jsonrpc:"2.0",id:e,error:{code:t,message:r,data:n}};await this.sendResponse(i)}async write(e){let r=[0,500,1e3];for(let n=0;n<3;n++)try{await this.writeOnce(e);return}catch(i){if(n<2)console.error(`[StdioTransport] Write attempt ${n+1} failed, retrying in ${r[n+1]}ms...`),await new Promise(s=>setTimeout(s,r[n+1]));else throw i}}async writeOnce(e){let t=e+`
|
|
5999
5999
|
`;return this.outputStream.writableNeedDrain&&await new Promise((r,n)=>{let i=setTimeout(()=>{n(new Error("Transport drain timeout after 30 seconds"))},3e4);this.outputStream.once("drain",()=>{clearTimeout(i),r()})}),new Promise((r,n)=>{let i=setTimeout(()=>{this.metrics.errors++,n(new Error("Transport write timeout after 120 seconds"))},12e4);this.outputStream.write(t,"utf-8",s=>{clearTimeout(i),s?(this.metrics.errors++,n(s)):(this.metrics.messagesSent++,this.metrics.bytesSent+=Buffer.byteLength(t,"utf-8"),r())})})}};function V0(o){return new U0(o)}N();B();N();var Yre={keepAliveInterval:15e3,connectionTimeout:3e5,maxConnections:1e3,enableMetrics:!0},Af=class{config;connections=new Map;threadIndex=new Map;closedConnections=[];keepAliveTimers=new Map;timeoutTimers=new Map;disposed=!1;constructor(e={}){this.config={...Yre,...e}}createConnection(e,t,r){if(this.disposed)throw new Error("ConnectionManager has been disposed");if(this.connections.size>=this.config.maxConnections)throw new Error(`Maximum connections (${this.config.maxConnections}) exceeded`);let n=R(),i=Date.now(),s={id:n,threadId:e,runId:t,createdAt:i,lastActivity:i,response:r,abortController:new AbortController,state:"connecting",metrics:{eventsSent:0,bytesSent:0,keepAlivesSent:0,errors:0,startTime:i}};this.connections.set(n,s);let a=this.threadIndex.get(e);return a||(a=new Set,this.threadIndex.set(e,a)),a.add(n),this.startKeepAlive(n),this.startTimeout(n),s}getConnection(e){return this.connections.get(e)}getConnectionByThreadId(e){let t=this.threadIndex.get(e);if(t)for(let r of t){let n=this.connections.get(r);if(n)return n}}getActiveConnections(){return Array.from(this.connections.values()).filter(e=>e.state==="open"||e.state==="connecting")}updateState(e,t){let r=this.connections.get(e);r&&(r.state=t,r.lastActivity=Date.now(),t==="closed"&&(r.metrics.endTime=Date.now()))}recordEventSent(e,t){let r=this.connections.get(e);r&&(r.metrics.eventsSent++,r.metrics.bytesSent+=t,r.lastActivity=Date.now(),this.resetTimeout(e))}recordError(e){let t=this.connections.get(e);t&&t.metrics.errors++}closeConnection(e,t){let r=this.connections.get(e);if(!r)return;if(this.stopKeepAlive(e),this.stopTimeout(e),r.state="closing",r.metrics.endTime=Date.now(),r.abortController.abort(t||"Connection closed"),!r.response.writableEnded)try{r.response.end()}catch{}for(r.state="closed",this.closedConnections.push(r);this.closedConnections.length>1e3;)this.closedConnections.shift();let n=this.threadIndex.get(r.threadId);n&&(n.delete(e),n.size===0&&this.threadIndex.delete(r.threadId)),this.connections.delete(e)}closeThreadConnections(e,t){let r=this.threadIndex.get(e);if(!r)return;let n=Array.from(r);for(let i of n)this.closeConnection(i,t)}getMetrics(){let e=Array.from(this.connections.values()),t=[...e,...this.closedConnections],r=e.filter(s=>s.state==="open"||s.state==="connecting"),n=t.filter(s=>s.metrics.endTime).map(s=>(s.metrics.endTime??0)-s.metrics.startTime),i=n.length>0?n.reduce((s,a)=>s+a,0)/n.length:0;return{totalConnections:t.length,activeConnections:r.length,totalEventsSent:t.reduce((s,a)=>s+a.metrics.eventsSent,0),totalBytesSent:t.reduce((s,a)=>s+a.metrics.bytesSent,0),totalErrors:t.reduce((s,a)=>s+a.metrics.errors,0),averageConnectionDuration:i}}dispose(){if(this.disposed)return;this.disposed=!0;let e=Array.from(this.connections.keys());for(let n of e)this.closeConnection(n,"Manager disposed");let t=Array.from(this.keepAliveTimers.values());for(let n of t)clearInterval(n);this.keepAliveTimers.clear();let r=Array.from(this.timeoutTimers.values());for(let n of r)clearTimeout(n);this.timeoutTimers.clear()}startKeepAlive(e){let t=setInterval(()=>{this.sendKeepAlive(e)},this.config.keepAliveInterval);this.keepAliveTimers.set(e,t)}stopKeepAlive(e){let t=this.keepAliveTimers.get(e);t&&(clearInterval(t),this.keepAliveTimers.delete(e))}sendKeepAlive(e){let t=this.connections.get(e);if(!(!t||t.state!=="open"))try{t.response.write(`: keep-alive
|
|
6000
6000
|
|
|
6001
6001
|
`),t.metrics.keepAlivesSent++,t.lastActivity=Date.now();let n=t.response;n.flush&&typeof n.flush=="function"&&n.flush()}catch{this.closeConnection(e,"Keep-alive failed")}}startTimeout(e){let t=setTimeout(()=>{this.closeConnection(e,"Connection timeout")},this.config.connectionTimeout);this.timeoutTimers.set(e,t)}stopTimeout(e){let t=this.timeoutTimers.get(e);t&&(clearTimeout(t),this.timeoutTimers.delete(e))}resetTimeout(e){this.stopTimeout(e),this.startTimeout(e)}};function J0(o){return new Af(o)}var Je={RUN_STARTED:"RUN_STARTED",RUN_FINISHED:"RUN_FINISHED",RUN_ERROR:"RUN_ERROR",STEP_STARTED:"STEP_STARTED",STEP_FINISHED:"STEP_FINISHED",TEXT_MESSAGE_START:"TEXT_MESSAGE_START",TEXT_MESSAGE_CONTENT:"TEXT_MESSAGE_CONTENT",TEXT_MESSAGE_END:"TEXT_MESSAGE_END",TOOL_CALL_START:"TOOL_CALL_START",TOOL_CALL_ARGS:"TOOL_CALL_ARGS",TOOL_CALL_END:"TOOL_CALL_END",TOOL_CALL_RESULT:"TOOL_CALL_RESULT",STATE_SNAPSHOT:"STATE_SNAPSHOT",STATE_DELTA:"STATE_DELTA",MESSAGES_SNAPSHOT:"MESSAGES_SNAPSHOT",ACTIVITY_SNAPSHOT:"ACTIVITY_SNAPSHOT",ACTIVITY_DELTA:"ACTIVITY_DELTA",RAW:"RAW",CUSTOM:"CUSTOM"};var Zre={keepAliveInterval:15e3,maxBufferSize:100,flushInterval:50,parseBody:!0,maxBodySize:1024*1024,connectionTimeout:3e5,customHeaders:{}},Y0=class{buffer=[];flushTimer=null;flushInterval;maxSize;onFlush;constructor(e,t,r){this.flushInterval=e,this.maxSize=t,this.onFlush=r}add(e){if(this.buffer.push(e),this.buffer.length>=this.maxSize){this.flush();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flush()},this.flushInterval))}flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.buffer.length>0){let e=this.buffer;this.buffer=[],this.onFlush(e)}}clear(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.buffer=[]}get size(){return this.buffer.length}},xf=class{config;connectionManager;agentHandler=null;disposed=!1;constructor(e={}){this.config={...Zre,...e},this.connectionManager=J0({keepAliveInterval:this.config.keepAliveInterval,connectionTimeout:this.config.connectionTimeout})}setAgentHandler(e){this.agentHandler=e}async handleRequest(e,t){if(this.disposed){this.sendError(t,503,"Service Unavailable","Transport disposed");return}if(e.method!=="POST"){this.sendError(t,405,"Method Not Allowed","Only POST is supported");return}let r;try{r=await this.parseRequestBody(e)}catch(c){let l=c instanceof Error?c.message:"Failed to parse request body";this.sendError(t,400,"Bad Request",l);return}if(!r.threadId){this.sendError(t,400,"Bad Request","Missing required field: threadId");return}let n=r.runId||R();this.setSSEHeaders(t);let i;try{i=this.connectionManager.createConnection(r.threadId,n,t)}catch(c){let l=c instanceof Error?c.message:"Failed to create connection";this.sendError(t,503,"Service Unavailable",l);return}this.connectionManager.updateState(i.id,"open");let s=new Y0(this.config.flushInterval,this.config.maxBufferSize,c=>this.writeEvents(i,c)),a=c=>{i.state==="open"&&(c.timestamp||(c.timestamp=Date.now()),s.add(c))};e.on("close",()=>{s.clear(),this.connectionManager.closeConnection(i.id,"Client disconnected")}),e.on("error",()=>{s.clear(),this.connectionManager.recordError(i.id),this.connectionManager.closeConnection(i.id,"Request error")}),t.on("error",()=>{s.clear(),this.connectionManager.recordError(i.id),this.connectionManager.closeConnection(i.id,"Response error")}),a({type:Je.RUN_STARTED,threadId:r.threadId,runId:n}),s.flush();try{if(!this.agentHandler)throw new Error("No agent handler registered");await this.agentHandler(r,a,i.abortController.signal),s.flush(),i.state==="open"&&this.writeEvent(i,{type:Je.RUN_FINISHED,runId:n,outcome:"success",timestamp:Date.now()})}catch(c){s.flush();let l=c instanceof Error?c.message:"Unknown error";!(c instanceof Error&&c.name==="AbortError")&&i.state==="open"&&(this.writeEvent(i,{type:Je.RUN_ERROR,runId:n,message:l,code:"INTERNAL_ERROR",timestamp:Date.now()}),this.connectionManager.recordError(i.id))}finally{s.clear(),this.connectionManager.closeConnection(i.id,"Request complete")}}getMetrics(){return this.connectionManager.getMetrics()}getActiveConnectionsCount(){return this.connectionManager.getActiveConnections().length}closeAllConnections(e){let t=this.connectionManager.getActiveConnections();for(let r of t)this.connectionManager.closeConnection(r.id,e)}dispose(){this.disposed||(this.disposed=!0,this.connectionManager.dispose())}async parseRequestBody(e){if(e.body)return e.body;if(!this.config.parseBody)throw new Error("Request body parsing is disabled");return new Promise((t,r)=>{let n=[],i=0;e.on("data",s=>{if(i+=s.length,i>this.config.maxBodySize){r(new Error(`Request body exceeds maximum size of ${this.config.maxBodySize} bytes`));return}n.push(s)}),e.on("end",()=>{try{let s=Buffer.concat(n).toString("utf-8");if(!s){r(new Error("Empty request body"));return}let a=k(s);t(a)}catch{r(new Error("Invalid JSON in request body"))}}),e.on("error",s=>{r(s)})})}setSSEHeaders(e){e.setHeader("Content-Type","text/event-stream"),e.setHeader("Cache-Control","no-cache"),e.setHeader("Connection","keep-alive"),e.setHeader("X-Accel-Buffering","no");for(let[t,r]of Object.entries(this.config.customHeaders))e.setHeader(t,r);e.flushHeaders()}writeEvent(e,t){if(!(e.state!=="open"||e.response.writableEnded))try{let r=this.formatSSEEvent(t);e.response.write(r),this.connectionManager.recordEventSent(e.id,Buffer.byteLength(r,"utf-8"));let n=e.response;n.flush&&typeof n.flush=="function"&&n.flush()}catch{this.connectionManager.recordError(e.id)}}writeEvents(e,t){if(!(e.state!=="open"||e.response.writableEnded))try{let r=0,n=[];for(let a of t){let c=this.formatSSEEvent(a);n.push(c),r+=Buffer.byteLength(c,"utf-8")}let i=n.join("");e.response.write(i),this.connectionManager.recordEventSent(e.id,r);let s=e.response;s.flush&&typeof s.flush=="function"&&s.flush()}catch{this.connectionManager.recordError(e.id)}}formatSSEEvent(e){let t=e.type,r=JSON.stringify(e);return`event: ${t}
|
|
@@ -17,7 +17,7 @@ import { safeJsonParse } from '../../safe-json.js';
|
|
|
17
17
|
* Default Gemini configuration
|
|
18
18
|
*/
|
|
19
19
|
export const DEFAULT_GEMINI_CONFIG = {
|
|
20
|
-
model: 'gemini-1.5-pro
|
|
20
|
+
model: 'gemini-2.5-flash', // gemini-1.5-pro was retired ("not found for API version"); 2.5-flash is current
|
|
21
21
|
maxTokens: 8192,
|
|
22
22
|
temperature: 0.7,
|
|
23
23
|
timeoutMs: 60000,
|
|
@@ -42,6 +42,10 @@ export const GEMINI_PRICING = {
|
|
|
42
42
|
'gemini-1.5-flash': { input: 0.075, output: 0.3 },
|
|
43
43
|
'gemini-1.5-flash-latest': { input: 0.075, output: 0.3 },
|
|
44
44
|
'gemini-2.0-flash-exp': { input: 0.075, output: 0.3 },
|
|
45
|
+
// Gemini 2.5 (current generation)
|
|
46
|
+
'gemini-2.5-pro': { input: 1.25, output: 10.0 },
|
|
47
|
+
'gemini-2.5-flash': { input: 0.3, output: 2.5 },
|
|
48
|
+
'gemini-flash-latest': { input: 0.3, output: 2.5 },
|
|
45
49
|
// Gemini Ultra (flagship)
|
|
46
50
|
'gemini-ultra': { input: 7.0, output: 21.0 },
|
|
47
51
|
'gemini-1.0-ultra': { input: 7.0, output: 21.0 },
|
|
@@ -393,15 +397,18 @@ export class GeminiProvider {
|
|
|
393
397
|
if (this.cachedModels) {
|
|
394
398
|
return this.cachedModels;
|
|
395
399
|
}
|
|
400
|
+
// Current text-generation models (verified via Gemini ListModels API 2026-06-27).
|
|
401
|
+
// Prefer the `-latest` aliases as defaults so they don't rot (gemini-1.5-pro was retired).
|
|
396
402
|
return [
|
|
397
|
-
'gemini-
|
|
398
|
-
'gemini-
|
|
399
|
-
'gemini-
|
|
400
|
-
'gemini-
|
|
401
|
-
'gemini-
|
|
402
|
-
'gemini-
|
|
403
|
-
'gemini-2.0-flash
|
|
404
|
-
'gemini-
|
|
403
|
+
'gemini-flash-latest',
|
|
404
|
+
'gemini-pro-latest',
|
|
405
|
+
'gemini-flash-lite-latest',
|
|
406
|
+
'gemini-2.5-pro',
|
|
407
|
+
'gemini-2.5-flash',
|
|
408
|
+
'gemini-2.5-flash-lite',
|
|
409
|
+
'gemini-2.0-flash',
|
|
410
|
+
'gemini-2.0-flash-lite',
|
|
411
|
+
'gemini-3.5-flash',
|
|
405
412
|
];
|
|
406
413
|
}
|
|
407
414
|
/**
|
|
@@ -485,7 +492,6 @@ export class GeminiProvider {
|
|
|
485
492
|
*/
|
|
486
493
|
handleApiError(status, data, model) {
|
|
487
494
|
const message = data.error?.message ?? 'Unknown API error';
|
|
488
|
-
const errorStatus = data.error?.status ?? '';
|
|
489
495
|
switch (status) {
|
|
490
496
|
case 400:
|
|
491
497
|
// Check for context length exceeded FIRST (message-based detection)
|