agentic-qe 3.10.7 → 3.10.9
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/skills-manifest.json +1 -1
- package/CHANGELOG.md +84 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-TRSV37EA.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-6I3JMU2M.js → agent-booster-wasm-RPAOJXZ3.js} +2 -2
- package/dist/cli/chunks/{agent-handler-XWI7YM6R.js → agent-handler-SMD5CAS6.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-QFZKQN2L.js → agent-memory-branch-3IOQIQ7Y.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-CVJRJOSO.js +2 -0
- package/dist/cli/chunks/{arena-5HNPVTBZ.js → arena-AP2J62WO.js} +4 -4
- package/dist/cli/chunks/{arena-P4IUBKZP.js → arena-GT3D6EAO.js} +2 -2
- package/dist/cli/chunks/{audit-PBSH25VZ.js → audit-Q3GJ5354.js} +2 -2
- package/dist/cli/chunks/base-BX4A2D4V.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-ILDTCGLZ.js → better-sqlite3-6A6EAXAT.js} +2 -2
- package/dist/cli/chunks/{brain-handler-EVYRCKXI.js → brain-handler-2Z4ILQF3.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-SUDGYJQJ.js → branch-enumerator-EZWGL4UM.js} +2 -2
- package/dist/cli/chunks/{browser-4UKMW2RE.js → browser-YZELFPLJ.js} +2 -2
- package/dist/cli/chunks/browser-workflow-O3RL7EYT.js +2 -0
- package/dist/cli/chunks/{chunk-QBVFONWU.js → chunk-246Z3PH6.js} +2 -2
- package/dist/cli/chunks/{chunk-B5ZJV7GZ.js → chunk-2I5QLMQF.js} +2 -2
- package/dist/cli/chunks/{chunk-AW3LGLC3.js → chunk-2K2X75UF.js} +2 -2
- package/dist/cli/chunks/{chunk-OW4LJ5HE.js → chunk-2WRVNEIR.js} +2 -2
- package/dist/cli/chunks/{chunk-EWNJK2BU.js → chunk-2WSEJHFQ.js} +1 -1
- package/dist/cli/chunks/{chunk-6RG7ZJ2H.js → chunk-352W5G4G.js} +2 -2
- package/dist/cli/chunks/{chunk-7NK2H7H5.js → chunk-3HT4CT6F.js} +2 -2
- package/dist/cli/chunks/{chunk-MDVJVY4C.js → chunk-3YKJGKOY.js} +4 -4
- package/dist/cli/chunks/{chunk-OPLLH67G.js → chunk-42FBJF73.js} +1 -1
- package/dist/cli/chunks/{chunk-IXAABYGS.js → chunk-4BB75U6N.js} +2 -2
- package/dist/cli/chunks/{chunk-LJHCPN4E.js → chunk-4D3LVXUD.js} +2 -2
- package/dist/cli/chunks/{chunk-VPBXVZWE.js → chunk-4EJTE5TL.js} +1 -1
- package/dist/cli/chunks/{chunk-I7M574IO.js → chunk-4MUZGQPE.js} +2 -2
- package/dist/cli/chunks/{chunk-M7SO5KNJ.js → chunk-57XCLC55.js} +2 -2
- package/dist/cli/chunks/{chunk-QBVS4CXM.js → chunk-5HLOQEKL.js} +1 -1
- package/dist/cli/chunks/{chunk-XWPUCPYW.js → chunk-5U5SEO7C.js} +2 -2
- package/dist/cli/chunks/{chunk-YB4GXJJG.js → chunk-5X73HV2P.js} +1 -1
- package/dist/cli/chunks/{chunk-OSETFZVE.js → chunk-62MH7QAQ.js} +2 -2
- package/dist/cli/chunks/{chunk-64BSODHA.js → chunk-6HPI6YX3.js} +2 -2
- package/dist/cli/chunks/{chunk-SG6O3PXZ.js → chunk-6TR3OM7C.js} +2 -2
- package/dist/cli/chunks/{chunk-FQBNPSV2.js → chunk-757YHKIJ.js} +2 -2
- package/dist/cli/chunks/{chunk-JJELOEIY.js → chunk-7C5HI4ZA.js} +4 -4
- package/dist/cli/chunks/chunk-7D5JE46U.js +2 -0
- package/dist/cli/chunks/{chunk-L2ZSYIDA.js → chunk-7NT34MLU.js} +1 -1
- package/dist/cli/chunks/{chunk-6QBD64W3.js → chunk-7PYEJ4NV.js} +2 -2
- package/dist/cli/chunks/{chunk-ISLI6D4K.js → chunk-7S6D5K4X.js} +2 -2
- package/dist/cli/chunks/chunk-ABJPFKHE.js +2 -0
- package/dist/cli/chunks/{chunk-LEZ2MGHM.js → chunk-ABVBHH7P.js} +3 -3
- package/dist/cli/chunks/{chunk-V7WBNB2S.js → chunk-AHUX7QSE.js} +2 -2
- package/dist/cli/chunks/{chunk-DPT37UHR.js → chunk-AU4DQMLJ.js} +4 -4
- package/dist/cli/chunks/{chunk-MOI74MMX.js → chunk-BG2FN5K2.js} +2 -2
- package/dist/cli/chunks/{chunk-JNQVPTOM.js → chunk-BM52ZEAD.js} +2 -2
- package/dist/cli/chunks/{chunk-BLFZFKT6.js → chunk-BSMUT672.js} +2 -2
- package/dist/cli/chunks/{chunk-34NT5NBZ.js → chunk-BVEQPMOF.js} +2 -2
- package/dist/cli/chunks/{chunk-QLVZEEPR.js → chunk-BYVARYGB.js} +2 -2
- package/dist/cli/chunks/{chunk-QDBFB4XD.js → chunk-C6GQIUKW.js} +2 -2
- package/dist/cli/chunks/{chunk-X6OJFP7G.js → chunk-C6JULAWA.js} +2 -2
- package/dist/cli/chunks/{chunk-76SUEI7S.js → chunk-CDJIYJIA.js} +1 -1
- package/dist/cli/chunks/{chunk-2J4ZUUU5.js → chunk-CLJNAQXB.js} +2 -2
- package/dist/cli/chunks/{chunk-DU7Y54JI.js → chunk-CLSHSVMY.js} +1 -1
- package/dist/cli/chunks/{chunk-O4B6FFC5.js → chunk-CREORFJV.js} +1 -1
- package/dist/cli/chunks/{chunk-S4NNQE4L.js → chunk-CVRTXIYP.js} +1 -1
- package/dist/cli/chunks/{chunk-TTLAWPEN.js → chunk-CWRSQQHV.js} +2 -2
- package/dist/cli/chunks/{chunk-R2B6EQQF.js → chunk-D2JCSWYM.js} +2 -2
- package/dist/cli/chunks/{chunk-Z44VJC5U.js → chunk-D7NWDUY3.js} +2 -2
- package/dist/cli/chunks/chunk-DK6WWNCL.js +2 -0
- package/dist/cli/chunks/{chunk-X3HRJV65.js → chunk-DNE6MVNA.js} +1 -1
- package/dist/cli/chunks/{chunk-UURGDFGU.js → chunk-DZWZASDV.js} +1 -1
- package/dist/cli/chunks/{chunk-L6NB4UHR.js → chunk-EL6F72JN.js} +2 -2
- package/dist/cli/chunks/{chunk-G7ISGLKP.js → chunk-EYGRNXQT.js} +1 -1
- package/dist/cli/chunks/{chunk-K6A3AWUI.js → chunk-FALB6Z2Y.js} +1 -1
- package/dist/cli/chunks/{chunk-TXXRBNOB.js → chunk-FD37QFXW.js} +1 -1
- package/dist/cli/chunks/{chunk-MWRKNBSY.js → chunk-G4KVGUQN.js} +2 -2
- package/dist/cli/chunks/{chunk-32E2OPIE.js → chunk-G7V2HDTH.js} +3 -3
- package/dist/cli/chunks/{chunk-YMBPKBKG.js → chunk-GPALZJD3.js} +1 -1
- package/dist/cli/chunks/{chunk-3IJS52OS.js → chunk-H4SHHYRD.js} +2 -2
- package/dist/cli/chunks/{chunk-3XEL7XCA.js → chunk-H7AQ7M3J.js} +1 -1
- package/dist/cli/chunks/{chunk-CW7JQVXV.js → chunk-HAC7NB6R.js} +2 -2
- package/dist/cli/chunks/{chunk-KXENXRZE.js → chunk-HGKZOSAI.js} +1 -1
- package/dist/cli/chunks/{chunk-L3EQQMFI.js → chunk-HQZX4XYH.js} +2 -2
- package/dist/cli/chunks/{chunk-LFSQSLNP.js → chunk-HZSYCVLC.js} +2 -2
- package/dist/cli/chunks/{chunk-2JWFS2K2.js → chunk-I5C7O5IQ.js} +2 -2
- package/dist/cli/chunks/{chunk-LSHUPEQQ.js → chunk-I7RTTJH5.js} +2 -2
- package/dist/cli/chunks/{chunk-R7KIC6TL.js → chunk-ILPIH4Z6.js} +1 -1
- package/dist/cli/chunks/{chunk-262F3EMN.js → chunk-IR7PJUO7.js} +2 -2
- package/dist/cli/chunks/{chunk-MMR23KAO.js → chunk-J6GKKXCP.js} +2 -2
- package/dist/cli/chunks/{chunk-INI3AGF5.js → chunk-JZNMU63B.js} +2 -2
- package/dist/cli/chunks/{chunk-J5ETX2DG.js → chunk-K23XK33X.js} +2 -2
- package/dist/cli/chunks/{chunk-S423UHYM.js → chunk-KAMFT25W.js} +2 -2
- package/dist/cli/chunks/{chunk-AKSCYNFH.js → chunk-KJA5A3TV.js} +2 -2
- package/dist/cli/chunks/{chunk-76JYG426.js → chunk-KRAWWBX5.js} +2 -2
- package/dist/cli/chunks/{chunk-4RGV6Z2H.js → chunk-L5IO7QNO.js} +2 -2
- package/dist/cli/chunks/{chunk-HBWAMCVB.js → chunk-L5NEEGKO.js} +14 -14
- package/dist/cli/chunks/{chunk-BRYYQQUV.js → chunk-LHKQW72O.js} +1 -1
- package/dist/cli/chunks/{chunk-BPC6X6VR.js → chunk-LT6QHDPK.js} +2 -2
- package/dist/cli/chunks/{chunk-HARYQMWN.js → chunk-MDED3HJI.js} +2 -2
- package/dist/cli/chunks/{chunk-HDLF6LGO.js → chunk-NLUWPS2H.js} +3 -3
- package/dist/cli/chunks/{chunk-CGBEI7UH.js → chunk-NMQEU4BG.js} +2 -2
- package/dist/cli/chunks/{chunk-K6IU2MV4.js → chunk-NOWGQ6YZ.js} +1 -1
- package/dist/cli/chunks/{chunk-YLXUF5KW.js → chunk-NYBAH76S.js} +3 -3
- package/dist/cli/chunks/{chunk-TIUC5LRA.js → chunk-O36VC7B7.js} +2 -2
- package/dist/cli/chunks/{chunk-3O4Q4GAX.js → chunk-OD4OIPXO.js} +15 -13
- package/dist/cli/chunks/{chunk-LUZH2IZY.js → chunk-OF3EMOWN.js} +2 -2
- package/dist/cli/chunks/{chunk-AKL5A3IZ.js → chunk-OIN3Y4BY.js} +1 -1
- package/dist/cli/chunks/chunk-OPKEQYAC.js +2 -0
- package/dist/cli/chunks/{chunk-TY7XPI6R.js → chunk-OQUH7657.js} +2 -2
- package/dist/cli/chunks/{chunk-F5RZSNHI.js → chunk-OSP5AJAB.js} +2 -2
- package/dist/cli/chunks/{chunk-6A2HRMTD.js → chunk-PFGH7TWL.js} +2 -2
- package/dist/cli/chunks/{chunk-MK73CCKO.js → chunk-PYQZ4OA3.js} +2 -2
- package/dist/cli/chunks/{chunk-BU2I77YW.js → chunk-QAP5S7YC.js} +3 -3
- package/dist/cli/chunks/{chunk-JNXPRDNV.js → chunk-QE3CZGAC.js} +3 -3
- package/dist/cli/chunks/{chunk-5QMIVHFT.js → chunk-QFIKEZB5.js} +2 -2
- package/dist/cli/chunks/{chunk-AY4IEMRI.js → chunk-QHICG2NI.js} +2 -2
- package/dist/cli/chunks/{chunk-4I6FK67T.js → chunk-QHPLU5BU.js} +3 -3
- package/dist/cli/chunks/{chunk-HI4DA7Z3.js → chunk-QL6ZJ7RV.js} +2 -2
- package/dist/cli/chunks/{chunk-FK4JHBG4.js → chunk-QL7OOCPO.js} +2 -2
- package/dist/cli/chunks/{chunk-6OLPKIYU.js → chunk-QWXJRZEH.js} +1 -1
- package/dist/cli/chunks/{chunk-S7FNTWFM.js → chunk-R2M3RMCN.js} +2 -2
- package/dist/cli/chunks/{chunk-NKYMHEHY.js → chunk-RHOBDQXA.js} +2 -2
- package/dist/cli/chunks/{chunk-6F5KPT6U.js → chunk-RRSJ7BMF.js} +1 -1
- package/dist/cli/chunks/{chunk-RLXCFURS.js → chunk-RSWQY4NZ.js} +2 -2
- package/dist/cli/chunks/{chunk-UPDPD43T.js → chunk-S73EBPI5.js} +2 -2
- package/dist/cli/chunks/{chunk-OMDV6GFP.js → chunk-TIR3Z6TE.js} +1 -1
- package/dist/cli/chunks/{chunk-UVUVWA4B.js → chunk-TKZABUHO.js} +1 -1
- package/dist/cli/chunks/{chunk-4MJQJQLY.js → chunk-TOGD2JH2.js} +2 -2
- package/dist/cli/chunks/{chunk-QMGNYRR5.js → chunk-TVU6NMO3.js} +3 -3
- package/dist/cli/chunks/{chunk-C5CY5NSW.js → chunk-TXWUV3S5.js} +2 -2
- package/dist/cli/chunks/{chunk-3W6QASVB.js → chunk-U6TZVACK.js} +2 -2
- package/dist/cli/chunks/{chunk-L5UUUSSB.js → chunk-UJBIHPU5.js} +1 -1
- package/dist/cli/chunks/{chunk-FWLXK6AH.js → chunk-UPGKS6Z3.js} +2 -2
- package/dist/cli/chunks/{chunk-SLASYVNX.js → chunk-UU7OCRZM.js} +2 -2
- package/dist/cli/chunks/{chunk-WCXQA24H.js → chunk-UUA2NVUN.js} +8 -8
- package/dist/cli/chunks/{chunk-IYZWEYWJ.js → chunk-UX4UHYLE.js} +1 -1
- package/dist/cli/chunks/{chunk-V3KNHI5B.js → chunk-VDL277DX.js} +2 -2
- package/dist/cli/chunks/{chunk-RJBCIN2G.js → chunk-VHCHBMZC.js} +2 -2
- package/dist/cli/chunks/{chunk-222ZQTL5.js → chunk-VHYNRISI.js} +2 -2
- package/dist/cli/chunks/{chunk-4W5QWFU4.js → chunk-VIHFC67B.js} +1 -1
- package/dist/cli/chunks/{chunk-DYNO72WD.js → chunk-WOGWIMQK.js} +2 -2
- package/dist/cli/chunks/{chunk-SFW6IDMR.js → chunk-WPBVLIWQ.js} +10 -10
- package/dist/cli/chunks/{chunk-CJTDQJ7E.js → chunk-WWGGL3TR.js} +1 -1
- package/dist/cli/chunks/{chunk-2MLISLRR.js → chunk-X6YUGKMM.js} +1 -1
- package/dist/cli/chunks/{chunk-PY3HWJRJ.js → chunk-X7677BX3.js} +2 -2
- package/dist/cli/chunks/{chunk-MRLGQX7Y.js → chunk-XEMP2PNW.js} +2 -2
- package/dist/cli/chunks/{chunk-YBM4LUSF.js → chunk-XLK4GP3I.js} +2 -2
- package/dist/cli/chunks/chunk-XYRJL7YN.js +2 -0
- package/dist/cli/chunks/{chunk-OAXDI4XM.js → chunk-YB3PQ3UV.js} +1 -1
- package/dist/cli/chunks/{chunk-GUDOOOO6.js → chunk-YHFCLJMY.js} +1 -1
- package/dist/cli/chunks/{chunk-HELQ7CXL.js → chunk-YQBL5XTM.js} +1 -1
- package/dist/cli/chunks/chunk-Z6FRNWQA.js +6 -0
- package/dist/cli/chunks/{chunk-U7EGKKN3.js → chunk-ZT2DGSIO.js} +2 -2
- package/dist/cli/chunks/{chunk-DYSRMAZP.js → chunk-ZVF7QY4R.js} +1 -1
- package/dist/cli/chunks/{ci-OO42YBET.js → ci-KDEFR2X3.js} +2 -2
- package/dist/cli/chunks/{ci-output-YXMTEX7Q.js → ci-output-Z3WXRRFI.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-EHA4N643.js → circuit-breaker-GS44DEW2.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-E6G6SLYI.js → claude-flow-setup-OHVMHAAH.js} +2 -2
- package/dist/cli/chunks/client-T263ZXVV.js +2 -0
- package/dist/cli/chunks/cline-installer-5TCF4MZD.js +4 -0
- package/dist/cli/chunks/{code-Q3U6XDOO.js → code-3KCGTG7Z.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-BK2DC4MO.js → code-index-extractor-LJBI54MZ.js} +2 -2
- package/dist/cli/chunks/codex-installer-IB62Z6LA.js +8 -0
- package/dist/cli/chunks/{completions-TZ5F33TA.js → completions-JDXX7KKB.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-N7U4V7ID.js → complexity-analyzer-6JVDXXXP.js} +2 -2
- package/dist/cli/chunks/continuedev-installer-PUB45QVR.js +15 -0
- package/dist/cli/chunks/copilot-installer-QWJ36P22.js +3 -0
- package/dist/cli/chunks/core-handlers-ODKKGCFK.js +2 -0
- package/dist/cli/chunks/{cost-tracker-ZTIDLUFW.js → cost-tracker-J3KEJDL5.js} +2 -2
- package/dist/cli/chunks/{coverage-6G7T7TRQ.js → coverage-FWKRI2EY.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-APU725GC.js +2 -0
- package/dist/cli/chunks/cursor-installer-2HYCUCTH.js +3 -0
- package/dist/cli/chunks/{daemon-KTXGJJRI.js → daemon-BVP66DIZ.js} +4 -4
- package/dist/cli/chunks/{daemon-5A4GD6XA.js → daemon-G3DBRWDQ.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-4CUEQZD6.js → dag-attention-scheduler-2AQLNB4B.js} +2 -2
- package/dist/cli/chunks/{detect-I32JUSUE.js → detect-RUM5SHNE.js} +2 -2
- package/dist/cli/chunks/{dist-node-7ITNV6QS.js → dist-node-GX7MJHFT.js} +2 -2
- package/dist/cli/chunks/{domain-handler-LIFCXSZ4.js → domain-handler-OFBGZ2U5.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-67UWLHSK.js → domain-transfer-6CGRPRGR.js} +2 -2
- package/dist/cli/chunks/dream-PJ5GKY3J.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-4WC5RUD6.js → embed-and-insert-pattern-MUOEVQX2.js} +2 -2
- package/dist/cli/chunks/{eval-DLS2UAQ2.js → eval-SJMG67DE.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-VG5E6OJA.js → experience-capture-middleware-ICKN6IXX.js} +3 -3
- package/dist/cli/chunks/{fast-paths-262IVHDN.js → fast-paths-HXLBG3J4.js} +2 -2
- package/dist/cli/chunks/{feature-flags-L3K7DBN3.js → feature-flags-CRUB2ASU.js} +2 -2
- package/dist/cli/chunks/{feature-flags-JJ3FHZGD.js → feature-flags-JYZSSQJC.js} +2 -2
- package/dist/cli/chunks/{file-discovery-Q3PBKVUW.js → file-discovery-YHHC7NTJ.js} +2 -2
- package/dist/cli/chunks/{fleet-LQ5S2YHG.js → fleet-2VGDL4YL.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-I33Z537H.js → gnn-wrapper-7ZAGD4S4.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-RYIRAGZ7.js → heartbeat-handler-HAW3JRHN.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-4ZHUIW3Q.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-UVJJ6TTP.js +2 -0
- package/dist/cli/chunks/hnsw-index-K6HS34JZ.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-SSENBBPR.js → hnsw-legacy-bridge-BO325POX.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-F262IAGH.js → hnswlib-node-YTK7S7GL.js} +2 -2
- package/dist/cli/chunks/{hooks-LR5KQMN5.js → hooks-HKM3JTFQ.js} +10 -10
- package/dist/cli/chunks/hybrid-router-25S7OH2Y.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-NDZA2DKP.js → hypergraph-engine-LGLGHK6B.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-ADMWVHBT.js → hypergraph-handler-6QDVREZA.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-UP4RDMJH.js +2 -0
- package/dist/cli/chunks/init-handler-XUQ7XHIE.js +74 -0
- package/dist/cli/chunks/init-wizard-2PAJ3GEC.js +2 -0
- package/dist/cli/chunks/kernel-7WOQGMMT.js +2 -0
- package/dist/cli/chunks/kilocode-installer-6CEZLVIX.js +4 -0
- package/dist/cli/chunks/{kiro-installer-TINLYZ22.js → kiro-installer-6CJGATOS.js} +4 -4
- package/dist/cli/chunks/knowledge-graph-FN2AWHGR.js +2 -0
- package/dist/cli/chunks/{learning-KBT3S5WW.js → learning-EIYTYZJY.js} +3 -3
- package/dist/cli/chunks/{llm-router-2MX5LUAB.js → llm-router-J4CI7VHU.js} +4 -4
- package/dist/cli/chunks/llm-router-service-C3UPBAS3.js +2 -0
- package/dist/cli/chunks/{load-IQWTGMLZ.js → load-CQPWGLQQ.js} +2 -2
- package/dist/cli/chunks/load-test-PQSGLDXJ.js +2 -0
- package/dist/cli/chunks/mcp-THOATWCO.js +2 -0
- package/dist/cli/chunks/{memory-XQVPI4UT.js → memory-NZHMHMRK.js} +5 -5
- package/dist/cli/chunks/memory-backend-6FR4RT5O.js +2 -0
- package/dist/cli/chunks/{memory-handlers-XD7MSFUN.js → memory-handlers-L2J54AQE.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-JC63UCWG.js → multi-model-executor-3P5E773H.js} +2 -2
- package/dist/cli/chunks/opencode-installer-IRZMKSNG.js +15 -0
- package/dist/cli/chunks/{orchestrator-B75QWJUF.js → orchestrator-UADLXTKP.js} +18 -18
- package/dist/cli/chunks/pattern-null-store-B2UX4NZY.js +2 -0
- package/dist/cli/chunks/{pipeline-TCBQ2UTZ.js → pipeline-QEH3XHXJ.js} +2 -2
- package/dist/cli/chunks/{platform-T43AYI3Z.js → platform-NEZ3NXLT.js} +2 -2
- package/dist/cli/chunks/{plugin-MSI3ZU3Z.js → plugin-O33HR2VO.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-V62CWI6M.js → prime-radiant-advanced-wasm-MBUMFEX7.js} +2 -2
- package/dist/cli/chunks/protocol-executor-OQ6SL7SR.js +2 -0
- package/dist/cli/chunks/{protocol-handler-OH2INET2.js → protocol-handler-L455UOUT.js} +2 -2
- package/dist/cli/chunks/{prove-6PTMXMUL.js → prove-3XA3SMAA.js} +2 -2
- package/dist/cli/chunks/provider-manager-DQWHW2RG.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-3JS2CZAE.js +2 -0
- package/dist/cli/chunks/{quality-PLNQN5GU.js → quality-H6Z5JH5B.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-KXCWEM3Y.js +2 -0
- package/dist/cli/chunks/{real-embeddings-OW4OKR77.js → real-embeddings-5DNJ4KEM.js} +2 -2
- package/dist/cli/chunks/roocode-installer-KHXKR2FK.js +4 -0
- package/dist/cli/chunks/router-OVLIKT55.js +2 -0
- package/dist/cli/chunks/routing-feedback-2BYCXNXX.js +2 -0
- package/dist/cli/chunks/{routing-handler-CKFXXPMI.js → routing-handler-WAMGESEM.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-GERRPTJL.js → ruvector-commands-4J7XC6XY.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-5FAB2QPA.js → rvf-dual-writer-3PZEN6XN.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-46COKWYB.js → rvf-migration-adapter-OIUNRQSU.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-AJVRWSNC.js → rvf-migration-coordinator-QZXDI4I5.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-YNUYOQ5C.js +2 -0
- package/dist/cli/chunks/safe-db-6TYYEU7C.js +2 -0
- package/dist/cli/chunks/schedule-XVH7RTVY.js +2 -0
- package/dist/cli/chunks/scheduler-DHZBN5HA.js +2 -0
- package/dist/cli/chunks/{security-Q622IVRB.js → security-5NY77AMD.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-EST24R3R.js → shared-rvf-adapter-MHPUZIMW.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-CP6EXKBT.js → shared-rvf-dual-writer-ITLDYHCX.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-NR5WXTPN.js +2 -0
- package/dist/cli/chunks/{status-handler-LLRQB4E2.js → status-handler-7RBRIXZD.js} +2 -2
- package/dist/cli/chunks/{structural-health-BUFWTNN2.js → structural-health-MQPY6GA6.js} +2 -2
- package/dist/cli/chunks/{sync-JDG4SNT5.js → sync-66KCEANE.js} +2 -2
- package/dist/cli/chunks/{sync-RDL2RUOV.js → sync-USVQTHKN.js} +2 -2
- package/dist/cli/chunks/{task-handler-KPP6ZXA6.js → task-handler-4UI4FPPW.js} +2 -2
- package/dist/cli/chunks/{task-handlers-MRK2BQWI.js → task-handlers-KRII3GVV.js} +3 -3
- package/dist/cli/chunks/{test-7NYFTHRY.js → test-JHN2MVEG.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-LGPKDMWD.js → test-scheduling-ZWTEGS3S.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-H5JHB7TD.js → token-bootstrap-YWXL6AS5.js} +2 -2
- package/dist/cli/chunks/{token-usage-TWPDS5U3.js → token-usage-INII2XM3.js} +2 -2
- package/dist/cli/chunks/{transformers-GRNPPUHM.js → transformers-DVFGDNZC.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-DOH5F6TO.js → tree-sitter-wasm-parser-W2XJT3XF.js} +2 -2
- package/dist/cli/chunks/{types-NYV3YKE3.js → types-GBZ5Q2GP.js} +2 -2
- package/dist/cli/chunks/unified-memory-WJEZ5YAK.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-6ZA2PMYO.js +2 -0
- package/dist/cli/chunks/unified-persistence-SWH6R7MA.js +2 -0
- package/dist/cli/chunks/{upgrade-GDJMRYAT.js → upgrade-2JEXEGQX.js} +2 -2
- package/dist/cli/chunks/{validate-SIRFOPPM.js → validate-GDCM5YTS.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-XGMJYR6X.js → validate-swarm-QZ5RSJEU.js} +2 -2
- package/dist/cli/chunks/{vibium-NP6ENRKV.js → vibium-I5BMT734.js} +2 -2
- package/dist/cli/chunks/visual-security-PH5JQZCZ.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-YDBWPYZD.js → web-tree-sitter-3QY2LMLP.js} +2 -2
- package/dist/cli/chunks/windsurf-installer-V7OBPLOB.js +7 -0
- package/dist/cli/chunks/{witness-chain-YHLBWQQ3.js → witness-chain-BNJ4VSZX.js} +2 -2
- package/dist/cli/chunks/witness-chain-WYMBNGSL.js +2 -0
- package/dist/cli/chunks/{workflow-TA6RY7R5.js → workflow-3FJSNLPI.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-56JIXCI4.js +2 -0
- package/dist/cli/chunks/{wrappers-DS77IK4H.js → wrappers-ERTQNIPK.js} +2 -2
- package/dist/cli/commands/mcp.js +28 -28
- package/dist/cli/handlers/init-handler.d.ts +4 -0
- package/dist/cli/handlers/init-handler.js +50 -1
- package/dist/coordination/result-saver.js +4 -0
- package/dist/domains/code-intelligence/coordinator-hypergraph.js +9 -4
- package/dist/domains/code-intelligence/coordinator.js +9 -4
- package/dist/init/cline-installer.d.ts +6 -0
- package/dist/init/cline-installer.js +3 -1
- package/dist/init/codex-installer.d.ts +6 -0
- package/dist/init/codex-installer.js +3 -1
- package/dist/init/continuedev-installer.d.ts +6 -0
- package/dist/init/continuedev-installer.js +10 -3
- package/dist/init/copilot-installer.d.ts +6 -0
- package/dist/init/copilot-installer.js +3 -1
- package/dist/init/cursor-installer.d.ts +6 -0
- package/dist/init/cursor-installer.js +3 -1
- package/dist/init/kilocode-installer.d.ts +6 -0
- package/dist/init/kilocode-installer.js +3 -1
- package/dist/init/kiro-installer.d.ts +5 -0
- package/dist/init/kiro-installer.js +4 -4
- package/dist/init/opencode-installer.d.ts +39 -17
- package/dist/init/opencode-installer.js +166 -114
- package/dist/init/orchestrator.js +2 -0
- package/dist/init/phases/04-database.d.ts +5 -0
- package/dist/init/phases/04-database.js +7 -0
- package/dist/init/phases/05-learning.js +3 -0
- package/dist/init/phases/06-code-intelligence.js +6 -0
- package/dist/init/phases/07-hooks.js +5 -0
- package/dist/init/phases/08-mcp.js +34 -7
- package/dist/init/phases/09-assets.js +35 -28
- package/dist/init/phases/10-workers.js +4 -0
- package/dist/init/phases/11-claude-md.d.ts +1 -0
- package/dist/init/phases/11-claude-md.js +8 -0
- package/dist/init/phases/12-verification.js +10 -5
- package/dist/init/phases/13-governance.js +5 -0
- package/dist/init/phases/phase-interface.d.ts +14 -0
- package/dist/init/platform-config-generator.d.ts +3 -1
- package/dist/init/platform-config-generator.js +31 -17
- package/dist/init/roocode-installer.d.ts +6 -0
- package/dist/init/roocode-installer.js +3 -1
- package/dist/init/windsurf-installer.d.ts +6 -0
- package/dist/init/windsurf-installer.js +3 -1
- package/dist/integrations/ruvector/rvf-native-adapter.js +8 -0
- package/dist/integrations/ruvector/shared-rvf-dual-writer.js +5 -0
- package/dist/kernel/kernel.js +4 -2
- package/dist/kernel/unified-memory.js +66 -48
- package/dist/learning/rvf-pattern-store.js +8 -0
- package/dist/mcp/bundle.js +361 -358
- package/dist/mcp/entry.js +52 -6
- package/dist/mcp/handlers/core-handlers.js +7 -2
- package/dist/mcp/protocol-server.js +27 -1
- package/dist/mcp/services/session-store.d.ts +1 -0
- package/dist/mcp/services/session-store.js +7 -0
- package/dist/mcp/tools/base.d.ts +6 -0
- package/dist/mcp/tools/base.js +16 -0
- package/dist/optimization/session-cache.d.ts +11 -0
- package/dist/optimization/session-cache.js +31 -0
- package/package.json +7 -5
- package/dist/cli/chunks/adapter-TTIBYXH2.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-CTV5OLSN.js +0 -2
- package/dist/cli/chunks/base-ISNCJZ7A.js +0 -2
- package/dist/cli/chunks/browser-workflow-OD32QTTI.js +0 -2
- package/dist/cli/chunks/chunk-DF7V6X3N.js +0 -2
- package/dist/cli/chunks/chunk-I64BLAFS.js +0 -2
- package/dist/cli/chunks/chunk-LHZYTNOQ.js +0 -6
- package/dist/cli/chunks/chunk-LRRQEAP5.js +0 -2
- package/dist/cli/chunks/chunk-XCYPVJ34.js +0 -2
- package/dist/cli/chunks/chunk-XK7P7OXO.js +0 -2
- package/dist/cli/chunks/client-N4FQ6SMD.js +0 -2
- package/dist/cli/chunks/cline-installer-6JPWD64G.js +0 -4
- package/dist/cli/chunks/codex-installer-DA3GBMLN.js +0 -8
- package/dist/cli/chunks/continuedev-installer-DDDJGW26.js +0 -14
- package/dist/cli/chunks/copilot-installer-JVFCE6GT.js +0 -3
- package/dist/cli/chunks/core-handlers-SFD5HCA3.js +0 -2
- package/dist/cli/chunks/cross-domain-router-7HGRUNLT.js +0 -2
- package/dist/cli/chunks/cursor-installer-JFNYGSDD.js +0 -3
- package/dist/cli/chunks/dream-HPGD5TLD.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-O6TI5E4P.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-TOVTN23J.js +0 -2
- package/dist/cli/chunks/hnsw-index-KCZ75V7K.js +0 -2
- package/dist/cli/chunks/hybrid-router-4JEPC4JZ.js +0 -2
- package/dist/cli/chunks/impact-analyzer-3MHIU3SE.js +0 -2
- package/dist/cli/chunks/init-handler-MGCYDX62.js +0 -70
- package/dist/cli/chunks/init-wizard-ERBO5JNA.js +0 -2
- package/dist/cli/chunks/kernel-XJPIIWET.js +0 -2
- package/dist/cli/chunks/kilocode-installer-DQVWZUKP.js +0 -4
- package/dist/cli/chunks/knowledge-graph-NTJEG6ZE.js +0 -2
- package/dist/cli/chunks/llm-router-service-4T66BGB5.js +0 -2
- package/dist/cli/chunks/load-test-PM674TSK.js +0 -2
- package/dist/cli/chunks/mcp-GCTTJUBZ.js +0 -2
- package/dist/cli/chunks/memory-backend-53NQ5CG7.js +0 -2
- package/dist/cli/chunks/opencode-installer-6VJGEBIU.js +0 -3
- package/dist/cli/chunks/pattern-null-store-IF2RG2ON.js +0 -2
- package/dist/cli/chunks/protocol-executor-7AS75ZWT.js +0 -2
- package/dist/cli/chunks/provider-manager-AU2C4AET.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-WATQRCFO.js +0 -2
- package/dist/cli/chunks/queen-coordinator-IOCC4VQH.js +0 -2
- package/dist/cli/chunks/roocode-installer-C32LCYAJ.js +0 -4
- package/dist/cli/chunks/router-SCJMX6WA.js +0 -2
- package/dist/cli/chunks/routing-feedback-RWC7F553.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-W2RT6PTO.js +0 -2
- package/dist/cli/chunks/safe-db-HO2LCAO3.js +0 -2
- package/dist/cli/chunks/schedule-XENCR4MR.js +0 -2
- package/dist/cli/chunks/scheduler-WKZ3O2SS.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-IN6BOSCX.js +0 -2
- package/dist/cli/chunks/unified-memory-6MXOYRXZ.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-HY3JJD5Z.js +0 -2
- package/dist/cli/chunks/unified-persistence-LKQNQYRY.js +0 -2
- package/dist/cli/chunks/visual-security-7TBWICHP.js +0 -2
- package/dist/cli/chunks/windsurf-installer-MFI6EAPH.js +0 -7
- package/dist/cli/chunks/witness-chain-24SVOWQL.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-XBDXCTLY.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.10.
|
|
2
|
-
import{c as u}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.10.9");process.exit(0)}
|
|
2
|
+
import{c as u}from"./chunk-ABJPFKHE.js";function t(){return{...e}}function o(r){e={...e,...r}}function i(){e={...s}}function a(){return e.useBrowserMode}function E(){return e.useScreenshotCapture}function l(){return e.useVisualRegression}function c(){return e.useE2EExecution}function f(){return e.defaultHeadless}function d(){return e.useAutoRetry}function _(){return e.logPerformanceMetrics}function I(){return e.useAxeCore}function p(){let r={};process.env.VIBIUM_USE_BROWSER_MODE!==void 0&&(r.useBrowserMode=process.env.VIBIUM_USE_BROWSER_MODE==="true"),process.env.VIBIUM_USE_SCREENSHOT_CAPTURE!==void 0&&(r.useScreenshotCapture=process.env.VIBIUM_USE_SCREENSHOT_CAPTURE==="true"),process.env.VIBIUM_USE_VISUAL_REGRESSION!==void 0&&(r.useVisualRegression=process.env.VIBIUM_USE_VISUAL_REGRESSION==="true"),process.env.VIBIUM_USE_E2E_EXECUTION!==void 0&&(r.useE2EExecution=process.env.VIBIUM_USE_E2E_EXECUTION==="true"),process.env.VIBIUM_DEFAULT_HEADLESS!==void 0&&(r.defaultHeadless=process.env.VIBIUM_DEFAULT_HEADLESS==="true"),process.env.VIBIUM_USE_AUTO_RETRY!==void 0&&(r.useAutoRetry=process.env.VIBIUM_USE_AUTO_RETRY==="true"),process.env.VIBIUM_LOG_PERFORMANCE_METRICS!==void 0&&(r.logPerformanceMetrics=process.env.VIBIUM_LOG_PERFORMANCE_METRICS==="true"),process.env.VIBIUM_USE_AXE_CORE!==void 0&&(r.useAxeCore=process.env.VIBIUM_USE_AXE_CORE==="true"),o(r)}function U(){o({defaultHeadless:!0,useAutoRetry:!0,logPerformanceMetrics:!0})}function R(){o({defaultHeadless:!1,logPerformanceMetrics:!0})}function S(){o({useBrowserMode:!1,useScreenshotCapture:!1,useVisualRegression:!1,useE2EExecution:!1,useAxeCore:!1})}var s,e,n=u(()=>{s={useBrowserMode:!0,useScreenshotCapture:!0,useVisualRegression:!0,useE2EExecution:!0,defaultHeadless:!1,useAutoRetry:!0,logPerformanceMetrics:!0,useAxeCore:!0},e={...s}});export{s as a,t as b,o as c,i as d,a as e,E as f,l as g,c as h,f as i,d as j,_ as k,I as l,p as m,U as n,R as o,S as p,n as q};
|
|
@@ -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.10.
|
|
2
|
-
import{b as x,c as w,d as U,e as A}from"./chunk-QBVS4CXM.js";import{a as v,b as _}from"./chunk-X3HRJV65.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-L2ZSYIDA.js";import{a as P}from"./chunk-GUDOOOO6.js";import{b as I,c as H}from"./chunk-XWPUCPYW.js";import{i as z}from"./chunk-6OLPKIYU.js";var h={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},D=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as $}from"crypto";var C=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${$().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function E(p){return new C(p)}var R=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),s={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(s),this.trimRecords(),this.checkAlerts(),s}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,s)=>n+s.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=P[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,s)=>n+s.inputTokens+s.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function q(p){return new R(p)}H();var T=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new T(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function je(p,e){return new M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
|
|
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.10.9");process.exit(0)}
|
|
2
|
+
import{b as x,c as w,d as U,e as A}from"./chunk-5HLOQEKL.js";import{a as v,b as _}from"./chunk-DNE6MVNA.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-7NT34MLU.js";import{a as P}from"./chunk-YHFCLJMY.js";import{b as I,c as H}from"./chunk-5U5SEO7C.js";import{i as z}from"./chunk-QWXJRZEH.js";var h={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},D=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as $}from"crypto";var C=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${$().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function E(p){return new C(p)}var R=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),s={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(s),this.trimRecords(),this.checkAlerts(),s}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,s)=>n+s.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=P[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,s)=>n+s.inputTokens+s.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function q(p){return new R(p)}H();var T=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new T(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function je(p,e){return new M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
|
|
@@ -1,5 +1,5 @@
|
|
|
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.10.
|
|
2
|
-
import{a as D,b as _,c as $,d as I}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.10.9");process.exit(0)}
|
|
2
|
+
import{a as D,b as _,c as $,d as I}from"./chunk-YB3PQ3UV.js";import{a as X}from"./chunk-7C5HI4ZA.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-757YHKIJ.js";import{b as C,f as G,i as U}from"./chunk-RRSJ7BMF.js";import{g as R}from"./chunk-OQUH7657.js";import{e as H}from"./chunk-BVEQPMOF.js";import{i as j,m as de}from"./chunk-L5NEEGKO.js";import{a as z}from"./chunk-OPKEQYAC.js";import{c as T}from"./chunk-VHYNRISI.js";import{b as k,c as A}from"./chunk-X6YUGKMM.js";import{a as h,b as V,c as W}from"./chunk-5U5SEO7C.js";import{S as pe,b as B}from"./chunk-KRAWWBX5.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
|
|
3
3
|
describe('{{methodName}}', () => {
|
|
4
4
|
it('should {{expectedBehavior}}', {{async}} () => {
|
|
5
5
|
// Arrange
|
|
@@ -317,4 +317,4 @@ On promotion:
|
|
|
317
317
|
AND agent_id = 'aqe-hook-router'
|
|
318
318
|
AND state_key = ?
|
|
319
319
|
AND action_key = ?
|
|
320
|
-
`);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-
|
|
320
|
+
`);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-5DNJ4KEM.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-5DNJ4KEM.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
|
|
@@ -1,6 +1,6 @@
|
|
|
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.10.
|
|
2
|
-
import{e as x,f as C,j as y,k as R,q as F}from"./chunk-
|
|
3
|
-
Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-
|
|
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.10.9");process.exit(0)}
|
|
2
|
+
import{e as x,f as C,j as y,k as R,q as F}from"./chunk-PFGH7TWL.js";import{b as I,c as k}from"./chunk-5U5SEO7C.js";import{c as w}from"./chunk-ABJPFKHE.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
|
|
3
|
+
Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-I5BMT734.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
|
|
4
4
|
Array.from(document.querySelectorAll('${t}'))
|
|
5
5
|
.map(el => ({
|
|
6
6
|
tag: el.tagName.toLowerCase(),
|
|
@@ -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.10.
|
|
2
|
-
import{a as l}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.10.9");process.exit(0)}
|
|
2
|
+
import{a as l}from"./chunk-ILPIH4Z6.js";import{a as m}from"./chunk-X6YUGKMM.js";import{i as a}from"./chunk-QWXJRZEH.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
|
|
@@ -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.10.
|
|
2
|
-
import{a as u,c as v,d as p}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.10.9");process.exit(0)}
|
|
2
|
+
import{a as u,c as v,d as p}from"./chunk-HAC7NB6R.js";import{b as l}from"./chunk-VHCHBMZC.js";import{a}from"./chunk-PYQZ4OA3.js";var P=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function x(e={}){if(e.providerManager){let d=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),f=new a(e.providerManager,d);return await f.initialize(),{router:f,resolvedConfig:d,enabledProviders:y(d)}}if(!p({projectRoot:e.projectRoot,env:e.env}))return null;let r=v({projectRoot:e.projectRoot,override:e.override,env:e.env}),o=g(r,e.env??process.env);if(o.length===0)return null;let{primary:n,fallbacks:t}=R(r,o),i={primary:n,fallbacks:t,providers:m(r,o),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},c=new l(i),s=new a(c,r);return await s.initialize(),{router:s,resolvedConfig:r,enabledProviders:o}}function g(e,r=process.env){let o=u(r),n=[],t=i=>{n.includes(i)||!e.providers?.[i]?.enabled||o.has(i)&&n.push(i)};t(e.defaultProvider);for(let i of e.fallbackChain?.entries??[])t(i.provider);for(let i of P)t(i);return n}function y(e){let r=new Set([e.defaultProvider]);for(let o of e.fallbackChain?.entries??[])r.add(o.provider);return Array.from(r)}function R(e,r){if(r.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let o=r.includes(e.defaultProvider)?e.defaultProvider:r[0],n=r.filter(t=>t!==o);return{primary:o,fallbacks:n}}function m(e,r){let o={};for(let n of r){let t=e.providers?.[n];t&&(o[n]=t)}return o}export{x as a,g as b,R as c};
|
|
@@ -1,5 +1,5 @@
|
|
|
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.10.
|
|
2
|
-
import{a as U,b as G}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.10.9");process.exit(0)}
|
|
2
|
+
import{a as U,b as G}from"./chunk-RHOBDQXA.js";import{h as N}from"./chunk-QAP5S7YC.js";import{a as W}from"./chunk-7C5HI4ZA.js";import{e as F}from"./chunk-RRSJ7BMF.js";import{b as v,c as x}from"./chunk-X7677BX3.js";import{a as re}from"./chunk-OPKEQYAC.js";import{c as O}from"./chunk-VHYNRISI.js";import{b as k,d as q}from"./chunk-246Z3PH6.js";import{b,c as E}from"./chunk-X6YUGKMM.js";import{a as y,c as I}from"./chunk-5U5SEO7C.js";import{i as z}from"./chunk-QWXJRZEH.js";import{S as ae,b as _}from"./chunk-KRAWWBX5.js";import{randomUUID as Y}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let o=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(o?.[1])return o[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),o=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&o.push("--result",i),n!==void 0&&o.push("--quality",String(n)),a("npx",o,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-WJEZ5YAK.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(s=>s.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
|
|
3
3
|
INSERT OR REPLACE INTO qe_trajectories
|
|
4
4
|
(id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -9,4 +9,4 @@ Steps:
|
|
|
9
9
|
${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
|
|
10
10
|
`)}
|
|
11
11
|
|
|
12
|
-
Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-CP6EXKBT.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-YHLBWQQ3.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-YHLBWQQ3.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-LKQNQYRY.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-LKQNQYRY.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-IF2RG2ON.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-JJ3FHZGD.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-67UWLHSK.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60*1e3})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
|
|
12
|
+
Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-ITLDYHCX.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-BNJ4VSZX.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-BNJ4VSZX.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-SWH6R7MA.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-SWH6R7MA.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-B2UX4NZY.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-JYZSSQJC.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-6CGRPRGR.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60*1e3})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
|