agentic-qe 3.12.3 → 3.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/helpers/.helpers-version +1 -1
- package/.claude/helpers/auto-memory-hook.mjs +430 -430
- package/.claude/helpers/helpers.manifest.json +6 -5
- package/.claude/helpers/hook-handler.cjs +565 -311
- package/.claude/helpers/intelligence.cjs +1058 -1058
- package/.claude/helpers/statusline.cjs +995 -682
- package/.claude/skills/qe-court/SKILL.md +186 -0
- package/.claude/skills/qe-court/config.json +27 -0
- package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +38 -0
- package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.test.ts +21 -0
- package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.ts +25 -0
- package/.claude/skills/qe-court/evals/qe-court.yaml +70 -0
- package/.claude/skills/qe-court/schemas/output.json +92 -0
- package/.claude/skills/qe-court/scripts/validate-config.json +30 -0
- package/.claude/skills/skills-manifest.json +9 -8
- package/CHANGELOG.md +65 -0
- package/README.md +3 -3
- package/assets/skills/qe-court/SKILL.md +186 -0
- package/assets/skills/qe-court/config.json +27 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +38 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.test.ts +21 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.ts +25 -0
- package/assets/skills/qe-court/evals/qe-court.yaml +70 -0
- package/assets/skills/qe-court/schemas/output.json +92 -0
- package/assets/skills/qe-court/scripts/validate-config.json +30 -0
- package/assets/skills/skills-manifest.json +9 -8
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-CWIMFWAI.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-XFAQATTH.js → agent-booster-wasm-ACX2DK7Y.js} +2 -2
- package/dist/cli/chunks/{agent-handler-2ZV4CA3U.js → agent-handler-B45WP4ZJ.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-6WGP7F5T.js → agent-memory-branch-QQLZDE56.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-OTXT2DLN.js +2 -0
- package/dist/cli/chunks/{arena-FWX7XZAE.js → arena-G3IKZAG5.js} +4 -4
- package/dist/cli/chunks/{arena-KJUNQK4N.js → arena-SDB7723R.js} +2 -2
- package/dist/cli/chunks/{audit-YFUDEOKN.js → audit-GY46XUZA.js} +3 -3
- package/dist/cli/chunks/base-O3SPSWBA.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-SKTT5KIH.js → better-sqlite3-DUZ6FFAH.js} +2 -2
- package/dist/cli/chunks/{brain-handler-ZCK4WTPK.js → brain-handler-347CYMPN.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-HTVINRYG.js → branch-enumerator-Z3ULBFSM.js} +2 -2
- package/dist/cli/chunks/{browser-WUL2B77M.js → browser-OYEIHD7F.js} +2 -2
- package/dist/cli/chunks/browser-workflow-MXS3ZKY2.js +2 -0
- package/dist/cli/chunks/{chunk-OBL6W4Z5.js → chunk-2DIT5AUU.js} +2 -2
- package/dist/cli/chunks/{chunk-IWQHQLT6.js → chunk-2NRZYQSF.js} +2 -2
- package/dist/cli/chunks/chunk-2VQVEQS4.js +153 -0
- package/dist/cli/chunks/{chunk-E2U3LTGM.js → chunk-32ZGV4Q4.js} +1 -1
- package/dist/cli/chunks/{chunk-VUCVSKJC.js → chunk-34PEINFS.js} +2 -2
- package/dist/cli/chunks/{chunk-XUUVAAHV.js → chunk-3GSYD5SL.js} +2 -2
- package/dist/cli/chunks/{chunk-MOX25RZQ.js → chunk-3JVUWKCO.js} +2 -2
- package/dist/cli/chunks/{chunk-RLBNAB6Y.js → chunk-3K4SF57Q.js} +1 -1
- package/dist/cli/chunks/{chunk-MSDIIRLM.js → chunk-3NOCK6ED.js} +2 -2
- package/dist/cli/chunks/{chunk-3YC4YUGB.js → chunk-3UHEZ5HZ.js} +2 -2
- package/dist/cli/chunks/{chunk-J2RJOJ5Q.js → chunk-4BDLD7V2.js} +1 -1
- package/dist/cli/chunks/{chunk-ZGKQCUPB.js → chunk-4BESADKE.js} +2 -2
- package/dist/cli/chunks/{chunk-PDX7IYTJ.js → chunk-54MFKCLT.js} +2 -2
- package/dist/cli/chunks/{chunk-TP3UAWMB.js → chunk-56WZFXTQ.js} +2 -2
- package/dist/cli/chunks/{chunk-WFPGIP4N.js → chunk-5EIOQCGN.js} +2 -2
- package/dist/cli/chunks/{chunk-32L7DKNQ.js → chunk-5FLTZ3KT.js} +2 -2
- package/dist/cli/chunks/{chunk-Y5L37K7X.js → chunk-5ICQL42E.js} +2 -2
- package/dist/cli/chunks/{chunk-Y625LP6K.js → chunk-5KAT6WBQ.js} +2 -2
- package/dist/cli/chunks/{chunk-UIHZ34SJ.js → chunk-6AOBLBR4.js} +2 -2
- package/dist/cli/chunks/{chunk-7WF3TW3G.js → chunk-6DTOGSDV.js} +4 -4
- package/dist/cli/chunks/{chunk-NAMJGRGC.js → chunk-6SXKCIN5.js} +2 -2
- package/dist/cli/chunks/{chunk-FTM562PF.js → chunk-7DMXCCSD.js} +1 -1
- package/dist/cli/chunks/{chunk-KE3RK35K.js → chunk-7UNY32PU.js} +1 -1
- package/dist/cli/chunks/{chunk-BSNNTOHY.js → chunk-7YXT6BXN.js} +3 -3
- package/dist/cli/chunks/{chunk-DZ775UGW.js → chunk-A4QLGPYO.js} +2 -2
- package/dist/cli/chunks/{chunk-SFS3UHNF.js → chunk-A7GLWWSE.js} +1 -1
- package/dist/cli/chunks/{chunk-WKE6WL5C.js → chunk-ANIDFJCT.js} +3 -3
- package/dist/cli/chunks/{chunk-XDHGCBTS.js → chunk-ANYYTWOQ.js} +2 -2
- package/dist/cli/chunks/{chunk-NLDLUHOF.js → chunk-AO7AHX6K.js} +2 -2
- package/dist/cli/chunks/{chunk-Z3SXMYVI.js → chunk-BCKTBGDM.js} +3 -3
- package/dist/cli/chunks/{chunk-UGW23T6S.js → chunk-BGYLNCL6.js} +2 -2
- package/dist/cli/chunks/{chunk-KVHCWH4H.js → chunk-BOVH6WSM.js} +2 -2
- package/dist/cli/chunks/{chunk-L2X3BWMN.js → chunk-BUGWPTMF.js} +2 -2
- package/dist/cli/chunks/{chunk-DTZFZ5M7.js → chunk-CFVEDUTW.js} +2 -2
- package/dist/cli/chunks/{chunk-CL6SNCFF.js → chunk-CPH5JP4L.js} +1 -1
- package/dist/cli/chunks/{chunk-AIWRYWK2.js → chunk-CQFT7H3F.js} +2 -2
- package/dist/cli/chunks/{chunk-BQ2K4BPD.js → chunk-CWUBOLKY.js} +2 -2
- package/dist/cli/chunks/{chunk-2LNDU7AW.js → chunk-CYL2FV23.js} +2 -2
- package/dist/cli/chunks/{chunk-YEC55GO5.js → chunk-D3MPV5G7.js} +2 -2
- package/dist/cli/chunks/{chunk-DMD6WVJ2.js → chunk-DRIJYTSK.js} +2 -2
- package/dist/cli/chunks/{chunk-PXCJDB7J.js → chunk-DYUC7WFA.js} +1 -1
- package/dist/cli/chunks/{chunk-EOUJ6X5H.js → chunk-E3B5XTXJ.js} +1 -1
- package/dist/cli/chunks/{chunk-PSDH7CIL.js → chunk-EECM5XKY.js} +1 -1
- package/dist/cli/chunks/{chunk-E53UR2EW.js → chunk-EFRESRLB.js} +3 -3
- package/dist/cli/chunks/{chunk-SGMJ277D.js → chunk-ES7WCYOU.js} +1 -1
- package/dist/cli/chunks/{chunk-DDYP6FBC.js → chunk-FAQLI3P5.js} +2 -2
- package/dist/cli/chunks/{chunk-CXMOIE7D.js → chunk-FBBZHATF.js} +2 -2
- package/dist/cli/chunks/{chunk-KKOFH26C.js → chunk-FL3BM54K.js} +1 -1
- package/dist/cli/chunks/{chunk-MB7TZQW3.js → chunk-FQLWQWRU.js} +3 -3
- package/dist/cli/chunks/{chunk-GMFFMJD6.js → chunk-FQY3UTGA.js} +2 -2
- package/dist/cli/chunks/{chunk-SPI4LUJ6.js → chunk-FUU32QY5.js} +2 -2
- package/dist/cli/chunks/{chunk-RSZOCQOL.js → chunk-G4GTE3RJ.js} +2 -2
- package/dist/cli/chunks/{chunk-NOSQI2OW.js → chunk-G5DFYX3J.js} +3 -3
- package/dist/cli/chunks/{chunk-OPG2HV2W.js → chunk-G7FMYFTN.js} +1 -1
- package/dist/cli/chunks/{chunk-N4ML23ZG.js → chunk-GFBLWFRV.js} +1 -1
- package/dist/cli/chunks/{chunk-LNIHLNW4.js → chunk-GJMZR7WU.js} +3 -3
- package/dist/cli/chunks/{chunk-PTPN6HQ7.js → chunk-GTUFX7AR.js} +2 -2
- package/dist/cli/chunks/{chunk-67BCEHU5.js → chunk-GUEZQOHL.js} +1 -1
- package/dist/cli/chunks/{chunk-RE42RJYR.js → chunk-HL2QMM4M.js} +2 -2
- package/dist/cli/chunks/{chunk-QILF6BZH.js → chunk-HOKON5EL.js} +2 -2
- package/dist/cli/chunks/{chunk-YOG5KQZF.js → chunk-HTPM3URI.js} +2 -2
- package/dist/cli/chunks/chunk-HVB2L52I.js +2 -0
- package/dist/cli/chunks/{chunk-DHUZHT5D.js → chunk-IHQTXJAQ.js} +1 -1
- package/dist/cli/chunks/{chunk-SV7J5FDW.js → chunk-IPHLXAMX.js} +2 -2
- package/dist/cli/chunks/{chunk-Y6XNISHP.js → chunk-IYDYJ33J.js} +2 -2
- package/dist/cli/chunks/{chunk-CYSBM52D.js → chunk-IZRLIWFN.js} +2 -2
- package/dist/cli/chunks/{chunk-MS6VOSPY.js → chunk-J3L52EA4.js} +5 -5
- package/dist/cli/chunks/{chunk-WQASUQ5P.js → chunk-JGM6XCCP.js} +1 -1
- package/dist/cli/chunks/chunk-JPIBPKBP.js +54 -0
- package/dist/cli/chunks/{chunk-TXLPOXAN.js → chunk-K5N6SLHO.js} +1 -1
- package/dist/cli/chunks/{chunk-R6WMGSEK.js → chunk-KSYLRM4Q.js} +2 -2
- package/dist/cli/chunks/{chunk-2CPJCXV6.js → chunk-KUA4HHU6.js} +2 -2
- package/dist/cli/chunks/{chunk-WUE53ZPH.js → chunk-KVL63BSU.js} +1 -1
- package/dist/cli/chunks/{chunk-6SUSRXXF.js → chunk-KZTBNDNE.js} +1 -1
- package/dist/cli/chunks/{chunk-M7W6VJ65.js → chunk-L2SFGFE6.js} +1 -1
- package/dist/cli/chunks/{chunk-XZGOXLZH.js → chunk-L4LLA5U7.js} +1 -1
- package/dist/cli/chunks/{chunk-AZ24ONMX.js → chunk-L4S722JD.js} +1 -1
- package/dist/cli/chunks/{chunk-HJ4U64BL.js → chunk-LBE2P6UC.js} +2 -2
- package/dist/cli/chunks/{chunk-KA4EAMMQ.js → chunk-LOXVVMS4.js} +3 -3
- package/dist/cli/chunks/{chunk-UGXHMQ6P.js → chunk-LWYLW7RX.js} +2 -2
- package/dist/cli/chunks/{chunk-HJ2LG5IH.js → chunk-LXPB7H2P.js} +1 -1
- package/dist/cli/chunks/{chunk-WBZNLFTV.js → chunk-MBCGI3M2.js} +3 -3
- package/dist/cli/chunks/{chunk-7XUM4LBC.js → chunk-MVI2QMRW.js} +1 -1
- package/dist/cli/chunks/{chunk-2OX74DOO.js → chunk-N5MMBA35.js} +1 -1
- package/dist/cli/chunks/{chunk-VSD6JE2H.js → chunk-N7VOOI3U.js} +2 -2
- package/dist/cli/chunks/{chunk-ROFCS47F.js → chunk-NETN3OUG.js} +1 -1
- package/dist/cli/chunks/chunk-NQNKKVNO.js +29 -0
- package/dist/cli/chunks/{chunk-NJDLJ3KD.js → chunk-NUQBJGGF.js} +2 -2
- package/dist/cli/chunks/chunk-OETDMOOE.js +2 -0
- package/dist/cli/chunks/{chunk-4EHW4TNA.js → chunk-OXXMVQDF.js} +2 -2
- package/dist/cli/chunks/{chunk-6HQDPDN5.js → chunk-OZR25R7W.js} +2 -2
- package/dist/cli/chunks/{chunk-UZ7FXVH5.js → chunk-PERJO2DY.js} +1 -1
- package/dist/cli/chunks/{chunk-XQ5JT7KM.js → chunk-PP2RYSHT.js} +3 -3
- package/dist/cli/chunks/{chunk-DCYBV6HV.js → chunk-Q7PBGNUD.js} +1 -1
- package/dist/cli/chunks/{chunk-LCM7TY76.js → chunk-QCEW4ZDW.js} +2 -2
- package/dist/cli/chunks/{chunk-NKTLKMUB.js → chunk-QI4CGJNK.js} +1 -1
- package/dist/cli/chunks/{chunk-NT66CT73.js → chunk-QQB55ZJJ.js} +2 -2
- package/dist/cli/chunks/{chunk-KRS4KGX5.js → chunk-QTU3CVOB.js} +2 -2
- package/dist/cli/chunks/{chunk-DW7OI5IF.js → chunk-QWYISZTN.js} +2 -2
- package/dist/cli/chunks/{chunk-KNWBRMLL.js → chunk-R3GEXYO4.js} +2 -2
- package/dist/cli/chunks/{chunk-YUDGQZJN.js → chunk-RDU4WTV2.js} +2 -2
- package/dist/cli/chunks/{chunk-VFYMWDSJ.js → chunk-RJZRWVL4.js} +1 -1
- package/dist/cli/chunks/{chunk-D4GMAUTP.js → chunk-RLCWR7TS.js} +10 -10
- package/dist/cli/chunks/{chunk-YDYKFSD2.js → chunk-RSFIOR2I.js} +10 -10
- package/dist/cli/chunks/{chunk-EHO52NKU.js → chunk-RVJPWRV6.js} +2 -2
- package/dist/cli/chunks/{chunk-KGHSKDC7.js → chunk-RVRBTOWX.js} +2 -2
- package/dist/cli/chunks/{chunk-2YDZXFO2.js → chunk-SHCTEXNH.js} +2 -2
- package/dist/cli/chunks/chunk-SNTUKW4Q.js +2 -0
- package/dist/cli/chunks/{chunk-MOXKKY5Q.js → chunk-SRQ3CPJE.js} +4 -4
- package/dist/cli/chunks/{chunk-GS6G7AVS.js → chunk-THBTN7XB.js} +2 -2
- package/dist/cli/chunks/{chunk-LHAUFY4Y.js → chunk-TNRIGQ6U.js} +2 -2
- package/dist/cli/chunks/{chunk-UAPUA6OY.js → chunk-TVMFH5N2.js} +2 -2
- package/dist/cli/chunks/{chunk-HGJQSTQD.js → chunk-TZ73SXQ5.js} +1 -1
- package/dist/cli/chunks/{chunk-CHFTHSMM.js → chunk-TZPKTRJB.js} +2 -2
- package/dist/cli/chunks/{chunk-GV2BS5NC.js → chunk-U2SW6KK5.js} +2 -2
- package/dist/cli/chunks/{chunk-BDGKB2PT.js → chunk-UIPPJKON.js} +2 -2
- package/dist/cli/chunks/{chunk-FXOOOJQD.js → chunk-UMG5URNV.js} +1 -1
- package/dist/cli/chunks/{chunk-7Q74K3HZ.js → chunk-UNIBND6A.js} +1 -1
- package/dist/cli/chunks/{chunk-LGYEOYQJ.js → chunk-USMDIIHY.js} +2 -2
- package/dist/cli/chunks/{chunk-2HCMRGMO.js → chunk-VC6EXDGY.js} +2 -2
- package/dist/cli/chunks/{chunk-5FAWIIWF.js → chunk-VHYMSZNF.js} +2 -2
- package/dist/cli/chunks/{chunk-ZTKCGEB6.js → chunk-VLBV2VL3.js} +1 -1
- package/dist/cli/chunks/{chunk-6E47R27C.js → chunk-VLNPJAVH.js} +1 -1
- package/dist/cli/chunks/{chunk-EH7TSJPS.js → chunk-VSNRPMAZ.js} +2 -2
- package/dist/cli/chunks/{chunk-FJACKKRL.js → chunk-W5YEIHIO.js} +2 -2
- package/dist/cli/chunks/{chunk-4HP7N6SP.js → chunk-WRYT4HTZ.js} +2 -2
- package/dist/cli/chunks/{chunk-ZFLE4D4X.js → chunk-XFCWYQHW.js} +2 -2
- package/dist/cli/chunks/{chunk-72QQDR3Y.js → chunk-XKFE3FLI.js} +2 -2
- package/dist/cli/chunks/{chunk-KXKACV3E.js → chunk-YFGAHNCG.js} +2 -2
- package/dist/cli/chunks/{chunk-S47YGWXK.js → chunk-YPTGE5NJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PEHEANAM.js → chunk-YRQLVGCI.js} +2 -2
- package/dist/cli/chunks/{chunk-L6GZGEFQ.js → chunk-Z6QCOZ2H.js} +2 -2
- package/dist/cli/chunks/{chunk-GGTCD4MA.js → chunk-ZCFZ4USU.js} +1 -1
- package/dist/cli/chunks/{chunk-MZ7SIO6R.js → chunk-ZEIG5IQ4.js} +2 -2
- package/dist/cli/chunks/{chunk-XBOCRCC6.js → chunk-ZJG6N2OK.js} +1 -1
- package/dist/cli/chunks/{chunk-M32DTUZM.js → chunk-ZJIX5FGQ.js} +3 -3
- package/dist/cli/chunks/{chunk-ADQFQBFJ.js → chunk-ZLXBNNNT.js} +2 -2
- package/dist/cli/chunks/{chunk-BEPP57C2.js → chunk-ZOXWASCC.js} +2 -2
- package/dist/cli/chunks/{ci-MMLUV6L6.js → ci-74ZUCO5V.js} +2 -2
- package/dist/cli/chunks/{ci-output-25GS6RXR.js → ci-output-HD6IZNJA.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-4OWAN6R6.js → circuit-breaker-USZVMA42.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-LR3SRBX6.js → claude-flow-setup-S4XKNCD5.js} +2 -2
- package/dist/cli/chunks/client-33PGO5FA.js +2 -0
- package/dist/cli/chunks/{cline-installer-YSZWRZUI.js → cline-installer-6EW4CHAR.js} +2 -2
- package/dist/cli/chunks/{code-UUWUIXI7.js → code-TOLWD2XL.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-2LSPQORU.js → code-index-extractor-UA4QQ7B3.js} +2 -2
- package/dist/cli/chunks/{codex-installer-E5BVXZVA.js → codex-installer-C2CUP4FW.js} +2 -2
- package/dist/cli/chunks/{completions-YKXBKZSO.js → completions-KVUMQQ4K.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-HNT2QRWB.js → complexity-analyzer-DFH6LMK2.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-AW5VCB66.js → continuedev-installer-LYDQSAU7.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-B6SVZXQT.js → copilot-installer-7USXLZHZ.js} +2 -2
- package/dist/cli/chunks/core-handlers-CSNZIM3A.js +2 -0
- package/dist/cli/chunks/{cost-tracker-POZMBN2V.js → cost-tracker-JBDIUMKZ.js} +2 -2
- package/dist/cli/chunks/{coverage-V5BGPN5Q.js → coverage-RGO3K357.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-DRIBR5L3.js +2 -0
- package/dist/cli/chunks/{cursor-installer-EYBI4QVK.js → cursor-installer-YEZGD37F.js} +2 -2
- package/dist/cli/chunks/{daemon-CF6ENQB2.js → daemon-FVETQ3LL.js} +3 -3
- package/dist/cli/chunks/{daemon-HKARXY2W.js → daemon-LPEXHNYG.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-XIL5IAP7.js → dag-attention-scheduler-UKYE2FII.js} +2 -2
- package/dist/cli/chunks/{detect-RRX2U2KK.js → detect-WBG5P7ER.js} +2 -2
- package/dist/cli/chunks/{dist-node-DOANNRCS.js → dist-node-YW6YRBCU.js} +2 -2
- package/dist/cli/chunks/{domain-handler-QMTJV5OR.js → domain-handler-HH7J4A32.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-FSNH75XW.js → domain-transfer-V34GXD5I.js} +2 -2
- package/dist/cli/chunks/dream-WUNO723O.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-NI7PGONV.js → embed-and-insert-pattern-WYLRS3CL.js} +2 -2
- package/dist/cli/chunks/{eval-6ZAF2RY3.js → eval-EIMVXY5J.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-JMXR7N5G.js → experience-capture-middleware-QMZHRUKM.js} +3 -3
- package/dist/cli/chunks/{fast-paths-YB7XZZ76.js → fast-paths-NHLW6XS6.js} +2 -2
- package/dist/cli/chunks/{feature-flags-KJSP7KR6.js → feature-flags-N3UHMSZ3.js} +2 -2
- package/dist/cli/chunks/{feature-flags-2RC4GFC4.js → feature-flags-NE3MBL3P.js} +2 -2
- package/dist/cli/chunks/{file-discovery-SUPBXFYI.js → file-discovery-SI44X4YS.js} +2 -2
- package/dist/cli/chunks/{fleet-KSXFOLFW.js → fleet-MMYUXRRM.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-DFZ5KPPK.js → gnn-wrapper-RLYXYU2Q.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-G3EADK2H.js → heartbeat-handler-6EDRUYLV.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-VAFQDJLL.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-TIRPA7XE.js +2 -0
- package/dist/cli/chunks/hnsw-index-SSQBRQCQ.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-MA676GER.js → hnsw-legacy-bridge-RVM7EAIH.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-FE55OGYB.js → hnswlib-node-RJPBJU2Q.js} +2 -2
- package/dist/cli/chunks/{hooks-HTCPMZNZ.js → hooks-ZF4VKHEO.js} +10 -10
- package/dist/cli/chunks/hybrid-router-AKBWZOQ3.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-QPB3IH4A.js → hypergraph-engine-YWS66PGO.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-GBFSVD7N.js → hypergraph-handler-OQHVRPWB.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-46FQIZ6Y.js +2 -0
- package/dist/cli/chunks/{init-handler-XYBTBCPD.js → init-handler-YW74YF2V.js} +6 -6
- package/dist/cli/chunks/init-wizard-U3NHGYSS.js +2 -0
- package/dist/cli/chunks/kernel-ZDXHT6QF.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-LY6JOBFY.js → kilocode-installer-APWB2GMA.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-JF6NXTJL.js → kiro-installer-DICKFVNC.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-6XTW6WO6.js +2 -0
- package/dist/cli/chunks/{learning-BIISN67N.js → learning-MXHNYW5D.js} +3 -3
- package/dist/cli/chunks/{llm-router-YZUNVZQE.js → llm-router-LTFIX7NY.js} +5 -5
- package/dist/cli/chunks/llm-router-service-3F4E64SY.js +2 -0
- package/dist/cli/chunks/{load-MTWNBNLL.js → load-JUMIQ4LZ.js} +2 -2
- package/dist/cli/chunks/load-test-SWZNGEIY.js +2 -0
- package/dist/cli/chunks/{mcp-37PYMNHQ.js → mcp-WHIARJGO.js} +2 -2
- package/dist/cli/chunks/{memory-IXUUDCI3.js → memory-KAHS6Z5A.js} +5 -5
- package/dist/cli/chunks/memory-backend-PR74ZPBA.js +2 -0
- package/dist/cli/chunks/{memory-handlers-RM2VOFJX.js → memory-handlers-DG3RRXB6.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-RKKS5XYG.js → multi-model-executor-E3Y2RHMX.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-3VXI5MTR.js → opencode-installer-3RKGNGGE.js} +2 -2
- package/dist/cli/chunks/{orchestrator-UO3ZOGFZ.js → orchestrator-TXITUKWD.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-EPE36BVT.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-YJKRL2GI.js → pattern-usage-recorder-EE2BUFZT.js} +2 -2
- package/dist/cli/chunks/{pipeline-GJQJKXWX.js → pipeline-AXTT6KZB.js} +2 -2
- package/dist/cli/chunks/{platform-RHVCZK6C.js → platform-TICPVKE2.js} +2 -2
- package/dist/cli/chunks/{plugin-ZKAIW7O6.js → plugin-VQKNV3EM.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-4X3DSKQV.js → prime-radiant-advanced-wasm-6GY5YY7D.js} +2 -2
- package/dist/cli/chunks/protocol-executor-IELENNST.js +2 -0
- package/dist/cli/chunks/{protocol-handler-KKYQZMB2.js → protocol-handler-YFWDR7UZ.js} +2 -2
- package/dist/cli/chunks/{prove-OD6RPKWX.js → prove-FUMRCXAA.js} +2 -2
- package/dist/cli/chunks/provider-manager-3R3KOBHG.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-S2R2PCBS.js +2 -0
- package/dist/cli/chunks/{quality-ZRWBXCKO.js → quality-2APISBW5.js} +2 -2
- package/dist/cli/chunks/{quality-gate-Y6BWQV7J.js → quality-gate-MCC3E5TM.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-2E23NEV4.js +2 -0
- package/dist/cli/chunks/{real-embeddings-YYEUO4P2.js → real-embeddings-CC5TNOTI.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-JBCPS3FK.js → roocode-installer-YAHTEVPI.js} +2 -2
- package/dist/cli/chunks/router-3FVLWO6S.js +2 -0
- package/dist/cli/chunks/routing-feedback-ZQLRNNR7.js +2 -0
- package/dist/cli/chunks/{routing-handler-KTPJOSBJ.js → routing-handler-6NQBW4TQ.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-SCZZVRE7.js → ruvector-commands-ZHXLHUPG.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-IP7GELQJ.js → rvf-dual-writer-5KF2DGCW.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-WLFTDARU.js → rvf-migration-adapter-BBU57BGF.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-MGFDQ5WD.js → rvf-migration-coordinator-VN4VRZA4.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-YFGLQNEB.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-OTOAGT5W.js → rvf-store-integrity-XCY2XQZA.js} +2 -2
- package/dist/cli/chunks/safe-db-4SBLBTW7.js +2 -0
- package/dist/cli/chunks/schedule-5Y3BGVAA.js +2 -0
- package/dist/cli/chunks/scheduler-DOID3QF3.js +2 -0
- package/dist/cli/chunks/{security-B2CLZKRB.js → security-PYP4H3KN.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-2PMFAQMN.js → shared-rvf-adapter-3CJHRNX6.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-B6P732AV.js → shared-rvf-dual-writer-MKSLKWDI.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-M4JEQO57.js +2 -0
- package/dist/cli/chunks/{status-handler-M6SN2W2D.js → status-handler-VYIZ3VJF.js} +2 -2
- package/dist/cli/chunks/{structural-health-YCCTGI3K.js → structural-health-MVV4OWXP.js} +2 -2
- package/dist/cli/chunks/{sync-KSRF77ID.js → sync-G47OYIQ3.js} +2 -2
- package/dist/cli/chunks/sync-VNX6L3TI.js +2 -0
- package/dist/cli/chunks/{task-handler-MIKRB2SL.js → task-handler-GOWF2GEH.js} +2 -2
- package/dist/cli/chunks/{task-handlers-YXKRUBQ4.js → task-handlers-J2WC6J37.js} +3 -3
- package/dist/cli/chunks/{test-MLOLQCB7.js → test-DMCJ3BXS.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-3KXESUZS.js → test-scheduling-TRFHHKFM.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-6V2PMDBJ.js → token-bootstrap-KEQ7AHFF.js} +2 -2
- package/dist/cli/chunks/{token-usage-DP6THJ3I.js → token-usage-B54FOFOF.js} +2 -2
- package/dist/cli/chunks/transformers-IACZG7IV.js +2 -0
- package/dist/cli/chunks/{tree-sitter-wasm-parser-COK2XERS.js → tree-sitter-wasm-parser-N7H4X37E.js} +2 -2
- package/dist/cli/chunks/{types-PYHUCVOZ.js → types-B3SHT4OD.js} +2 -2
- package/dist/cli/chunks/unified-memory-WNYWTGVX.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-YPAV7U4E.js +2 -0
- package/dist/cli/chunks/unified-persistence-TJ252S7L.js +2 -0
- package/dist/cli/chunks/{upgrade-ONP2HNGL.js → upgrade-A2PQ5EWK.js} +2 -2
- package/dist/cli/chunks/{validate-NWSICDAY.js → validate-UXV7UQUT.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-KXS5P3U7.js → validate-swarm-MMBU4FPP.js} +2 -2
- package/dist/cli/chunks/{vibium-TZSGZRCQ.js → vibium-R4GUVADA.js} +2 -2
- package/dist/cli/chunks/visual-security-VKYXEGJB.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-V2FADNRA.js → web-tree-sitter-MP6E6CJB.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-GQM7KWDC.js → windsurf-installer-Z6BWMUUO.js} +2 -2
- package/dist/cli/chunks/{witness-chain-GTITDIA2.js → witness-chain-EFLTABBA.js} +2 -2
- package/dist/cli/chunks/witness-chain-WVXRXKQP.js +2 -0
- package/dist/cli/chunks/{witness-key-manager-AHRM2M52.js → witness-key-manager-PN36TV43.js} +2 -2
- package/dist/cli/chunks/{workflow-XCGHEL3I.js → workflow-A2AX3RJU.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-GOWSPR3G.js +2 -0
- package/dist/cli/chunks/{wrappers-VGO2GO4J.js → wrappers-NA6FHA63.js} +2 -2
- package/dist/cli/commands/llm-router.js +1 -0
- package/dist/init/skills-installer.js +1 -0
- package/dist/integrations/embeddings/base/EmbeddingGenerator.js +13 -1
- package/dist/kernel/unified-memory.js +4 -0
- package/dist/learning/qe-flywheel/corpus-scorer.js +10 -7
- package/dist/learning/qe-flywheel/generation.d.ts +7 -0
- package/dist/learning/qe-flywheel/generation.js +5 -0
- package/dist/learning/qe-flywheel/witness-verify.d.ts +86 -0
- package/dist/learning/qe-flywheel/witness-verify.js +156 -0
- package/dist/mcp/bundle.js +397 -386
- package/dist/shared/db-recovery.d.ts +55 -0
- package/dist/shared/db-recovery.js +184 -0
- package/dist/shared/llm/billing-modes.js +5 -2
- package/dist/shared/llm/cost-tracker.js +1 -0
- package/dist/shared/llm/interfaces.d.ts +14 -1
- package/dist/shared/llm/provider-manager.d.ts +1 -1
- package/dist/shared/llm/provider-manager.js +7 -3
- package/dist/shared/llm/providers/claude-code.js +12 -3
- package/dist/shared/llm/providers/codex.d.ts +58 -0
- package/dist/shared/llm/providers/codex.js +305 -0
- package/dist/shared/llm/providers/index.d.ts +1 -0
- package/dist/shared/llm/providers/index.js +1 -0
- package/dist/shared/llm/router/config-store.js +5 -0
- package/dist/shared/llm/router/hybrid-router.js +2 -2
- package/dist/shared/llm/spend-ledger.d.ts +24 -0
- package/dist/shared/llm/spend-ledger.js +86 -15
- package/dist/shared/llm/translation/message-formatter.js +1 -0
- package/dist/shared/safe-db.d.ts +10 -0
- package/dist/shared/safe-db.js +17 -0
- package/dist/skills/qe-court/referee.d.ts +62 -0
- package/dist/skills/qe-court/referee.js +78 -0
- package/dist/validation/gate-reexecute.d.ts +9 -0
- package/dist/validation/gate-reexecute.js +61 -0
- package/dist/validation/paired-bootstrap.d.ts +36 -0
- package/dist/validation/paired-bootstrap.js +58 -0
- package/package.json +7 -3
- package/dist/cli/chunks/adapter-D657MKZY.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-AFR6OZJK.js +0 -2
- package/dist/cli/chunks/base-K5QRGZWE.js +0 -2
- package/dist/cli/chunks/browser-workflow-ZMMKCGYW.js +0 -2
- package/dist/cli/chunks/chunk-6SQ72FG7.js +0 -2
- package/dist/cli/chunks/chunk-FHHCH7WL.js +0 -2
- package/dist/cli/chunks/chunk-G5OGKVLO.js +0 -2
- package/dist/cli/chunks/chunk-ILRKO6A5.js +0 -43
- package/dist/cli/chunks/chunk-NX522PRH.js +0 -153
- package/dist/cli/chunks/chunk-PPUDKQ4X.js +0 -29
- package/dist/cli/chunks/chunk-ULQCEM7K.js +0 -2
- package/dist/cli/chunks/client-WI7RRUZO.js +0 -2
- package/dist/cli/chunks/core-handlers-T6URR57V.js +0 -2
- package/dist/cli/chunks/cross-domain-router-WHTTKHWM.js +0 -2
- package/dist/cli/chunks/dream-QUL6SURC.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-VZNKE33K.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-LGWLDZLC.js +0 -2
- package/dist/cli/chunks/hnsw-index-66FOOI7U.js +0 -2
- package/dist/cli/chunks/hybrid-router-I5MEVQDF.js +0 -2
- package/dist/cli/chunks/impact-analyzer-K6ANYIY3.js +0 -2
- package/dist/cli/chunks/init-wizard-URHGXJ32.js +0 -2
- package/dist/cli/chunks/kernel-OKI5ZY5P.js +0 -2
- package/dist/cli/chunks/knowledge-graph-VQQSK7T5.js +0 -2
- package/dist/cli/chunks/llm-router-service-TISH33SY.js +0 -2
- package/dist/cli/chunks/load-test-KWKWC4Q7.js +0 -2
- package/dist/cli/chunks/memory-backend-JSQQMXVS.js +0 -2
- package/dist/cli/chunks/pattern-null-store-SXBIUKE5.js +0 -2
- package/dist/cli/chunks/protocol-executor-D3Q5P3WY.js +0 -2
- package/dist/cli/chunks/provider-manager-2EIX7E5Q.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-ITOW2ZHC.js +0 -2
- package/dist/cli/chunks/queen-coordinator-TO5X2EXL.js +0 -2
- package/dist/cli/chunks/router-GZJQEJU3.js +0 -2
- package/dist/cli/chunks/routing-feedback-CRXSKFNS.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-WHADT5HX.js +0 -2
- package/dist/cli/chunks/safe-db-MIZ2OFWC.js +0 -2
- package/dist/cli/chunks/schedule-XFILYTYC.js +0 -2
- package/dist/cli/chunks/scheduler-EIPJ777A.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-PFU3GSRD.js +0 -2
- package/dist/cli/chunks/sync-3SDMVAIU.js +0 -2
- package/dist/cli/chunks/transformers-QFOBOP2Y.js +0 -2
- package/dist/cli/chunks/unified-memory-OUVCMFGK.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-YGQPOHXB.js +0 -2
- package/dist/cli/chunks/unified-persistence-GFRZVDOW.js +0 -2
- package/dist/cli/chunks/visual-security-LVOOYQ64.js +0 -2
- package/dist/cli/chunks/witness-chain-QNFPV4UL.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-MIVBCALG.js +0 -2
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QE-Court referee (ADR-124) — the falsifiable core of the adversarial court,
|
|
3
|
+
* as pure, deterministic functions so the court's invariants are ENFORCED in
|
|
4
|
+
* code (and unit-testable as oracles), not merely described in the skill doc.
|
|
5
|
+
*
|
|
6
|
+
* These back the qe-court acceptance eval (`.claude/skills/qe-court/evals`):
|
|
7
|
+
* - verdict resolution + the overturn mechanic (SHIP must survive escalation)
|
|
8
|
+
* - panel validation (writer≠juror, vendor diversity)
|
|
9
|
+
* - DoE-gated scoring (no un-validated numeric score)
|
|
10
|
+
*
|
|
11
|
+
* No I/O, no LLM calls — the orchestration (spawning prosecutors, calling the
|
|
12
|
+
* two-gate judge) lives in the skill; the RULES live here.
|
|
13
|
+
*/
|
|
14
|
+
/** Map a provider id to its coarse vendor. */
|
|
15
|
+
export function vendorOf(providerId) {
|
|
16
|
+
const p = providerId.toLowerCase();
|
|
17
|
+
if (p.startsWith('claude'))
|
|
18
|
+
return 'claude';
|
|
19
|
+
if (p.startsWith('cognitum'))
|
|
20
|
+
return 'cognitum';
|
|
21
|
+
if (p === 'codex' || p === 'openai' || p.startsWith('gpt') || p.startsWith('o3') || p.startsWith('o4'))
|
|
22
|
+
return 'gpt';
|
|
23
|
+
if (p.startsWith('openrouter'))
|
|
24
|
+
return 'openrouter';
|
|
25
|
+
if (p === 'ollama' || p === 'local')
|
|
26
|
+
return 'local';
|
|
27
|
+
return 'unknown';
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Resolve the verdict from the surviving charges, applying the overturn window.
|
|
31
|
+
*
|
|
32
|
+
* THE OVERTURN MECHANIC: only charges surfaced at depth ≤ `overturnDepth` count.
|
|
33
|
+
* With `overturnDepth = 0` the deeper-review rounds are disabled, so a mutant a
|
|
34
|
+
* shallow pass missed (surfaced at depth ≥ 1) does NOT count and the verdict
|
|
35
|
+
* stays SHIP — which is exactly the false-SHIP the court exists to catch. With
|
|
36
|
+
* `overturnDepth ≥ 1` that same charge counts and flips the verdict. This
|
|
37
|
+
* asymmetry is the whole point: a SHIP must SURVIVE escalation.
|
|
38
|
+
*/
|
|
39
|
+
export function resolveVerdict(charges, overturnDepth) {
|
|
40
|
+
const surviving = charges.filter((c) => c.reproduced && c.depthFound <= overturnDepth);
|
|
41
|
+
if (surviving.some((c) => c.fatal))
|
|
42
|
+
return 'BLOCK';
|
|
43
|
+
if (surviving.length > 0)
|
|
44
|
+
return 'REMAND';
|
|
45
|
+
return 'SHIP';
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Validate a seated panel against the court's anti-collusion invariants.
|
|
49
|
+
* Returns a list of violation codes (empty == valid).
|
|
50
|
+
* - 'writerIsNeverJuror' : the jury shares a vendor with the writer/defense.
|
|
51
|
+
* - 'vendor-diversity' : fewer than `minVendors` distinct vendors seated.
|
|
52
|
+
*/
|
|
53
|
+
export function validatePanel(panel, policy = {}) {
|
|
54
|
+
const minVendors = policy.minVendors ?? 2;
|
|
55
|
+
const violations = [];
|
|
56
|
+
const vendorsSeated = new Set(panel.map((s) => vendorOf(s.provider)));
|
|
57
|
+
if (vendorsSeated.size < minVendors)
|
|
58
|
+
violations.push('vendor-diversity');
|
|
59
|
+
const jury = panel.find((s) => s.role === 'jury');
|
|
60
|
+
const writerLike = panel.filter((s) => s.role === 'writer' || s.role === 'defense');
|
|
61
|
+
if (jury) {
|
|
62
|
+
const juryVendor = vendorOf(jury.provider);
|
|
63
|
+
if (writerLike.some((w) => vendorOf(w.provider) === juryVendor)) {
|
|
64
|
+
violations.push('writerIsNeverJuror');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return violations;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* DoE-gated scoring: emit a numeric score ONLY when the operator asked for one
|
|
71
|
+
* AND the scoring rubric passed the ADR-122 ANOVA screen (it actually
|
|
72
|
+
* discriminates). Otherwise the court reports the verdict class + charges, never
|
|
73
|
+
* a noise "91/100".
|
|
74
|
+
*/
|
|
75
|
+
export function shouldEmitScore(rubricDoePassed, emitScore) {
|
|
76
|
+
return emitScore && rubricDoePassed;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=referee.js.map
|
|
@@ -40,6 +40,15 @@ export interface SealedInputs {
|
|
|
40
40
|
provenanceTier: string;
|
|
41
41
|
/** Whether judge-tier promotion was explicitly budgeted (ADR-121). */
|
|
42
42
|
allowJudgeTier?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* accept/v1+sig only: the candidate's PER-HELD-OUT-TASK scores, matched by
|
|
45
|
+
* index to `baselineHeldOutSamples`. Optional and omitted from the sealed hash
|
|
46
|
+
* when undefined (so `accept/v1` receipts are byte-identical). The paired
|
|
47
|
+
* bootstrap significance gate needs these; `accept/v1` ignores them.
|
|
48
|
+
*/
|
|
49
|
+
candidateHeldOutSamples?: number[];
|
|
50
|
+
/** accept/v1+sig only: the baseline's per-held-out-task scores (paired by index). */
|
|
51
|
+
baselineHeldOutSamples?: number[];
|
|
43
52
|
}
|
|
44
53
|
export interface RuleResult {
|
|
45
54
|
promote: boolean;
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
import { createHash } from 'node:crypto';
|
|
26
26
|
import { meetsNoRegression } from './anchor-set.js';
|
|
27
27
|
import { tierAllowsPromotion } from '../learning/provenance-tier.js';
|
|
28
|
+
import { bootstrapDeltaCILow, pairedDeltas } from './paired-bootstrap.js';
|
|
28
29
|
/** Tag domain-separating the rule fingerprint hash. */
|
|
29
30
|
const RULE_TAG = 'aqe:accept-rule:v1+sig';
|
|
30
31
|
/**
|
|
@@ -45,9 +46,69 @@ const acceptV1 = (s) => {
|
|
|
45
46
|
}
|
|
46
47
|
return { promote: true, reason: 'held-out gain, no anchor regression, oracle-tier evidence' };
|
|
47
48
|
};
|
|
49
|
+
/**
|
|
50
|
+
* accept/v1+sig — accept/v1 PLUS a paired-bootstrap significance gate on the
|
|
51
|
+
* held-out delta (adopted from ruflo's flywheel gate). A NEW frozen version:
|
|
52
|
+
* `accept/v1` is untouched. Promotes only when accept/v1 passes AND the paired
|
|
53
|
+
* per-task held-out gain is significant (one-sided 95% CI lower bound > 0) —
|
|
54
|
+
* closing accept/v1's "promote any positive mean-beat, even within noise" gap.
|
|
55
|
+
*
|
|
56
|
+
* Fail-closed: if the paired sample vectors are absent or mismatched, it does
|
|
57
|
+
* NOT promote (a significance claim it cannot verify is a rejection).
|
|
58
|
+
*/
|
|
59
|
+
/** Minimum paired sample size for a meaningful bootstrap CI. Below this, a "95%
|
|
60
|
+
* CI" is just the raw delta dressed up (n=1 → ciLow == delta), so we fail closed
|
|
61
|
+
* rather than certify noise as significant (qe-court finding). */
|
|
62
|
+
const MIN_SIG_SAMPLES = 8;
|
|
63
|
+
/** Tolerance for mean(samples) vs the sealed scalar — guards forged scalar/vector pairs. */
|
|
64
|
+
const SAMPLE_MEAN_TOL = 1e-6;
|
|
65
|
+
const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
|
|
66
|
+
const acceptV1Sig = (s) => {
|
|
67
|
+
const base = acceptV1(s);
|
|
68
|
+
if (!base.promote)
|
|
69
|
+
return base;
|
|
70
|
+
const cand = s.candidateHeldOutSamples;
|
|
71
|
+
const bl = s.baselineHeldOutSamples;
|
|
72
|
+
if (!cand || !bl || cand.length === 0 || cand.length !== bl.length) {
|
|
73
|
+
return {
|
|
74
|
+
promote: false,
|
|
75
|
+
reason: `significance gate: missing/mismatched paired held-out samples ` +
|
|
76
|
+
`(need equal-length candidate & baseline per-task vectors)`,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
if (cand.length < MIN_SIG_SAMPLES) {
|
|
80
|
+
return {
|
|
81
|
+
promote: false,
|
|
82
|
+
reason: `significance gate: only ${cand.length} paired samples (< ${MIN_SIG_SAMPLES}) — ` +
|
|
83
|
+
`a bootstrap CI is not meaningful; fail closed rather than certify noise`,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
// The sealed scalar means MUST match the sealed sample vectors, or a forged
|
|
87
|
+
// receipt could pair a passing scalar with an unrelated (or noisy) vector to
|
|
88
|
+
// spoof significance. This module's whole job is to defend against forged
|
|
89
|
+
// receipts (ADR-120), so it asserts the two describe the same evaluation.
|
|
90
|
+
if (Math.abs(mean(cand) - s.candidateHeldOut) > SAMPLE_MEAN_TOL ||
|
|
91
|
+
Math.abs(mean(bl) - s.baselineHeldOut) > SAMPLE_MEAN_TOL) {
|
|
92
|
+
return {
|
|
93
|
+
promote: false,
|
|
94
|
+
reason: `significance gate: sealed sample means do not match the sealed held-out ` +
|
|
95
|
+
`scalars — inconsistent/forged evaluation`,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const ciLow = bootstrapDeltaCILow(pairedDeltas(cand, bl));
|
|
99
|
+
if (!(ciLow > 0)) {
|
|
100
|
+
return {
|
|
101
|
+
promote: false,
|
|
102
|
+
reason: `significance gate: paired held-out gain not significant ` +
|
|
103
|
+
`(95% CI lower bound ${ciLow.toFixed(4)} ≤ 0)`,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return { promote: true, reason: `${base.reason}; paired gain significant (CI low ${ciLow.toFixed(4)} > 0)` };
|
|
107
|
+
};
|
|
48
108
|
/** Registry of versioned frozen rules. Add a NEW key to change a rule; never edit in place. */
|
|
49
109
|
export const ACCEPTANCE_RULES = Object.freeze({
|
|
50
110
|
'accept/v1': acceptV1,
|
|
111
|
+
'accept/v1+sig': acceptV1Sig,
|
|
51
112
|
});
|
|
52
113
|
/**
|
|
53
114
|
* Canonical (sorted-key) JSON — same discipline as ADR-116 proof-gate. Keys
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paired-delta bootstrap significance (ADR-118 accept/v1+sig).
|
|
3
|
+
*
|
|
4
|
+
* Adopted from ruflo's flywheel promotion gate (`accept/v1+sig`,
|
|
5
|
+
* `bootstrapDeltaCILow`), reimplemented dependency-free (technique adoption, not
|
|
6
|
+
* an import — AQE does not depend on the ruflo package). ruflo's gate closes a
|
|
7
|
+
* real gap in AQE's `accept/v1`, which promotes a candidate whose held-out MEAN
|
|
8
|
+
* merely beats baseline by any amount — i.e. it can promote a within-noise gain.
|
|
9
|
+
*
|
|
10
|
+
* This computes a one-sided lower confidence bound on the MEAN of the PAIRED
|
|
11
|
+
* per-task deltas (candidate − baseline, matched by task). If that bound is > 0
|
|
12
|
+
* the gain is significant. The pairing is what makes it stronger than an
|
|
13
|
+
* unpaired 2-group ANOVA (for 2 groups ANOVA F = t², and it discards the
|
|
14
|
+
* pairing this exploits).
|
|
15
|
+
*
|
|
16
|
+
* MUST be DETERMINISTIC — the promotion decision is replay-verified (ADR-120):
|
|
17
|
+
* a fixed-seed LCG resampler makes the same deltas always yield the same bound,
|
|
18
|
+
* so an independent re-run reproduces the exact promote/reject decision.
|
|
19
|
+
*/
|
|
20
|
+
export interface BootstrapOptions {
|
|
21
|
+
/** Resample count (default 2000, matching ruflo). */
|
|
22
|
+
iters?: number;
|
|
23
|
+
/** One-sided significance level (default 0.05 → 95% lower bound). */
|
|
24
|
+
alpha?: number;
|
|
25
|
+
/** LCG seed. Fixed by default so the bound is reproducible for replay. */
|
|
26
|
+
seed?: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* One-sided lower confidence bound on the mean of `deltas`. Returns -Infinity
|
|
30
|
+
* for an empty sample (no evidence ⇒ never significant), so callers can gate on
|
|
31
|
+
* `bootstrapDeltaCILow(deltas) > 0` and fail closed.
|
|
32
|
+
*/
|
|
33
|
+
export declare function bootstrapDeltaCILow(deltas: number[], opts?: BootstrapOptions): number;
|
|
34
|
+
/** Convenience: paired deltas from matched candidate/baseline sample vectors. */
|
|
35
|
+
export declare function pairedDeltas(candidate: number[], baseline: number[]): number[];
|
|
36
|
+
//# sourceMappingURL=paired-bootstrap.d.ts.map
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paired-delta bootstrap significance (ADR-118 accept/v1+sig).
|
|
3
|
+
*
|
|
4
|
+
* Adopted from ruflo's flywheel promotion gate (`accept/v1+sig`,
|
|
5
|
+
* `bootstrapDeltaCILow`), reimplemented dependency-free (technique adoption, not
|
|
6
|
+
* an import — AQE does not depend on the ruflo package). ruflo's gate closes a
|
|
7
|
+
* real gap in AQE's `accept/v1`, which promotes a candidate whose held-out MEAN
|
|
8
|
+
* merely beats baseline by any amount — i.e. it can promote a within-noise gain.
|
|
9
|
+
*
|
|
10
|
+
* This computes a one-sided lower confidence bound on the MEAN of the PAIRED
|
|
11
|
+
* per-task deltas (candidate − baseline, matched by task). If that bound is > 0
|
|
12
|
+
* the gain is significant. The pairing is what makes it stronger than an
|
|
13
|
+
* unpaired 2-group ANOVA (for 2 groups ANOVA F = t², and it discards the
|
|
14
|
+
* pairing this exploits).
|
|
15
|
+
*
|
|
16
|
+
* MUST be DETERMINISTIC — the promotion decision is replay-verified (ADR-120):
|
|
17
|
+
* a fixed-seed LCG resampler makes the same deltas always yield the same bound,
|
|
18
|
+
* so an independent re-run reproduces the exact promote/reject decision.
|
|
19
|
+
*/
|
|
20
|
+
/**
|
|
21
|
+
* One-sided lower confidence bound on the mean of `deltas`. Returns -Infinity
|
|
22
|
+
* for an empty sample (no evidence ⇒ never significant), so callers can gate on
|
|
23
|
+
* `bootstrapDeltaCILow(deltas) > 0` and fail closed.
|
|
24
|
+
*/
|
|
25
|
+
export function bootstrapDeltaCILow(deltas, opts) {
|
|
26
|
+
const n = deltas.length;
|
|
27
|
+
if (n === 0)
|
|
28
|
+
return -Infinity;
|
|
29
|
+
const iters = opts?.iters ?? 2000;
|
|
30
|
+
const alpha = opts?.alpha ?? 0.05;
|
|
31
|
+
// Deterministic LCG (Numerical Recipes constants). Seed is fixed by default so
|
|
32
|
+
// the bound is byte-stable across independent replays of the same deltas.
|
|
33
|
+
let state = (opts?.seed ?? 0x9e3779b1) >>> 0;
|
|
34
|
+
const next = () => {
|
|
35
|
+
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
|
|
36
|
+
return state / 0x1_0000_0000;
|
|
37
|
+
};
|
|
38
|
+
const resampleMeans = new Array(iters);
|
|
39
|
+
for (let b = 0; b < iters; b++) {
|
|
40
|
+
let sum = 0;
|
|
41
|
+
for (let i = 0; i < n; i++) {
|
|
42
|
+
sum += deltas[Math.floor(next() * n)];
|
|
43
|
+
}
|
|
44
|
+
resampleMeans[b] = sum / n;
|
|
45
|
+
}
|
|
46
|
+
resampleMeans.sort((a, b) => a - b);
|
|
47
|
+
const idx = Math.min(Math.floor(alpha * iters), iters - 1);
|
|
48
|
+
return resampleMeans[idx];
|
|
49
|
+
}
|
|
50
|
+
/** Convenience: paired deltas from matched candidate/baseline sample vectors. */
|
|
51
|
+
export function pairedDeltas(candidate, baseline) {
|
|
52
|
+
const n = Math.min(candidate.length, baseline.length);
|
|
53
|
+
const out = new Array(n);
|
|
54
|
+
for (let i = 0; i < n; i++)
|
|
55
|
+
out[i] = candidate[i] - baseline[i];
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=paired-bootstrap.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentic-qe",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.13.0",
|
|
4
4
|
"description": "Agentic Quality Engineering V3 - Domain-Driven Design Architecture with 13 Bounded Contexts, O(log n) coverage analysis, ReasoningBank learning, 60 specialized QE agents, mathematical Coherence verification, deep Claude Flow integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -164,7 +164,6 @@
|
|
|
164
164
|
"author": "AQE Development Team",
|
|
165
165
|
"license": "MIT",
|
|
166
166
|
"dependencies": {
|
|
167
|
-
"@huggingface/transformers": "^4.2.0",
|
|
168
167
|
"@ruvector/attention": "0.1.3",
|
|
169
168
|
"@ruvector/gnn": "0.1.25",
|
|
170
169
|
"@ruvector/learning-wasm": "^0.1.29",
|
|
@@ -190,7 +189,8 @@
|
|
|
190
189
|
},
|
|
191
190
|
"peerDependencies": {
|
|
192
191
|
"@claude-flow/browser": "3.0.0-alpha.1",
|
|
193
|
-
"@claude-flow/guidance": "3.0.0-alpha.1"
|
|
192
|
+
"@claude-flow/guidance": "3.0.0-alpha.1",
|
|
193
|
+
"@huggingface/transformers": "^4.2.0"
|
|
194
194
|
},
|
|
195
195
|
"peerDependenciesMeta": {
|
|
196
196
|
"@claude-flow/browser": {
|
|
@@ -198,6 +198,9 @@
|
|
|
198
198
|
},
|
|
199
199
|
"@claude-flow/guidance": {
|
|
200
200
|
"optional": true
|
|
201
|
+
},
|
|
202
|
+
"@huggingface/transformers": {
|
|
203
|
+
"optional": true
|
|
201
204
|
}
|
|
202
205
|
},
|
|
203
206
|
"optionalDependencies": {
|
|
@@ -240,6 +243,7 @@
|
|
|
240
243
|
"devDependencies": {
|
|
241
244
|
"@claude-flow/guidance": "3.0.0-alpha.1",
|
|
242
245
|
"@faker-js/faker": "^10.2.0",
|
|
246
|
+
"@huggingface/transformers": "^4.2.0",
|
|
243
247
|
"@types/better-sqlite3": "^7.6.13",
|
|
244
248
|
"@types/cli-progress": "^3.11.6",
|
|
245
249
|
"@types/node": "^25.8.0",
|
|
@@ -1,2 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
import{a,b,c}from"./chunk-BSNNTOHY.js";import"./chunk-KRS4KGX5.js";import"./chunk-6SUSRXXF.js";import"./chunk-OBL6W4Z5.js";import"./chunk-2LNDU7AW.js";import"./chunk-SGMJ277D.js";export{a as AgentBoosterAdapter,b as createAgentBoosterAdapter,c as createAgentBoosterAdapterSync};
|
|
@@ -1,2 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
import{a,b,c,d,e,f}from"./chunk-LNIHLNW4.js";import"./chunk-32L7DKNQ.js";import"./chunk-WKE6WL5C.js";import"./chunk-MOXKKY5Q.js";import"./chunk-67BCEHU5.js";import"./chunk-MOX25RZQ.js";import"./chunk-GGTCD4MA.js";import"./chunk-6E47R27C.js";import"./chunk-DCYBV6HV.js";import"./chunk-DDYP6FBC.js";import"./chunk-MSDIIRLM.js";import"./chunk-DZ775UGW.js";import"./chunk-SPI4LUJ6.js";import"./chunk-2YDZXFO2.js";import"./chunk-VSD6JE2H.js";import"./chunk-Z3SXMYVI.js";import"./chunk-NOSQI2OW.js";import"./chunk-FJACKKRL.js";import"./chunk-L2X3BWMN.js";import"./chunk-G5OGKVLO.js";import"./chunk-4EHW4TNA.js";import"./chunk-NJDLJ3KD.js";import"./chunk-OBL6W4Z5.js";import"./chunk-HJ2LG5IH.js";import"./chunk-2CPJCXV6.js";import"./chunk-OPG2HV2W.js";import"./chunk-NKTLKMUB.js";import"./chunk-2LNDU7AW.js";import"./chunk-EOUJ6X5H.js";import"./chunk-ULQCEM7K.js";import"./chunk-UAPUA6OY.js";import"./chunk-GS6G7AVS.js";import"./chunk-YUDGQZJN.js";import"./chunk-HJ4U64BL.js";import"./chunk-CYSBM52D.js";import"./chunk-NLDLUHOF.js";import"./chunk-PEHEANAM.js";import"./chunk-XUUVAAHV.js";import"./chunk-SGMJ277D.js";export{b as AQELearningEngine,a as DEFAULT_ENGINE_CONFIG,c as DEFAULT_META_LEARNING_CONFIG,d as MetaLearningEngine,e as createAQELearningEngine,f as createDefaultLearningEngine};
|
|
@@ -1,2 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-AIWRYWK2.js";import"./chunk-BDGKB2PT.js";import"./chunk-NOSQI2OW.js";import"./chunk-FJACKKRL.js";import"./chunk-L2X3BWMN.js";import"./chunk-G5OGKVLO.js";import"./chunk-4EHW4TNA.js";import"./chunk-NJDLJ3KD.js";import"./chunk-OBL6W4Z5.js";import"./chunk-2LNDU7AW.js";import"./chunk-EOUJ6X5H.js";import"./chunk-L6GZGEFQ.js";import"./chunk-ULQCEM7K.js";import"./chunk-UAPUA6OY.js";import"./chunk-GS6G7AVS.js";import"./chunk-YUDGQZJN.js";import"./chunk-HJ4U64BL.js";import"./chunk-CYSBM52D.js";import"./chunk-NLDLUHOF.js";import"./chunk-PEHEANAM.js";import"./chunk-XUUVAAHV.js";import"./chunk-SGMJ277D.js";export{l as MCPToolBase,k as defaultToolLogger,j as getKernel,i as getLLMRouter,e as getMemoryBackend,g as getSharedLLMRouter,c as getSharedMemoryBackend,a as isMemoryOnlyMode,b as registerRvfResetFn,h as resetSharedLLMRouter,d as resetSharedMemoryBackend,f as setSharedLLMRouter};
|
|
@@ -1,2 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
import{a}from"./chunk-UGXHMQ6P.js";import"./chunk-AIWRYWK2.js";import"./chunk-BDGKB2PT.js";import"./chunk-NOSQI2OW.js";import"./chunk-FJACKKRL.js";import"./chunk-L2X3BWMN.js";import"./chunk-G5OGKVLO.js";import"./chunk-4EHW4TNA.js";import"./chunk-NJDLJ3KD.js";import"./chunk-OBL6W4Z5.js";import"./chunk-2LNDU7AW.js";import"./chunk-EOUJ6X5H.js";import"./chunk-L6GZGEFQ.js";import"./chunk-ULQCEM7K.js";import"./chunk-UAPUA6OY.js";import"./chunk-GS6G7AVS.js";import"./chunk-YUDGQZJN.js";import"./chunk-HJ4U64BL.js";import"./chunk-CYSBM52D.js";import"./chunk-NLDLUHOF.js";import"./chunk-PEHEANAM.js";import"./chunk-XUUVAAHV.js";import"./chunk-SGMJ277D.js";export{a as BrowserWorkflowTool};
|
|
@@ -1,2 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
var r={claude:"metered-api","claude-code":"subscription",openai:"metered-api",openrouter:"metered-api",gemini:"metered-api","azure-openai":"metered-api",bedrock:"metered-api",cognitum:"metered-capped",ollama:"local"};function o(e){return e.billingMode??r[e.type]??"metered-api"}function n(e){return r[e]??"metered-api"}function t(e,i){switch(i){case"metered-api":return`\u26A0\uFE0F LLM provider "${e}" bills a pay-per-token API key (not your Claude subscription) and has no server-side spend cap. Set a budget with --max-budget-usd / AQE_MAX_BUDGET_USD, or use AQE_LLM_PROVIDER=claude-code to run on your Claude Code subscription instead.`;case"metered-capped":return`\u2139\uFE0F LLM provider "${e}" bills per-token but enforces a server-side hard spend cap; it will pause at the cap rather than overspend.`;case"subscription":return`\u2139\uFE0F LLM provider "${e}" runs on your Claude Code subscription (shared plan usage). Worst case is hitting your plan's rate limit and pausing \u2014 no per-token API charges.`;case"local":return}}export{o as a,n as b,t as c};
|
|
@@ -1,2 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
import{createRequire as t}from"module";var o=t(import.meta.url),e=o("@huggingface/transformers"),n=e,{RuvectorLayer:i,TensorCompress:a,differentiableSearch:c,hierarchicalForward:s,getCompressionLevel:l,init:p,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:d,HyperbolicAttention:f,LinearAttention:A,MoEAttention:g,SonaEngine:h,pipeline:_}=e||{};export{n as a,i as b,a as c,c as d,s as e,l as f,p as g,m as h,u as i,d as j,f as k,A as l,g as m,h as n,_ as o};
|
|
@@ -1,2 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
import{a as e,b as g,e as r}from"./chunk-4EHW4TNA.js";import{c as o}from"./chunk-SGMJ277D.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
|
|
@@ -1,43 +0,0 @@
|
|
|
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.12.3");process.exit(0)}
|
|
2
|
-
import{b as T}from"./chunk-WFPGIP4N.js";import{a as de,c as pe}from"./chunk-6SQ72FG7.js";import{a as re,b as Ce}from"./chunk-SV7J5FDW.js";import{a}from"./chunk-NAMJGRGC.js";import{d as me}from"./chunk-DHUZHT5D.js";import{b as R,c as ue}from"./chunk-CXMOIE7D.js";import{b as D,d as ce}from"./chunk-OBL6W4Z5.js";import{b as E,c as L}from"./chunk-2LNDU7AW.js";import{b as le,d as Ee}from"./chunk-YUDGQZJN.js";Ee();L();var he={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},se=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...he,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(E(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},K=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...he,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new se(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var ge={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},M=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...ge,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),o=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);o=(o<<5)-o+l,o=o&o}return`${t}:${Math.abs(o).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let s={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,s),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let s of this.cache.values())r+=this.estimateSize(s.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,s]of this.cache.entries())s.ttlMs>0&&t-s.createdAt.getTime()>s.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},q=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...ge,...t},this.generationCache=new M(t),this.embeddingCache=new M(t),this.completionCache=new M(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=M.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,s){if(!this.config.cacheGenerations)return;let n=M.generateKey("generation",t,r);this.generationCache.set(n,e,s)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=M.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,s){if(!this.config.cacheEmbeddings)return;let n=M.generateKey("embedding",t,r);this.embeddingCache.set(n,e,s)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=M.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,s){if(!this.config.cacheCompletions)return;let n=M.generateKey("completion",t,r);this.completionCache.set(n,e,s)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),s=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,o=s+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:s,misses:n,hitRate:o>0?s/o:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};var Re=`
|
|
3
|
-
CREATE TABLE IF NOT EXISTS llm_spend (
|
|
4
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
|
-
ts INTEGER NOT NULL,
|
|
6
|
-
provider TEXT NOT NULL,
|
|
7
|
-
model TEXT NOT NULL,
|
|
8
|
-
cost_usd REAL NOT NULL,
|
|
9
|
-
cost_source TEXT NOT NULL,
|
|
10
|
-
prompt_tokens INTEGER NOT NULL DEFAULT 0,
|
|
11
|
-
completion_tokens INTEGER NOT NULL DEFAULT 0,
|
|
12
|
-
request_id TEXT
|
|
13
|
-
);
|
|
14
|
-
CREATE INDEX IF NOT EXISTS idx_llm_spend_ts ON llm_spend(ts);
|
|
15
|
-
`,oe=class{db;constructor(t){this.db=t,this.db.exec(Re)}record(t){try{this.db.prepare(`INSERT INTO llm_spend
|
|
16
|
-
(ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id)
|
|
17
|
-
VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId})}catch{}}spentSince(t,e=Date.now()){try{return this.db.prepare("SELECT COALESCE(SUM(cost_usd), 0) AS total FROM llm_spend WHERE ts >= ?").get(e-t)?.total??0}catch{return 0}}},N=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd})}spentSince(t,e=Date.now()){let r=e-t,s=0;for(let n of this.entries)n.ts>=r&&(s+=n.costUsd);return s}};async function fe(){try{let t=(await import("./unified-memory-OUVCMFGK.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new oe(t.getDatabase())}catch{return new N}}L();function ne(g,t,e,r){let s=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*s;return s+n}var we=1e3,_e=3e4;function v(g,t=we,e=_e){return ne(g,t,e,0)}import{readFileSync as Me}from"fs";import*as ye from"path";var ie=["low","medium","high","xhigh","max"],Ae="xhigh";function G(g){return typeof g=="string"&&ie.includes(g)}var B;function Le(g){try{let e=Me(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&G(e[1])?e[1]:null}catch{return null}}function be(g={}){if(g.override&&G(g.override))return g.override;if(g.agentEffort&&G(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&G(e))return e;let r=g.fleetDefaultsPath??ye.join(process.cwd(),"config","fleet-defaults.yaml");return B===void 0&&(B=Le(r)),B||Ae}function ve(g,t){let e=ie.indexOf(g),r=ie.indexOf(t);return e>r?t:g}var Pe={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},$=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...Pe,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),s=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:s,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:s,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let s=this.formatMessages(t),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s};e?.systemPrompt&&(h.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(h.stop_sequences=e.stopSequences);try{if(me(n).supportsEffortXHigh){let d=be({override:e?.effort}),u=ve(d,"xhigh");h.thinking={type:"adaptive",effort:u}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),d=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let u=await c.json(),m=u.usage.cache_creation_input_tokens??0,f=u.usage.cache_read_input_tokens??0,b={promptTokens:u.usage.input_tokens,completionTokens:u.usage.output_tokens,totalTokens:u.usage.input_tokens+m+f+u.usage.output_tokens,cacheCreationTokens:m,cacheReadTokens:f},y=R.calculateCost(n,b);return T.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:u.usage.input_tokens,outputTokens:u.usage.output_tokens,totalTokens:u.usage.input_tokens+u.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:u.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:u.model,provider:"claude",usage:b,cost:y,latencyMs:d,finishReason:this.mapFinishReason(u.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:n,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
18
|
-
|
|
19
|
-
`,"```"]});return{completion:r.content,model:r.model,provider:"claude",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["claude-opus-4-7","claude-sonnet-4-6","claude-haiku-4-5-20251001","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getCostPerToken(){return R.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.ANTHROPIC_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.ANTHROPIC_BASE_URL??"https://api.anthropic.com").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","x-api-key":this.getApiKey(),"anthropic-version":this.config.anthropicVersion??"2023-06-01"}}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let s="error"in e?e.error?.message??"Unknown API error":"Unknown API error",n="error"in e&&"type"in e.error?e.error.type:"";switch(t){case 401:throw a(s,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(s,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n==="invalid_request_error"&&s.includes("context")?a(s,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(s,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(s,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(s,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}):o}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){let l=v(o);await this.sleep(l);continue}return i}catch(i){if(n=E(i),o<s-1){let l=v(o);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};import{spawn as Oe}from"node:child_process";var Ie=["ANTHROPIC_API_KEY","CLAUDE_API_KEY","ANTHROPIC_AUTH_TOKEN"],Se={model:"sonnet",maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:1,binaryPath:"claude",maxConcurrency:2,disallowedTools:["Bash","Edit","Write","NotebookEdit","WebFetch","WebSearch","Task"]},F=class g{type="claude-code";name="Claude Code (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...Se,...t};let e=Number.parseInt(process.env.AQE_CLAUDE_CODE_CONCURRENCY??"",10);Number.isFinite(e)&&e>0&&(this.config.maxConcurrency=e)}async isAvailable(){let t=Date.now();if(this.availabilityCache&&t-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=!1;try{let{code:r}=await this.runProcess(["--version"],void 0,5e3);e=r===0}catch{e=!1}return this.availabilityCache={at:t,available:e},e}async healthCheck(){let t=Date.now(),e=await this.isAvailable(),r=Date.now()-t;return e?{healthy:!0,latencyMs:r,models:this.getSupportedModels(),details:{binaryPath:this.config.binaryPath,billing:"subscription"}}:{healthy:!1,latencyMs:r,error:`Claude Code CLI ("${this.config.binaryPath}") not found or not runnable. Install Claude Code and log in with your Pro/Max account.`}}async generate(t,e){let r=this.toCliModel(e?.model??this.config.model),s=`claude-code-${++this.requestId}-${Date.now()}`,{prompt:n,systemPrompt:o}=this.flatten(t,e?.systemPrompt),i=["-p","--output-format","json","--model",r];o&&i.push("--append-system-prompt",o);let l=this.config.disallowedTools??[];l.length>0&&i.push("--disallowedTools",...l);let p=Date.now(),h=e?.timeoutMs??this.config.timeoutMs??12e4,{code:c,stdout:d,stderr:u}=await this.withConcurrency(()=>this.runProcess(i,n,h)),m=Date.now()-p;if(c!==0&&!d.trim())throw this.classifyError(u||`claude exited with code ${c}`,r);let f;try{f=JSON.parse(d)}catch{throw a(`Could not parse claude -p JSON output: ${d.slice(0,200)}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",model:r,retryable:!0})}if(f.is_error)throw this.classifyError(f.result??f.api_error_status??"claude error",r);let b=f.usage??{},y={promptTokens:b.input_tokens??0,completionTokens:b.output_tokens??0,totalTokens:(b.input_tokens??0)+(b.output_tokens??0),cacheCreationTokens:b.cache_creation_input_tokens??0,cacheReadTokens:b.cache_read_input_tokens??0},C=f.modelUsage&&Object.keys(f.modelUsage)[0]||r;return T.recordTokenUsage(s,"claude-code-provider","llm","generate",{inputTokens:y.promptTokens,outputTokens:y.completionTokens,totalTokens:y.totalTokens,estimatedCostUsd:0}),{content:f.result??"",model:C,provider:"claude-code",usage:y,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"provider-receipt"},latencyMs:m,finishReason:this.mapFinishReason(f.stop_reason),cached:!1,requestId:s}}async embed(t,e){throw a("Claude Code provider does not support embeddings. Use openai, ollama, or cognitum.","MODEL_NOT_FOUND",{provider:"claude-code",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256});return{completion:r.content,model:r.model,provider:"claude-code",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["opus","sonnet","haiku"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}toCliModel(t){let e=t.toLowerCase();return e.includes("opus")?"opus":e.includes("haiku")?"haiku":e.includes("sonnet")?"sonnet":t}flatten(t,e){if(typeof t=="string")return{prompt:t,systemPrompt:e};let r=t.filter(n=>n.role==="system").map(n=>n.content);return e&&r.unshift(e),{prompt:t.filter(n=>n.role!=="system").map(n=>`${n.role==="assistant"?"Assistant":"User"}: ${n.content}`).join(`
|
|
20
|
-
|
|
21
|
-
`),systemPrompt:r.length>0?r.join(`
|
|
22
|
-
|
|
23
|
-
`):void 0}}mapFinishReason(t){return t==="max_tokens"?"length":"stop"}classifyError(t,e){let r=t.toLowerCase();return r.includes("rate limit")||r.includes("usage limit")||r.includes("429")||r.includes("quota")?a(t,"RATE_LIMITED",{provider:"claude-code",model:e,retryable:!0,retryAfterMs:6e4}):a(t,"PROVIDER_UNAVAILABLE",{provider:"claude-code",model:e,retryable:!0})}static childEnv(t=process.env){let e={...t};for(let r of Ie)delete e[r];return e}runProcess(t,e,r){return new Promise((s,n)=>{let o=Oe(this.config.binaryPath??"claude",t,{env:g.childEnv(),stdio:["pipe","pipe","pipe"]}),i="",l="",p=!1,h=setTimeout(()=>{p||(p=!0,o.kill("SIGKILL"),n(a("claude -p timed out","TIMEOUT",{provider:"claude-code",retryable:!0})))},r);o.stdout.on("data",c=>i+=c.toString()),o.stderr.on("data",c=>l+=c.toString()),o.on("error",c=>{p||(p=!0,clearTimeout(h),n(a(`Failed to spawn claude: ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",retryable:!1,cause:c})))}),o.on("close",c=>{p||(p=!0,clearTimeout(h),s({code:c??0,stdout:i,stderr:l}))}),e!==void 0&&o.stdin.write(e),o.stdin.end()})}async withConcurrency(t){let e=this.config.maxConcurrency??2;this.active>=e&&await new Promise(r=>this.queue.push(r)),this.active++;try{return await t()}finally{this.active--;let r=this.queue.shift();r&&r()}}};L();var xe={model:"cognitum-auto",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0},W=class{type="cognitum";name="Cognitum";billingMode="metered-capped";config;requestId=0;constructor(t={}){this.config={...xe,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set COGNITUM_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/models`,{method:"GET",headers:this.getHeaders()},5e3),s=Date.now()-e;return r.ok?{healthy:!0,latencyMs:s,models:this.getSupportedModels(),details:{billing:"metered-capped",baseUrl:this.getBaseUrl()}}:{healthy:!1,latencyMs:s,error:`API error: ${r.status}`}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Cognitum API key not configured","API_KEY_MISSING",{provider:"cognitum",retryable:!1});let s=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`cognitum-${++this.requestId}-${Date.now()}`,p=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s};e?.stopSequences?.length&&(h.stop=e.stopSequences);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),d=Date.now()-p;if(!c.ok)throw await this.toApiError(c,n);let u=await c.json(),m=u.x_cognitum,f={promptTokens:u.usage.prompt_tokens,completionTokens:u.usage.completion_tokens,totalTokens:u.usage.total_tokens,cacheReadTokens:u.usage.cache_read_tokens??0},b=this.receiptCost(m);return T.recordTokenUsage(l,"cognitum-provider","llm","generate",{inputTokens:f.promptTokens,outputTokens:f.completionTokens,totalTokens:f.totalTokens,estimatedCostUsd:b.totalCost}),{content:u.choices[0]?.message?.content??"",model:m?.resolved_model??u.model,provider:"cognitum",usage:f,cost:b,latencyMs:d,finishReason:this.mapFinishReason(u.choices[0]?.finish_reason),cached:m?.cache==="hit",requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"cognitum",model:n,retryable:!0,cause:c})}}async embed(t,e){if(!this.getApiKey())throw a("Cognitum API key not configured","API_KEY_MISSING",{provider:"cognitum",retryable:!1});let s=e?.model??"cognitum-embed",n=Date.now();try{let o=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:s,input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!o.ok)throw await this.toApiError(o,s);let l=await o.json();return{embedding:l.data[0].embedding,model:l.x_cognitum?.resolved_model??l.model,provider:"cognitum",tokenCount:l.usage.total_tokens,latencyMs:i,cached:!1}}catch(o){throw o instanceof Error&&"code"in o?o:a(o instanceof Error?o.message:"Embedding request failed","NETWORK_ERROR",{provider:"cognitum",model:s,retryable:!0,cause:o})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences});return{completion:r.content,model:r.model,provider:"cognitum",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["cognitum-auto","cognitum-low","cognitum-mid","cognitum-high"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}async getRemoteBudget(){try{let t=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/usage`,{method:"GET",headers:this.getHeaders()},5e3);if(!t.ok)return;let r=(await t.json()).budget;return r?{servingBudgetUsd:r.servingBudgetUsd??0,hardCapUsd:r.hardCapUsd??0,committedUsd:r.committedUsd??0,headroomUsd:r.headroomUsd??0,status:r.status??"unknown",headroomExhausted:r.headroomExhausted??!1}:void 0}catch{return}}receiptCost(t){return{inputCost:0,outputCost:0,totalCost:t?.price_usd??0,currency:"USD",source:t?.price_usd!==void 0?"provider-receipt":"local-estimate"}}getApiKey(){return this.config.apiKey??process.env.COGNITUM_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.COGNITUM_BASE_URL??"https://api.cognitum.one").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","X-API-Key":this.getApiKey()}}formatMessages(t,e){let r=[];if(typeof t=="string")e&&r.push({role:"system",content:e}),r.push({role:"user",content:t});else{let s=t.some(n=>n.role==="system");e&&!s&&r.push({role:"system",content:e});for(let n of t)r.push({role:n.role,content:n.content})}return r}mapFinishReason(t){switch(t){case"length":return"length";case"content_filter":return"content_filter";default:return"stop"}}async toApiError(t,e){let r=await t.text().catch(()=>""),s=r;try{s=JSON.parse(r).error??r}catch{}switch(t.status){case 401:case 403:return a(s||"Unauthorized","API_KEY_INVALID",{provider:"cognitum",model:e,retryable:!1});case 402:return a(s||"Budget cap reached","COST_LIMIT_EXCEEDED",{provider:"cognitum",model:e,retryable:!1});case 429:return a(s||"Rate limited","RATE_LIMITED",{provider:"cognitum",model:e,retryable:!0,retryAfterMs:6e4});case 500:case 502:case 503:return a(s||"Provider unavailable","PROVIDER_UNAVAILABLE",{provider:"cognitum",model:e,retryable:!0,retryAfterMs:5e3});default:return a(s||`HTTP ${t.status}`,"UNKNOWN",{provider:"cognitum",model:e,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"cognitum",retryable:!0}):o}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){await this.sleep(v(o));continue}return i}catch(i){n=E(i),o<s-1&&await this.sleep(v(o))}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var Ue={model:"gpt-4o",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0},z=class{type="openai";name="OpenAI";config;requestId=0;constructor(t={}){this.config={...Ue,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set OPENAI_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),s=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:s,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:s,models:this.getSupportedModels(),details:{defaultModel:this.config.model,organization:this.config.organization}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("OpenAI API key not configured","API_KEY_MISSING",{provider:"openai",retryable:!1});let s=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`openai-${++this.requestId}-${Date.now()}`,p=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s};e?.stopSequences&&e.stopSequences.length>0&&(h.stop=e.stopSequences),this.config.presencePenalty!==void 0&&(h.presence_penalty=this.config.presencePenalty),this.config.frequencyPenalty!==void 0&&(h.frequency_penalty=this.config.frequencyPenalty);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),d=Date.now()-p;if(!c.ok){let y=await c.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(c.status,y,n)}let u=await c.json(),m={promptTokens:u.usage.prompt_tokens,completionTokens:u.usage.completion_tokens,totalTokens:u.usage.total_tokens},f=R.calculateCost(n,m);return T.recordTokenUsage(l,"openai-provider","llm","generate",{inputTokens:u.usage.prompt_tokens,outputTokens:u.usage.completion_tokens,totalTokens:u.usage.total_tokens,estimatedCostUsd:f.totalCost}),{content:u.choices[0]?.message?.content??"",model:u.model,provider:"openai",usage:m,cost:f,latencyMs:d,finishReason:this.mapFinishReason(u.choices[0]?.finish_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"openai",model:n,retryable:!0,cause:c})}}async embed(t,e){if(!this.getApiKey())throw a("OpenAI API key not configured","API_KEY_MISSING",{provider:"openai",retryable:!1});let s=e?.model??"text-embedding-3-small",n=Date.now();try{let o=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:s,input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!o.ok){let p=await o.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(o.status,p,s)}let l=await o.json();return{embedding:l.data[0].embedding,model:l.model,provider:"openai",tokenCount:l.usage.total_tokens,latencyMs:i,cached:!1}}catch(o){throw o instanceof Error&&"code"in o?o:a(o instanceof Error?o.message:"Embedding request failed","NETWORK_ERROR",{provider:"openai",model:s,retryable:!0,cause:o})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
24
|
-
|
|
25
|
-
`]});return{completion:r.content,model:r.model,provider:"openai",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-4","gpt-3.5-turbo"]}getCostPerToken(){return R.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.OPENAI_API_KEY}getBaseUrl(){return(this.config.baseUrl??"https://api.openai.com").replace(/\/$/,"")}getHeaders(){let t={"Content-Type":"application/json",Authorization:`Bearer ${this.getApiKey()}`};return this.config.organization&&(t["OpenAI-Organization"]=this.config.organization),t}formatMessages(t,e){let r=[];if(typeof t=="string")e&&r.push({role:"system",content:e}),r.push({role:"user",content:t});else{let s=t.some(n=>n.role==="system");e&&!s&&r.push({role:"system",content:e});for(let n of t)r.push({role:n.role,content:n.content})}return r}mapFinishReason(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content_filter";default:return"stop"}}handleApiError(t,e,r){let s=e.error?.message??"Unknown API error",n=e.error?.type??"",o=e.error?.code??"";switch(t){case 401:throw a(s,"API_KEY_INVALID",{provider:"openai",model:r,retryable:!1});case 429:throw a(s,"RATE_LIMITED",{provider:"openai",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw o==="context_length_exceeded"||n==="invalid_request_error"?a(s,"CONTEXT_LENGTH_EXCEEDED",{provider:"openai",model:r,retryable:!1}):a(s,"UNKNOWN",{provider:"openai",model:r,retryable:!1});case 500:case 502:case 503:throw a(s,"PROVIDER_UNAVAILABLE",{provider:"openai",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(s,"UNKNOWN",{provider:"openai",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"openai",retryable:!0}):o}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){let l=v(o);await this.sleep(l);continue}return i}catch(i){if(n=E(i),o<s-1){let l=v(o);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};Ce();var U={DEFAULT_TOK_PER_SEC:15,SAFETY_FACTOR:2.5,LOAD_OVERHEAD_MS:15e3,FLOOR_MS:3e4,CEIL_MS:6e5};function Te(g,t=U.DEFAULT_TOK_PER_SEC){let e=t>0?t:U.DEFAULT_TOK_PER_SEC,s=Math.max(0,g)/e*1e3*U.SAFETY_FACTOR+U.LOAD_OVERHEAD_MS;return Math.min(U.CEIL_MS,Math.max(U.FLOOR_MS,Math.round(s)))}var ke={model:"llama3.1",baseUrl:re("http://localhost:11434"),maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:2,contextLength:4096,keepAlive:"5m",enableCache:!0,enableCircuitBreaker:!0},j=class{type="ollama";name="Ollama (Local)";config;requestId=0;availableModels=[];observedTokPerSec=new Map;constructor(t={}){this.config={...ke,...t}}timeoutFor(t,e){let r=this.config.timeoutMs;return r&&r!==ke.timeoutMs?r:Te(e,this.observedTokPerSec.get(t))}recordThroughput(t,e,r){if(!e||!r||r<=0)return;let s=e/(r/1e9);if(!Number.isFinite(s)||s<=0)return;let n=this.observedTokPerSec.get(t);this.observedTokPerSec.set(t,n?n*.5+s*.5:s)}async isAvailable(){try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){let t=Date.now();try{let e=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3),r=Date.now()-t;if(!e.ok)return{healthy:!1,latencyMs:r,error:`Ollama server returned ${e.status}`};let s=await e.json();return this.availableModels=s.models?.map(o=>o.name.split(":")[0])??[],!this.availableModels.some(o=>o===this.config.model||o.startsWith(this.config.model)||this.config.model.startsWith(o))&&this.availableModels.length>0?{healthy:!0,latencyMs:r,models:this.availableModels,details:{warning:`Configured model '${this.config.model}' not found. Available: ${this.availableModels.join(", ")}`,defaultModel:this.config.model}}:{healthy:!0,latencyMs:r,models:this.availableModels,details:{defaultModel:this.config.model,modelCount:this.availableModels.length}}}catch(e){return{healthy:!1,error:`Ollama not running. Start with: ollama serve. Error: ${e instanceof Error?e.message:"Unknown"}`}}}async generate(t,e){let r=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,n=e?.temperature??this.config.temperature??.7,o=`ollama-${++this.requestId}-${Date.now()}`,i=Date.now(),l=Array.isArray(t);try{let p,h,c,d;if(l){let b=this.formatMessages(t,e?.systemPrompt);if(p=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,messages:b,stream:!1,options:{temperature:n,num_predict:s,stop:e?.stopSequences}})},e?.timeoutMs??this.timeoutFor(r,s)),!p.ok)throw await this.handleApiError(p,r);let y=await p.json();h=y.message.content,this.recordThroughput(r,y.eval_count,y.eval_duration),c=y.prompt_eval_count??this.estimateTokens(JSON.stringify(b)),d=y.eval_count??this.estimateTokens(h)}else{let b=e?.systemPrompt?`${e.systemPrompt}
|
|
26
|
-
|
|
27
|
-
${t}`:t;if(p=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,prompt:b,stream:!1,options:{temperature:n,num_predict:s,stop:e?.stopSequences}})},e?.timeoutMs??this.timeoutFor(r,s)),!p.ok)throw await this.handleApiError(p,r);let y=await p.json();h=y.response,this.recordThroughput(r,y.eval_count,y.eval_duration),c=y.prompt_eval_count??this.estimateTokens(b),d=y.eval_count??this.estimateTokens(h)}let u=Date.now()-i,m={promptTokens:c,completionTokens:d,totalTokens:c+d},f=R.calculateCost(r,m);return T.recordTokenUsage(o,"ollama-provider","llm","generate",{inputTokens:c,outputTokens:d,totalTokens:c+d,estimatedCostUsd:f.totalCost}),{content:h,model:r,provider:"ollama",usage:m,cost:f,latencyMs:u,finishReason:"stop",cached:!1,requestId:o}}catch(p){throw p instanceof Error&&"code"in p?p:a(p instanceof Error?p.message:"Request failed","NETWORK_ERROR",{provider:"ollama",model:r,retryable:!0,cause:p})}}async embed(t,e){let r=e?.model??"all-MiniLM-L6-v2",s=Date.now();try{let n=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,prompt:t})},e?.timeoutMs??3e4),o=Date.now()-s;if(!n.ok)throw await this.handleApiError(n,r);return{embedding:(await n.json()).embedding,model:r,provider:"ollama",tokenCount:this.estimateTokens(t),latencyMs:o,cached:!1}}catch(n){throw n instanceof Error&&"code"in n?n:a(n instanceof Error?n.message:"Embedding request failed","NETWORK_ERROR",{provider:"ollama",model:r,retryable:!0,cause:n})}}async complete(t,e){let r=e?.model??this.selectCodeModel(),s=await this.generate(t,{model:r,temperature:e?.temperature??.1,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
28
|
-
|
|
29
|
-
`,"```","// ","# "]});return{completion:s.content,model:s.model,provider:"ollama",usage:s.usage,latencyMs:s.latencyMs,cached:s.cached}}getConfig(){return{...this.config}}getSupportedModels(){let t=["llama3","llama3.1","llama3.2","codellama","mistral","mixtral","phi3","qwen2","gemma","nomic-embed-text"],e=new Set([...t,...this.availableModels]);return Array.from(e)}getCostPerToken(){return{input:0,output:0}}async dispose(){}async pullModel(t){try{let e=await this.fetchWithTimeout(`${this.getBaseUrl()}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,stream:!1})},6e5);if(!e.ok){let r=await e.text();throw new Error(`Failed to pull model: ${r}`)}}catch(e){throw a(`Failed to pull model ${t}: ${e instanceof Error?e.message:"Unknown"}`,"MODEL_NOT_FOUND",{provider:"ollama",model:t,retryable:!0})}}getBaseUrl(){return(this.config.baseUrl??re()).replace(/\/$/,"")}formatMessages(t,e){let r=[];e&&r.push({role:"system",content:e});for(let s of t)r.push({role:s.role,content:s.content});return r}selectCodeModel(){let t=["codellama","llama3.1","llama3","mistral"];for(let e of t)if(this.availableModels.some(r=>r===e||r.startsWith(e)))return e;return this.config.model}estimateTokens(t){return Math.ceil(t.length/4)}async handleApiError(t,e){let r=await t.text().catch(()=>"Unknown error");throw t.status===404?a(`Model '${e}' not found. Pull it with: ollama pull ${e}`,"MODEL_NOT_FOUND",{provider:"ollama",model:e,retryable:!1}):t.status===500?a(`Ollama server error: ${r}`,"PROVIDER_UNAVAILABLE",{provider:"ollama",model:e,retryable:!0,retryAfterMs:1e3}):a(`Ollama API error (${t.status}): ${r}`,"UNKNOWN",{provider:"ollama",model:e,retryable:!1})}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"ollama",retryable:!0}):o}finally{clearTimeout(n)}}};L();ce();var Ne={model:"anthropic/claude-3.5-sonnet",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,baseUrl:"https://openrouter.ai/api/v1",allowFallback:!1},H={"anthropic/claude-3.5-sonnet":{input:3,output:15},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15},"anthropic/claude-3-opus":{input:15,output:75},"anthropic/claude-3-sonnet":{input:3,output:15},"anthropic/claude-3-haiku":{input:.25,output:1.25},"openai/gpt-4o":{input:5,output:15},"openai/gpt-4o-mini":{input:.15,output:.6},"openai/gpt-4-turbo":{input:10,output:30},"openai/gpt-3.5-turbo":{input:.5,output:1.5},"google/gemini-pro":{input:.125,output:.375},"google/gemini-pro-1.5":{input:3.5,output:10.5},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06},"mistralai/mistral-large":{input:2,output:6},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24},"mistralai/mistral-7b-instruct":{input:.06,output:.06},default:{input:1,output:3}},V=class{type="openrouter";name="OpenRouter";config;requestId=0;cachedModels=null;constructor(t={}){this.config={...Ne,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set OPENROUTER_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/models`,{method:"GET",headers:this.getHeaders()},5e3),s=Date.now()-e;if(!r.ok){let i=await r.text();return{healthy:!1,latencyMs:s,error:`API error: ${r.status} - ${i}`}}let o=(await r.json()).data?.map(i=>i.id)||[];return this.cachedModels=o,{healthy:!0,latencyMs:s,models:o.slice(0,20),details:{totalModels:o.length,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("OpenRouter API key not configured","API_KEY_MISSING",{provider:"openrouter",retryable:!1});let s=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`openrouter-${++this.requestId}-${Date.now()}`,p=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s};e?.stopSequences&&e.stopSequences.length>0&&(h.stop=e.stopSequences),this.config.allowFallback!==void 0&&(h.route=this.config.allowFallback?"fallback":void 0),this.config.forceProvider&&(h.provider={order:[this.config.forceProvider]});try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),d=Date.now()-p;if(!c.ok){let y=await c.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(c.status,y,n)}let u=await c.json(),m={promptTokens:u.usage?.prompt_tokens??0,completionTokens:u.usage?.completion_tokens??0,totalTokens:u.usage?.total_tokens??0},f=this.calculateCost(n,m);return T.recordTokenUsage(l,"openrouter-provider","llm","generate",{inputTokens:m.promptTokens,outputTokens:m.completionTokens,totalTokens:m.totalTokens,estimatedCostUsd:f.totalCost}),{content:u.choices[0]?.message?.content??"",model:u.model,provider:"openrouter",usage:m,cost:f,latencyMs:d,finishReason:this.mapFinishReason(u.choices[0]?.finish_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"openrouter",model:n,retryable:!0,cause:c})}}async*generateStream(t,e){if(!this.getApiKey())throw a("OpenRouter API key not configured","API_KEY_MISSING",{provider:"openrouter",retryable:!1});let s=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`openrouter-stream-${++this.requestId}-${Date.now()}`,p=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s,stream:!0};e?.stopSequences&&e.stopSequences.length>0&&(h.stop=e.stopSequences);let c=await this.fetchWithTimeout(`${this.getBaseUrl()}/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4);if(!c.ok){let _=await c.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(c.status,_,n)}if(!c.body)throw a("No response body for streaming","NETWORK_ERROR",{provider:"openrouter",model:n,retryable:!0});let d="",u="stop",m=n,f=c.body.getReader(),b=new TextDecoder,y="";try{for(;;){let{done:_,value:ee}=await f.read();if(_)break;y+=b.decode(ee,{stream:!0});let x=y.split(`
|
|
30
|
-
`);y=x.pop()||"";for(let A of x){let P=A.trim();if(!(!P||P==="data: [DONE]")&&P.startsWith("data: "))try{let I=D(P.slice(6)),te=I.choices[0]?.delta;te?.content&&(d+=te.content,yield te.content),I.choices[0]?.finish_reason&&(u=this.mapFinishReason(I.choices[0].finish_reason)),I.model&&(m=I.model)}catch{}}}}finally{f.releaseLock()}let C=Date.now()-p,k=Math.ceil(JSON.stringify(s).length/4),O=Math.ceil(d.length/4),w={promptTokens:k,completionTokens:O,totalTokens:k+O},S=this.calculateCost(n,w);return T.recordTokenUsage(l,"openrouter-provider","llm","generate-stream",{inputTokens:w.promptTokens,outputTokens:w.completionTokens,totalTokens:w.totalTokens,estimatedCostUsd:S.totalCost}),{content:d,model:m,provider:"openrouter",usage:w,cost:S,latencyMs:C,finishReason:u,cached:!1,requestId:l}}async embed(t,e){if(!this.getApiKey())throw a("OpenRouter API key not configured","API_KEY_MISSING",{provider:"openrouter",retryable:!1});let s=e?.model??"openai/text-embedding-3-small",n=Date.now();try{let o=await this.fetchWithTimeout(`${this.getBaseUrl()}/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:s,input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!o.ok){let p=await o.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(o.status,p,s)}let l=await o.json();return{embedding:l.data[0].embedding,model:l.model,provider:"openrouter",tokenCount:l.usage.total_tokens,latencyMs:i,cached:!1}}catch(o){throw o instanceof Error&&"code"in o?o:a(o instanceof Error?o.message:"Embedding request failed","NETWORK_ERROR",{provider:"openrouter",model:s,retryable:!0,cause:o})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
31
|
-
|
|
32
|
-
`]});return{completion:r.content,model:r.model,provider:"openrouter",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return this.cachedModels?this.cachedModels:["anthropic/claude-3.5-sonnet","anthropic/claude-3-opus","anthropic/claude-3-sonnet","anthropic/claude-3-haiku","openai/gpt-4o","openai/gpt-4o-mini","openai/gpt-4-turbo","openai/gpt-3.5-turbo","google/gemini-pro","google/gemini-pro-1.5","meta-llama/llama-3.1-70b-instruct","meta-llama/llama-3.1-8b-instruct","mistralai/mistral-large","mistralai/mixtral-8x7b-instruct"]}getCostPerToken(){let t=H[this.config.model]||H.default;return{input:t.input/1e6,output:t.output/1e6}}async dispose(){this.cachedModels=null}calculateCost(t,e){let r=H[t]||H.default,s=e.promptTokens/1e6*r.input,n=e.completionTokens/1e6*r.output;return{inputCost:s,outputCost:n,totalCost:s+n,currency:"USD"}}getApiKey(){return this.config.apiKey??process.env.OPENROUTER_API_KEY}getBaseUrl(){return(this.config.baseUrl??"https://openrouter.ai/api/v1").replace(/\/$/,"")}getHeaders(){let t={"Content-Type":"application/json",Authorization:`Bearer ${this.getApiKey()}`};return this.config.siteUrl&&(t["HTTP-Referer"]=this.config.siteUrl),this.config.siteName&&(t["X-Title"]=this.config.siteName),t}formatMessages(t,e){let r=[];if(typeof t=="string")e&&r.push({role:"system",content:e}),r.push({role:"user",content:t});else{let s=t.some(n=>n.role==="system");e&&!s&&r.push({role:"system",content:e});for(let n of t)r.push({role:n.role,content:n.content})}return r}mapFinishReason(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content_filter";case"tool_calls":return"stop";default:return"stop"}}handleApiError(t,e,r){let s=e.error?.message??"Unknown API error",n=e.error?.type??"",o=e.error?.code;switch(t){case 401:throw a(s,"API_KEY_INVALID",{provider:"openrouter",model:r,retryable:!1});case 402:throw a(s,"COST_LIMIT_EXCEEDED",{provider:"openrouter",model:r,retryable:!1});case 429:throw a(s,"RATE_LIMITED",{provider:"openrouter",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw o==="context_length_exceeded"||n==="invalid_request_error"?a(s,"CONTEXT_LENGTH_EXCEEDED",{provider:"openrouter",model:r,retryable:!1}):a(s,"UNKNOWN",{provider:"openrouter",model:r,retryable:!1});case 404:throw a(s,"MODEL_NOT_FOUND",{provider:"openrouter",model:r,retryable:!1});case 500:case 502:case 503:throw a(s,"PROVIDER_UNAVAILABLE",{provider:"openrouter",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(s,"UNKNOWN",{provider:"openrouter",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"openrouter",retryable:!0}):o}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){let l=v(o);await this.sleep(l);continue}return i}catch(i){if(n=E(i),o<s-1){let l=v(o);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();ce();var De={model:"gemini-2.5-flash",maxTokens:8192,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,baseUrl:"https://generativelanguage.googleapis.com/v1beta",safetyThreshold:"BLOCK_MEDIUM_AND_ABOVE"},Y={"gemini-pro":{input:.5,output:1.5},"gemini-1.0-pro":{input:.5,output:1.5},"gemini-1.5-pro":{input:3.5,output:10.5},"gemini-1.5-pro-latest":{input:3.5,output:10.5},"gemini-1.5-flash":{input:.075,output:.3},"gemini-1.5-flash-latest":{input:.075,output:.3},"gemini-2.0-flash-exp":{input:.075,output:.3},"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.3,output:2.5},"gemini-flash-latest":{input:.3,output:2.5},"gemini-ultra":{input:7,output:21},"gemini-1.0-ultra":{input:7,output:21},default:{input:1,output:3}},J=class{type="gemini";name="Google Gemini";config;requestId=0;cachedModels=null;constructor(t={}){this.config={...De,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){let t=this.getApiKey();if(!t)return{healthy:!1,error:"API key not configured. Set GOOGLE_AI_API_KEY, GEMINI_API_KEY, or GOOGLE_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/models?key=${t}`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3),s=Date.now()-e;if(!r.ok){let i=await r.text();return{healthy:!1,latencyMs:s,error:`API error: ${r.status} - ${i}`}}let o=(await r.json()).models?.filter(i=>i.supportedGenerationMethods?.includes("generateContent")).map(i=>i.name.replace("models/",""))||[];return this.cachedModels=o,{healthy:!0,latencyMs:s,models:o.slice(0,20),details:{totalModels:o.length,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){let r=this.getApiKey();if(!r)throw a("Gemini API key not configured","API_KEY_MISSING",{provider:"gemini",retryable:!1});let s=this.formatContents(t),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??8192,i=e?.temperature??this.config.temperature??.7,l=`gemini-${++this.requestId}-${Date.now()}`,p=Date.now(),h={contents:s,generationConfig:{maxOutputTokens:o,temperature:i,topP:this.config.topP}};e?.systemPrompt&&(h.systemInstruction={parts:[{text:e.systemPrompt}]}),e?.stopSequences&&e.stopSequences.length>0&&(h.generationConfig.stopSequences=e.stopSequences);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/models/${n}:generateContent?key=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),d=Date.now()-p;if(!c.ok){let y=await c.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(c.status,y,n)}let u=await c.json(),m={promptTokens:u.usageMetadata?.promptTokenCount??0,completionTokens:u.usageMetadata?.candidatesTokenCount??0,totalTokens:u.usageMetadata?.totalTokenCount??0},f=this.calculateCost(n,m);return T.recordTokenUsage(l,"gemini-provider","llm","generate",{inputTokens:m.promptTokens,outputTokens:m.completionTokens,totalTokens:m.totalTokens,estimatedCostUsd:f.totalCost}),{content:u.candidates[0]?.content?.parts?.map(y=>y.text??"").join("")??"",model:u.modelVersion??n,provider:"gemini",usage:m,cost:f,latencyMs:d,finishReason:this.mapFinishReason(u.candidates[0]?.finishReason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"gemini",model:n,retryable:!0,cause:c})}}async*generateStream(t,e){let r=this.getApiKey();if(!r)throw a("Gemini API key not configured","API_KEY_MISSING",{provider:"gemini",retryable:!1});let s=this.formatContents(t),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??8192,i=e?.temperature??this.config.temperature??.7,l=`gemini-stream-${++this.requestId}-${Date.now()}`,p=Date.now(),h={contents:s,generationConfig:{maxOutputTokens:o,temperature:i}};e?.systemPrompt&&(h.systemInstruction={parts:[{text:e.systemPrompt}]});let c=await this.fetchWithTimeout(`${this.getBaseUrl()}/models/${n}:streamGenerateContent?key=${r}&alt=sse`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4);if(!c.ok){let w=await c.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(c.status,w,n)}if(!c.body)throw a("No response body for streaming","NETWORK_ERROR",{provider:"gemini",model:n,retryable:!0});let d="",u="stop",m={promptTokens:0,completionTokens:0,totalTokens:0},f=c.body.getReader(),b=new TextDecoder,y="";try{for(;;){let{done:w,value:S}=await f.read();if(w)break;y+=b.decode(S,{stream:!0});let _=y.split(`
|
|
33
|
-
`);y=_.pop()||"";for(let ee of _){let x=ee.trim();if(!(!x||!x.startsWith("data: ")))try{let A=D(x.slice(6)),P=A.candidates?.[0]?.content?.parts?.map(I=>I.text??"").join("")??"";P&&(d+=P,yield P),A.candidates?.[0]?.finishReason&&(u=this.mapFinishReason(A.candidates[0].finishReason)),A.usageMetadata&&(m={promptTokens:A.usageMetadata.promptTokenCount,completionTokens:A.usageMetadata.candidatesTokenCount,totalTokens:A.usageMetadata.totalTokenCount})}catch{}}}}finally{f.releaseLock()}let C=Date.now()-p,k=m.totalTokens>0?m:{promptTokens:Math.ceil(JSON.stringify(s).length/4),completionTokens:Math.ceil(d.length/4),totalTokens:0};k.totalTokens=k.promptTokens+k.completionTokens;let O=this.calculateCost(n,k);return T.recordTokenUsage(l,"gemini-provider","llm","generate-stream",{inputTokens:k.promptTokens,outputTokens:k.completionTokens,totalTokens:k.totalTokens,estimatedCostUsd:O.totalCost}),{content:d,model:n,provider:"gemini",usage:k,cost:O,latencyMs:C,finishReason:u,cached:!1,requestId:l}}async embed(t,e){let r=this.getApiKey();if(!r)throw a("Gemini API key not configured","API_KEY_MISSING",{provider:"gemini",retryable:!1});let s=e?.model??"text-embedding-004",n=Date.now();try{let o=await this.fetchWithTimeout(`${this.getBaseUrl()}/models/${s}:embedContent?key=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:{parts:[{text:t}]}})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!o.ok){let p=await o.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(o.status,p,s)}return{embedding:(await o.json()).embedding.values,model:s,provider:"gemini",tokenCount:Math.ceil(t.length/4),latencyMs:i,cached:!1}}catch(o){throw o instanceof Error&&"code"in o?o:a(o instanceof Error?o.message:"Embedding request failed","NETWORK_ERROR",{provider:"gemini",model:s,retryable:!0,cause:o})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
34
|
-
|
|
35
|
-
`]});return{completion:r.content,model:r.model,provider:"gemini",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return this.cachedModels?this.cachedModels:["gemini-flash-latest","gemini-pro-latest","gemini-flash-lite-latest","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-3.5-flash"]}getCostPerToken(){let t=Y[this.config.model]||Y.default;return{input:t.input/1e6,output:t.output/1e6}}async dispose(){this.cachedModels=null}calculateCost(t,e){let r=Y[t]||Y.default,s=e.promptTokens/1e6*r.input,n=e.completionTokens/1e6*r.output;return{inputCost:s,outputCost:n,totalCost:s+n,currency:"USD"}}getApiKey(){return this.config.apiKey??process.env.GOOGLE_AI_API_KEY??process.env.GEMINI_API_KEY??process.env.GOOGLE_API_KEY}getBaseUrl(){return(this.config.baseUrl??"https://generativelanguage.googleapis.com/v1beta").replace(/\/$/,"")}formatContents(t){return typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role==="assistant"?"model":"user",parts:[{text:e.content}]}))}mapFinishReason(t){switch(t){case"STOP":return"stop";case"MAX_TOKENS":return"length";case"SAFETY":return"content_filter";case"RECITATION":return"content_filter";default:return"stop"}}handleApiError(t,e,r){let s=e.error?.message??"Unknown API error";switch(t){case 400:throw s.includes("token")||s.includes("length")||s.includes("exceeds")?a(s,"CONTEXT_LENGTH_EXCEEDED",{provider:"gemini",model:r,retryable:!1}):s.includes("API key")?a(s,"API_KEY_INVALID",{provider:"gemini",model:r,retryable:!1}):a(s,"UNKNOWN",{provider:"gemini",model:r,retryable:!1});case 401:case 403:throw a(s,"API_KEY_INVALID",{provider:"gemini",model:r,retryable:!1});case 404:throw a(s,"MODEL_NOT_FOUND",{provider:"gemini",model:r,retryable:!1});case 429:throw a(s,"RATE_LIMITED",{provider:"gemini",model:r,retryable:!0,retryAfterMs:6e4});case 500:case 502:case 503:throw a(s,"PROVIDER_UNAVAILABLE",{provider:"gemini",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(s,"UNKNOWN",{provider:"gemini",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"gemini",retryable:!0}):o}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){let l=v(o);await this.sleep(l);continue}return i}catch(i){if(n=E(i),o<s-1){let l=v(o);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var Ke={model:"gpt-4o",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,apiVersion:"2024-02-15-preview"},X=class{type="azure-openai";name="Azure OpenAI";config;requestId=0;constructor(t){this.config={...Ke,...t}}async isAvailable(){let t=this.getEndpoint(),e=this.getApiKey()||this.getAzureAdToken();if(!t||!e||!this.config.deploymentId)return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){let t=this.getEndpoint(),e=this.getApiKey()||this.getAzureAdToken();if(!t)return{healthy:!1,error:"Azure endpoint not configured. Set AZURE_OPENAI_ENDPOINT environment variable."};if(!e)return{healthy:!1,error:"Azure authentication not configured. Set AZURE_OPENAI_API_KEY or provide azureAdToken."};if(!this.config.deploymentId)return{healthy:!1,error:"Deployment ID not configured. Set AZURE_OPENAI_DEPLOYMENT or provide deploymentId."};let r=Date.now();try{let s=await this.fetchWithTimeout(this.buildUrl("chat/completions"),{method:"POST",headers:this.getHeaders(),body:JSON.stringify({max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),n=Date.now()-r;if(!s.ok){let o=await s.text();return{healthy:!1,latencyMs:n,error:`API error: ${s.status} - ${o}`}}return{healthy:!0,latencyMs:n,models:this.getSupportedModels(),details:{endpoint:this.getEndpoint(),deploymentId:this.config.deploymentId,apiVersion:this.config.apiVersion,authType:this.getAzureAdToken()?"Azure AD":"API Key"}}}catch(s){return{healthy:!1,error:s instanceof Error?s.message:"Unknown error"}}}async generate(t,e){let r=this.getEndpoint(),s=this.getApiKey()||this.getAzureAdToken();if(!r||!s)throw a("Azure OpenAI not configured","API_KEY_MISSING",{provider:"azure-openai",retryable:!1});let n=this.formatMessages(t,e?.systemPrompt),o=e?.model??this.config.model??"gpt-4o",i=e?.maxTokens??this.config.maxTokens??4096,l=e?.temperature??this.config.temperature??.7,p=`azure-openai-${++this.requestId}-${Date.now()}`,h=Date.now(),c={max_tokens:i,temperature:l,messages:n};e?.stopSequences&&e.stopSequences.length>0&&(c.stop=e.stopSequences),this.config.presencePenalty!==void 0&&(c.presence_penalty=this.config.presencePenalty),this.config.frequencyPenalty!==void 0&&(c.frequency_penalty=this.config.frequencyPenalty);try{let d=await this.fetchWithRetry(this.buildUrl("chat/completions"),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(c)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-h;if(!d.ok){let C=await d.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(d.status,C,o)}let m=await d.json(),f={promptTokens:m.usage.prompt_tokens,completionTokens:m.usage.completion_tokens,totalTokens:m.usage.total_tokens},b=R.calculateCost(o,f);return T.recordTokenUsage(p,"azure-openai-provider","llm","generate",{inputTokens:m.usage.prompt_tokens,outputTokens:m.usage.completion_tokens,totalTokens:m.usage.total_tokens,estimatedCostUsd:b.totalCost}),{content:m.choices[0]?.message?.content??"",model:m.model,provider:"azure-openai",usage:f,cost:b,latencyMs:u,finishReason:this.mapFinishReason(m.choices[0]?.finish_reason),cached:!1,requestId:p}}catch(d){throw d instanceof Error&&"code"in d?d:a(d instanceof Error?d.message:"Request failed","NETWORK_ERROR",{provider:"azure-openai",model:o,retryable:!0,cause:d})}}async embed(t,e){let r=this.getEndpoint(),s=this.getApiKey()||this.getAzureAdToken();if(!r||!s)throw a("Azure OpenAI not configured","API_KEY_MISSING",{provider:"azure-openai",retryable:!1});let n=e?.model??this.config.deploymentId,o=Date.now();try{let i=await this.fetchWithTimeout(this.buildUrl("embeddings",n),{method:"POST",headers:this.getHeaders(),body:JSON.stringify({input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),l=Date.now()-o;if(!i.ok){let h=await i.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(i.status,h,n)}let p=await i.json();return{embedding:p.data[0].embedding,model:p.model,provider:"azure-openai",tokenCount:p.usage.total_tokens,latencyMs:l,cached:!1}}catch(i){throw i instanceof Error&&"code"in i?i:a(i instanceof Error?i.message:"Embedding request failed","NETWORK_ERROR",{provider:"azure-openai",model:n,retryable:!0,cause:i})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
36
|
-
|
|
37
|
-
`]});return{completion:r.content,model:r.model,provider:"azure-openai",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-4","gpt-35-turbo","text-embedding-ada-002","text-embedding-3-small","text-embedding-3-large"]}getCostPerToken(){return R.getCostPerToken(this.config.model??"gpt-4o")}async dispose(){}getApiKey(){return this.config.apiKey??process.env.AZURE_OPENAI_API_KEY}getAzureAdToken(){return this.config.azureAdToken}getEndpoint(){return(this.config.endpoint??process.env.AZURE_OPENAI_ENDPOINT)?.replace(/\/$/,"")}getApiVersion(){return this.config.apiVersion??process.env.AZURE_OPENAI_API_VERSION??"2024-02-15-preview"}buildUrl(t,e){let r=this.getEndpoint(),s=e??this.config.deploymentId,n=this.getApiVersion();return`${r}/openai/deployments/${s}/${t}?api-version=${n}`}getHeaders(){let t={"Content-Type":"application/json"},e=this.getAzureAdToken();if(e)t.Authorization=`Bearer ${e}`;else{let r=this.getApiKey();r&&(t["api-key"]=r)}return t}formatMessages(t,e){let r=[];if(typeof t=="string")e&&r.push({role:"system",content:e}),r.push({role:"user",content:t});else{let s=t.some(n=>n.role==="system");e&&!s&&r.push({role:"system",content:e});for(let n of t)r.push({role:n.role,content:n.content})}return r}mapFinishReason(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content_filter";default:return"stop"}}handleApiError(t,e,r){let s=e.error?.message??"Unknown API error",n=e.error?.code??"",o=e.error?.innererror?.code??"";switch(t){case 401:throw a(s,"API_KEY_INVALID",{provider:"azure-openai",model:r,retryable:!1});case 403:throw a(s,"API_KEY_INVALID",{provider:"azure-openai",model:r,retryable:!1});case 429:throw a(s,"RATE_LIMITED",{provider:"azure-openai",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n==="context_length_exceeded"||o==="context_length_exceeded"?a(s,"CONTEXT_LENGTH_EXCEEDED",{provider:"azure-openai",model:r,retryable:!1}):o==="content_filter"?a(s,"CONTENT_FILTERED",{provider:"azure-openai",model:r,retryable:!1}):a(s,"UNKNOWN",{provider:"azure-openai",model:r,retryable:!1});case 404:throw a(`Deployment not found: ${r}`,"MODEL_NOT_FOUND",{provider:"azure-openai",model:r,retryable:!1});case 500:case 502:case 503:throw a(s,"PROVIDER_UNAVAILABLE",{provider:"azure-openai",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(s,"UNKNOWN",{provider:"azure-openai",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"azure-openai",retryable:!0}):o}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){let l=v(o);await this.sleep(l);continue}return i}catch(i){if(n=E(i),o<s-1){let l=v(o);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var qe={model:"anthropic.claude-3-5-sonnet-20241022-v2:0",region:"us-east-1",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0},ae={"claude-opus-4-7":"anthropic.claude-opus-4-7-v1:0","claude-sonnet-4-6":"anthropic.claude-sonnet-4-6-v1:0","claude-haiku-4-5-20251001":"anthropic.claude-haiku-4-5-v1:0","claude-haiku-4-5":"anthropic.claude-haiku-4-5-v1:0","claude-opus-4-5-20251101":"anthropic.claude-opus-4-5-v1:0","claude-opus-4-5":"anthropic.claude-opus-4-5-v1:0","claude-opus-4-20250514":"anthropic.claude-opus-4-v1:0","claude-opus-4":"anthropic.claude-opus-4-v1:0","claude-sonnet-4-20250514":"anthropic.claude-sonnet-4-v1:0","claude-sonnet-4":"anthropic.claude-sonnet-4-v1:0","claude-3-5-haiku-20241022":"anthropic.claude-3-5-haiku-v1:0","claude-haiku-3-5":"anthropic.claude-3-5-haiku-v1:0","claude-sonnet-4-5-20250929":"anthropic.claude-sonnet-4-5-v2:0","claude-sonnet-4-5":"anthropic.claude-sonnet-4-5-v2:0","claude-3-opus-20240229":"anthropic.claude-3-opus-20240229-v1:0","claude-3-sonnet-20240229":"anthropic.claude-3-sonnet-20240229-v1:0","claude-3-haiku-20240307":"anthropic.claude-3-haiku-20240307-v1:0","claude-3-5-sonnet-20241022":"anthropic.claude-3-5-sonnet-20241022-v2:0"},co=Object.fromEntries(Object.entries(ae).map(([g,t])=>[t,g])),Q=class{type="bedrock";name="AWS Bedrock";config;requestId=0;constructor(t={}){this.config={...qe,...t}}async isAvailable(){if(!this.getCredentials())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getCredentials())return{healthy:!1,error:"AWS credentials not configured. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or use IAM role."};let e=Date.now();try{let r=this.mapToBedrockModel(this.config.model),s=await this.invokeModel(r,{anthropic_version:"bedrock-2023-05-31",max_tokens:1,messages:[{role:"user",content:"Hi"}]},5e3),n=Date.now()-e;if(!s.ok){let o=await s.text();return{healthy:!1,latencyMs:n,error:`API error: ${s.status} - ${o}`}}return{healthy:!0,latencyMs:n,models:this.getSupportedModels(),details:{region:this.getRegion(),defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getCredentials())throw a("AWS credentials not configured","API_KEY_MISSING",{provider:"bedrock",retryable:!1});let s=this.formatMessages(t),n=e?.model??this.config.model,o=this.mapToBedrockModel(n),i=e?.maxTokens??this.config.maxTokens??4096,l=e?.temperature??this.config.temperature??.7,p=`bedrock-${++this.requestId}-${Date.now()}`,h=Date.now(),c={anthropic_version:"bedrock-2023-05-31",max_tokens:i,messages:s};l!==void 0&&(c.temperature=Math.min(Math.max(l,0),1)),e?.systemPrompt&&(c.system=e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(c.stop_sequences=e.stopSequences);try{let d=await this.invokeModelWithRetry(o,c,e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-h;if(!d.ok){let C=await d.json().catch(()=>({message:"Unknown error"}));throw this.handleApiError(d.status,C,n)}let m=await d.json(),f={promptTokens:m.usage.input_tokens,completionTokens:m.usage.output_tokens,totalTokens:m.usage.input_tokens+m.usage.output_tokens},b=R.calculateCost(o,f);return T.recordTokenUsage(p,"bedrock-provider","llm","generate",{inputTokens:m.usage.input_tokens,outputTokens:m.usage.output_tokens,totalTokens:m.usage.input_tokens+m.usage.output_tokens,estimatedCostUsd:b.totalCost}),{content:m.content.filter(C=>C.type==="text").map(C=>C.text).join(""),model:o,provider:"bedrock",usage:f,cost:b,latencyMs:u,finishReason:this.mapFinishReason(m.stop_reason),cached:!1,requestId:p}}catch(d){throw d instanceof Error&&"code"in d?d:a(d instanceof Error?d.message:"Request failed","NETWORK_ERROR",{provider:"bedrock",model:n,retryable:!0,cause:d})}}async embed(t,e){throw a("Bedrock Claude models do not support native embeddings. Use Bedrock Titan or Cohere for embeddings.","MODEL_NOT_FOUND",{provider:"bedrock",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
38
|
-
|
|
39
|
-
`,"```"]});return{completion:r.content,model:r.model,provider:"bedrock",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return Object.keys(ae)}getCostPerToken(){let t=this.mapToBedrockModel(this.config.model);return R.getCostPerToken(t)}async dispose(){}getCredentials(){let t=this.config.accessKeyId??process.env.AWS_ACCESS_KEY_ID,e=this.config.secretAccessKey??process.env.AWS_SECRET_ACCESS_KEY,r=this.config.sessionToken??process.env.AWS_SESSION_TOKEN;return!t||!e?null:{region:this.getRegion(),service:"bedrock",accessKeyId:t,secretAccessKey:e,sessionToken:r}}getRegion(){return this.config.region??process.env.AWS_REGION??process.env.AWS_DEFAULT_REGION??"us-east-1"}mapToBedrockModel(t){if(t.startsWith("anthropic."))return t;let e=ae[t];return e||t}getEndpointUrl(t){let e=this.getRegion();return`${this.config.baseUrl??`https://bedrock-runtime.${e}.amazonaws.com`}/model/${t}/invoke`}async invokeModel(t,e,r){let s=this.getCredentials();if(!s)throw a("AWS credentials not configured","API_KEY_MISSING",{provider:"bedrock",retryable:!1});let n=this.getEndpointUrl(t),o=JSON.stringify(e),i=await this.signRequest(n,o,s);return this.fetchWithTimeout(n,{method:"POST",headers:i,body:o},r)}async invokeModelWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.invokeModel(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){let l=v(o);await this.sleep(l);continue}return i}catch(i){if(n=E(i),o<s-1){let l=v(o);await this.sleep(l)}}throw n??new Error("Request failed after retries")}async signRequest(t,e,r){let s=new URL(t),o=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),i=o.substring(0,8),l={"Content-Type":"application/json",Host:s.host,"X-Amz-Date":o};r.sessionToken&&(l["X-Amz-Security-Token"]=r.sessionToken);let p="POST",h=s.pathname,c="",d=Object.keys(l).map(_=>_.toLowerCase()).sort().join(";"),u=Object.keys(l).map(_=>`${_.toLowerCase()}:${l[_].trim()}`).sort().join(`
|
|
40
|
-
`)+`
|
|
41
|
-
`,m=await this.sha256(e),f=[p,h,c,u,d,m].join(`
|
|
42
|
-
`),b="AWS4-HMAC-SHA256",y=`${i}/${r.region}/${r.service}/aws4_request`,C=await this.sha256(f),k=[b,o,y,C].join(`
|
|
43
|
-
`),O=await this.getSignatureKey(r.secretAccessKey,i,r.region,r.service),w=await this.hmacHex(O,k),S=`${b} Credential=${r.accessKeyId}/${y}, SignedHeaders=${d}, Signature=${w}`;return{...l,Authorization:S}}async sha256(t){let r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}async hmac(t,e){let r=new TextEncoder,s=t instanceof Uint8Array?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,n=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",n,r.encode(e))}async hmacHex(t,e){let r=await this.hmac(t,e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}async getSignatureKey(t,e,r,s){let n=new TextEncoder,o=await this.hmac(n.encode(`AWS4${t}`),e),i=await this.hmac(o,r),l=await this.hmac(i,s);return this.hmac(l,"aws4_request")}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let s=e.message??"Unknown API error",n=e.__type??"";switch(t){case 401:case 403:throw a(s,"API_KEY_INVALID",{provider:"bedrock",model:r,retryable:!1});case 429:throw a(s,"RATE_LIMITED",{provider:"bedrock",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n.includes("ValidationException")&&s.includes("token")?a(s,"CONTEXT_LENGTH_EXCEEDED",{provider:"bedrock",model:r,retryable:!1}):a(s,"UNKNOWN",{provider:"bedrock",model:r,retryable:!1});case 500:case 502:case 503:throw a(s,"PROVIDER_UNAVAILABLE",{provider:"bedrock",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(s,"UNKNOWN",{provider:"bedrock",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"bedrock",retryable:!0}):o}finally{clearTimeout(n)}}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var Be={primary:"claude",fallbacks:["openai","ollama"],loadBalancing:"round-robin",providers:{},global:{enableCostTracking:!0,enableMetrics:!0}},Z=class{providers=new Map;circuitBreakers;cache;costTracker;config;metrics=new Map;roundRobinIndex=0;initialized=!1;spendLedger;injectedLedger;maxCostPerRun;billingNoticeShown=!1;constructor(t={},e){this.config={...Be,...t},this.circuitBreakers=new K(e?.circuitBreakerConfig),this.cache=new q(e?.cacheConfig),this.costTracker=e?.costTracker??ue(),this.injectedLedger=e?.spendLedger;let r=Number.parseFloat(process.env.AQE_MAX_BUDGET_USD??"");this.maxCostPerRun=this.config.global?.maxCostPerRun??(Number.isFinite(r)&&r>0?r:void 0)}async initialize(){if(!this.initialized){await this.createProviders();for(let t of this.providers.keys())this.initializeMetrics(t);this.budgetConfigured()&&(this.spendLedger=this.injectedLedger??await fe().catch(()=>new N)),this.emitBillingNotice(),this.initialized=!0}}budgetConfigured(){let t=this.config.global;return!!(this.maxCostPerRun||t?.maxCostPerHour&&t.maxCostPerHour>0||t?.maxCostPerDay&&t.maxCostPerDay>0)}emitBillingNotice(){if(this.billingNoticeShown||(process.env.AQE_LLM_NO_BILLING_NOTICE??"")==="1")return;let t=this.providers.get(this.config.primary);if(!t)return;let e=de(t),r=pe(t.type,e);r&&console.error(r),this.billingNoticeShown=!0}enforceBudget(t,e){if(!this.budgetConfigured()||!this.spendLedger)return;let r=e?.model??this.providers.get(this.config.primary)?.getConfig().model??this.config.primary,s=typeof t=="string"?t:JSON.stringify(t),n=Math.ceil(s.length/4),o=e?.maxTokens??4096,i=this.costTracker.estimateCost(r,n,o).totalCost;if(i===0)return;let l=this.config.global,p=[{limit:this.maxCostPerRun,spent:this.costTracker.getCurrentCost("all"),label:"per-run"},{limit:l?.maxCostPerHour,spent:this.spendLedger.spentSince(36e5),label:"hourly"},{limit:l?.maxCostPerDay,spent:this.spendLedger.spentSince(864e5),label:"daily"}];for(let{limit:h,spent:c,label:d}of p)if(h&&h>0&&c+i>h)throw a(`LLM ${d} budget exceeded: $${c.toFixed(4)} spent + $${i.toFixed(4)} estimated > $${h.toFixed(2)} cap. Raise --max-budget-usd / maxCost* or switch to a local/subscription provider.`,"COST_LIMIT_EXCEEDED",{retryable:!1})}recordSpend(t){this.spendLedger&&this.spendLedger.record({provider:t.provider,model:t.model,costUsd:t.cost.totalCost,costSource:t.cost.source??"local-estimate",promptTokens:t.usage.promptTokens,completionTokens:t.usage.completionTokens,requestId:t.requestId})}assertWithinBudget(t,e){this.enforceBudget(t,e)}recordResponseSpend(t){this.recordSpend(t)}async generate(t,e){if(await this.ensureInitialized(),!e?.skipCache){let s=typeof t=="string"?t:JSON.stringify(t),n=this.cache.getGeneration(s,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens,systemPrompt:e?.systemPrompt});if(n)return{...n,cached:!0}}this.enforceBudget(t,e);let r=await this.executeWithFailover("generate",async s=>s.generate(t,e),e?.preferredProvider);if(!e?.skipCache){let s=typeof t=="string"?t:JSON.stringify(t);this.cache.setGeneration(s,r,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens,systemPrompt:e?.systemPrompt})}return this.costTracker.recordUsage(r.provider,r.model,r.usage,r.requestId),this.recordSpend(r),r}async embed(t,e){if(await this.ensureInitialized(),!e?.skipCache){let n=this.cache.getEmbedding(t,{model:e?.model});if(n)return{...n,cached:!0}}let r=["openai","ollama","cognitum"],s=await this.executeWithFailover("embed",async n=>n.embed(t,e),r.find(n=>this.providers.has(n)));return e?.skipCache||this.cache.setEmbedding(t,s,{model:e?.model}),s}async complete(t,e){if(await this.ensureInitialized(),!e?.skipCache){let s=this.cache.getCompletion(t,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});if(s)return{...s,cached:!0}}this.enforceBudget(t,e);let r=await this.executeWithFailover("complete",async s=>s.complete(t,e));return e?.skipCache||this.cache.setCompletion(t,r,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens}),this.costTracker.recordUsage(r.provider,r.model,r.usage,`complete-${r.model}-${Date.now()}`),this.recordSpend({content:r.completion,model:r.model,provider:r.provider,usage:r.usage,cost:R.calculateCost(r.model,r.usage),latencyMs:r.latencyMs,finishReason:"stop",cached:r.cached,requestId:`complete-${r.model}-${Date.now()}`}),r}async healthCheck(){await this.ensureInitialized();let t={};for(let[e,r]of this.providers)t[e]=await r.healthCheck();return t}getProvider(t){return this.providers.get(t)}getAvailableProviders(){let t=[];for(let[e,r]of this.providers)this.circuitBreakers.getBreaker(e).canExecute()&&t.push(e);return t}getMetrics(){let t={};for(let[e,r]of this.metrics){let s=this.circuitBreakers.getBreaker(e),n=r.latencies.slice(-100);t[e]={provider:e,totalRequests:r.totalRequests,successCount:r.successCount,failureCount:r.failureCount,avgLatencyMs:this.calculateAverage(n),p95LatencyMs:this.calculatePercentile(n,95),p99LatencyMs:this.calculatePercentile(n,99),totalCost:r.totalCost,totalTokens:r.totalTokens,circuitState:s.getState()}}return t}getCacheStats(){return this.cache.getStats()}getCostSummary(t="day"){return this.costTracker.getSummary(t)}clearCache(){this.cache.clear()}resetCircuitBreakers(){this.circuitBreakers.resetAll()}async dispose(){for(let t of this.providers.values())await t.dispose();this.providers.clear(),this.metrics.clear(),this.cache.clear(),this.initialized=!1}async createProviders(){let t=new Set([this.config.primary,...this.config.fallbacks]);for(let e of t)try{let r=this.createProvider(e);this.providers.set(e,r)}catch(r){console.warn(`Failed to create ${e} provider: ${r instanceof Error?r.message:"Unknown"}`)}if(this.providers.size===0)throw a("No LLM providers could be initialized","PROVIDER_UNAVAILABLE",{retryable:!1})}createProvider(t){switch(t){case"claude":return new $(this.config.providers.claude);case"claude-code":return new F(this.config.providers["claude-code"]);case"cognitum":return new W(this.config.providers.cognitum);case"openai":return new z(this.config.providers.openai);case"ollama":return new j(this.config.providers.ollama);case"openrouter":return new V(this.config.providers.openrouter);case"gemini":return new J(this.config.providers.gemini);case"azure-openai":{let e=this.config.providers["azure-openai"];if(!e)throw new Error("Azure OpenAI provider requires configuration with deploymentId");return new X(e)}case"bedrock":return new Q(this.config.providers.bedrock);default:throw new Error(`Unknown provider type: ${t}`)}}initializeMetrics(t){this.metrics.set(t,{totalRequests:0,successCount:0,failureCount:0,latencies:[],totalCost:0,totalTokens:0})}async executeWithFailover(t,e,r){let s=this.selectProvider(r),n=new Set,o,i=[s.provider.type,...this.config.fallbacks.filter(l=>l!==s.provider.type)];for(let l of i){if(n.has(l))continue;n.add(l);let p=this.providers.get(l);if(!p)continue;let h=this.circuitBreakers.getBreaker(l);if(h.canExecute())try{let c=Date.now(),d=await h.execute(()=>e(p)),u=Date.now()-c;return this.recordSuccess(l,u,d),d}catch(c){if(o=E(c),this.recordFailure(l,o),"retryable"in o&&!o.retryable)throw o}}throw a(`All providers failed for ${t}: ${o?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:o})}selectProvider(t){if(t){let r=this.providers.get(t),s=this.circuitBreakers.getBreaker(t);if(r&&s.canExecute())return{provider:r,reason:"primary"}}let e=this.getAvailableProviders();if(e.length===0){let r=this.providers.get(this.config.primary);if(r)return{provider:r,reason:"fallback"};throw a("No providers available","PROVIDER_UNAVAILABLE",{retryable:!1})}switch(this.config.loadBalancing){case"round-robin":return this.selectRoundRobin(e);case"least-cost":return this.selectLeastCost(e);case"least-latency":return this.selectLeastLatency(e);case"random":return this.selectRandom(e);default:return this.selectRoundRobin(e)}}selectRoundRobin(t){this.roundRobinIndex=(this.roundRobinIndex+1)%t.length;let e=t[this.roundRobinIndex];return{provider:this.providers.get(e),reason:"load-balance"}}selectLeastCost(t){let e=1/0,r=t[0];for(let s of t){let n=this.providers.get(s),{input:o,output:i}=n.getCostPerToken(),l=o+i;l<e&&(e=l,r=s)}return{provider:this.providers.get(r),reason:"cost-optimization",metadata:{estimatedCost:e}}}selectLeastLatency(t){let e=1/0,r=t[0];for(let s of t){let n=this.metrics.get(s);if(n&&n.latencies.length>0){let o=this.calculateAverage(n.latencies);o<e&&(e=o,r=s)}}return{provider:this.providers.get(r),reason:"latency-optimization",metadata:{avgLatency:e}}}selectRandom(t){let e=le(0,t.length),r=t[e];return{provider:this.providers.get(r),reason:"load-balance"}}recordSuccess(t,e,r){let s=this.metrics.get(t);if(s&&(s.totalRequests++,s.successCount++,s.latencies.push(e),s.latencies.length>1e3&&(s.latencies=s.latencies.slice(-1e3)),r&&typeof r=="object")){let n=r;n.cost?.totalCost&&(s.totalCost+=n.cost.totalCost),n.usage?.totalTokens&&(s.totalTokens+=n.usage.totalTokens)}}recordFailure(t,e){let r=this.metrics.get(t);r&&(r.totalRequests++,r.failureCount++)}async ensureInitialized(){this.initialized||await this.initialize()}calculateAverage(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}calculatePercentile(t,e){if(t.length===0)return 0;let r=[...t].sort((n,o)=>n-o),s=Math.ceil(e/100*r.length)-1;return r[Math.max(0,s)]}};function Fo(g){return new Z(g)}function Wo(){return new Z({primary:"claude",fallbacks:["openai","ollama"],loadBalancing:"least-cost",providers:{claude:{model:"claude-sonnet-4-6",maxTokens:8192,temperature:.3},openai:{model:"gpt-4o",maxTokens:8192,temperature:.3},ollama:{model:"llama3.1",maxTokens:4096,temperature:.3}},global:{enableCostTracking:!0,enableMetrics:!0,maxCostPerDay:100}})}export{F as a,j as b,Be as c,Z as d,Fo as e,Wo as f};
|