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
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
2
|
-
import{a as q}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
|
|
2
|
+
import{a as q}from"./chunk-FQY3UTGA.js";import{c as V,d as W}from"./chunk-GJMZR7WU.js";import{c as x}from"./chunk-CFVEDUTW.js";import{a as G}from"./chunk-HVB2L52I.js";import{c as R}from"./chunk-OXXMVQDF.js";import{b as E,d as $}from"./chunk-2DIT5AUU.js";import{a as C,c as H}from"./chunk-CYL2FV23.js";import{i as v}from"./chunk-E3B5XTXJ.js";import{a as M,b as U,d as ee}from"./chunk-RDU4WTV2.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
|
|
3
3
|
INSERT INTO concept_nodes
|
|
4
4
|
(id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -63,7 +63,7 @@ import{a as q}from"./chunk-GMFFMJD6.js";import{c as V,d as W}from"./chunk-LNIHLN
|
|
|
63
63
|
ORDER BY weight DESC
|
|
64
64
|
LIMIT -1 OFFSET ?
|
|
65
65
|
)
|
|
66
|
-
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-KJSP7KR6.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
|
|
66
|
+
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-N3UHMSZ3.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
|
|
67
67
|
FROM qe_pattern_nulls n
|
|
68
68
|
JOIN qe_patterns p ON p.id = n.pattern_id
|
|
69
69
|
ORDER BY n.updated_at DESC
|
|
@@ -89,7 +89,7 @@ import{a as q}from"./chunk-GMFFMJD6.js";import{c as V,d as W}from"./chunk-LNIHLN
|
|
|
89
89
|
WHERE confidence >= 0.3 AND success_rate < 0.7
|
|
90
90
|
ORDER BY usage_count DESC
|
|
91
91
|
LIMIT 40
|
|
92
|
-
)`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-
|
|
92
|
+
)`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-O3SPSWBA.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-S2R2PCBS.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-MKSLKWDI.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
|
|
93
93
|
UPDATE dream_insights
|
|
94
94
|
SET applied = 1, pattern_id = ?
|
|
95
95
|
WHERE id = ?
|
|
@@ -117,4 +117,4 @@ import{a as q}from"./chunk-GMFFMJD6.js";import{c as V,d as W}from"./chunk-LNIHLN
|
|
|
117
117
|
(id, cycle_id, insight_type, source_concepts, description, novelty_score,
|
|
118
118
|
confidence_score, actionable, applied, suggested_action, pattern_id)
|
|
119
119
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
120
|
-
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-KJSP7KR6.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-2PMFAQMN.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-2PMFAQMN.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-B6P732AV.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
|
|
120
|
+
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-N3UHMSZ3.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-3CJHRNX6.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-3CJHRNX6.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-MKSLKWDI.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
|
|
@@ -1,3 +1,3 @@
|
|
|
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.
|
|
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.13.0");process.exit(0)}
|
|
2
2
|
import a from"chalk";import{existsSync as m,statSync as S}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}defaultValue;description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var V=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
|
|
3
3
|
Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,V as j};
|
|
@@ -0,0 +1,54 @@
|
|
|
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.13.0");process.exit(0)}
|
|
2
|
+
import{b as v}from"./chunk-5EIOQCGN.js";import{a as he,c as ge}from"./chunk-OETDMOOE.js";import{a as se,b as Me}from"./chunk-IPHLXAMX.js";import{a}from"./chunk-6SXKCIN5.js";import{d as fe}from"./chunk-IHQTXJAQ.js";import{b as R,c as me}from"./chunk-FBBZHATF.js";import{b as K,d as de}from"./chunk-2DIT5AUU.js";import{b as E,c as L}from"./chunk-CYL2FV23.js";import{b as pe,d as we}from"./chunk-RDU4WTV2.js";we();L();var ye={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},ne=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={...ye,...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)}}},q=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...ye,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new ne(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 be={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={...be,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s<<5)-s+l,s=s&s}return`${t}:${Math.abs(s).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 o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),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 o of this.cache.values())r+=this.estimateSize(o.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,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.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}},B=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...be,...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,o){if(!this.config.cacheGenerations)return;let n=M.generateKey("generation",t,r);this.generationCache.set(n,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=M.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let n=M.generateKey("embedding",t,r);this.embeddingCache.set(n,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=M.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let n=M.generateKey("completion",t,r);this.completionCache.set(n,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,s=o+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:n,hitRate:s>0?o/s: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 ie="(unattributed)",Ae=`
|
|
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
|
+
`,ae=class{db;hasAgentColumn=!1;constructor(t){this.db=t,this.db.exec(Ae);try{this.db.prepare("PRAGMA table_info(llm_spend)").all().some(r=>r.name==="agent_type")||this.db.exec("ALTER TABLE llm_spend ADD COLUMN agent_type TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_llm_spend_agent ON llm_spend(agent_type)"),this.hasAgentColumn=!0}catch{}}record(t){try{this.hasAgentColumn?this.db.prepare(`INSERT INTO llm_spend
|
|
16
|
+
(ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id, agent_type)
|
|
17
|
+
VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id, @agent_type)`).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,agent_type:t.agent??null}):this.db.prepare(`INSERT INTO llm_spend
|
|
18
|
+
(ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id)
|
|
19
|
+
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}}spentByAgentSince(t,e=Date.now()){try{let r=this.db.prepare(`SELECT COALESCE(agent_type, ?) AS agent, COALESCE(SUM(cost_usd), 0) AS total
|
|
20
|
+
FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ie,e-t,ie),o={};for(let n of r)o[n.agent]=n.total;return o}catch{return{}}}},N=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ie})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let n of this.entries)n.ts>=r&&(o+=n.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o={};for(let n of this.entries)n.ts>=r&&(o[n.agent]=(o[n.agent]??0)+n.costUsd);return o}};async function ve(){try{let t=(await import("./unified-memory-WNYWTGVX.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new ae(t.getDatabase())}catch{return new N}}L();function ce(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*o;return o+n}var Le=1e3,Pe=3e4;function T(g,t=Le,e=Pe){return ce(g,t,e,0)}import{readFileSync as Oe}from"fs";import*as Te from"path";var le=["low","medium","high","xhigh","max"],Ie="xhigh";function G(g){return typeof g=="string"&&le.includes(g)}var $;function Se(g){try{let e=Oe(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&G(e[1])?e[1]:null}catch{return null}}function ke(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??Te.join(process.cwd(),"config","fleet-defaults.yaml");return $===void 0&&($=Se(r)),$||Ie}function Ee(g,t){let e=le.indexOf(g),r=le.indexOf(t);return e>r?t:g}var xe={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},F=class{type="claude";name="Anthropic Claude";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 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),o=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:o,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 o=this.formatMessages(t),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.systemPrompt&&(m.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(m.stop_sequences=e.stopSequences);try{if(fe(n).supportsEffortXHigh){let u=ke({override:e?.effort}),d=Ee(u,"xhigh");m.thinking={type:"adaptive",effort:d}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let d=await c.json(),h=d.usage.cache_creation_input_tokens??0,f=d.usage.cache_read_input_tokens??0,b={promptTokens:d.usage.input_tokens,completionTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+h+f+d.usage.output_tokens,cacheCreationTokens:h,cacheReadTokens:f},y=R.calculateCost(n,b);return v.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+d.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:d.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:d.model,provider:"claude",usage:b,cost:y,latencyMs:u,finishReason:this.mapFinishReason(d.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??[`
|
|
21
|
+
|
|
22
|
+
`,"```"]});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 o="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(o,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n==="invalid_request_error"&&o.includes("context")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)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)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};import{spawn as Ue}from"node:child_process";var Ne=["ANTHROPIC_API_KEY","CLAUDE_API_KEY","ANTHROPIC_AUTH_TOKEN"],De={model:"sonnet",maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:1,binaryPath:"claude",maxConcurrency:2,disallowedTools:["Bash","Edit","Write","NotebookEdit","WebFetch","WebSearch","Task"]},W=class g{type="claude-code";name="Claude Code (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...De,...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),o=`claude-code-${++this.requestId}-${Date.now()}`,{prompt:n,systemPrompt:s}=this.flatten(t,e?.systemPrompt),i=["-p","--output-format","json","--model",r];s&&i.push("--append-system-prompt",s);let l=this.config.disallowedTools??[];l.length>0&&i.push("--disallowedTools",...l);let p=Date.now(),m=e?.timeoutMs??this.config.timeoutMs??12e4,{code:c,stdout:u,stderr:d}=await this.withConcurrency(()=>this.runProcess(i,n,m)),h=Date.now()-p;if(c!==0&&!u.trim())throw this.classifyError(d||`claude exited with code ${c}`,r);let f;try{f=JSON.parse(u)}catch{throw a(`Could not parse claude -p JSON output: ${u.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 v.recordTokenUsage(o,"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:h,finishReason:this.mapFinishReason(f.stop_reason),cached:!1,requestId:o}}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(`
|
|
23
|
+
|
|
24
|
+
`),systemPrompt:r.length>0?r.join(`
|
|
25
|
+
|
|
26
|
+
`):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 Ne)delete e[r];return e}runProcess(t,e,r){return new Promise((o,n)=>{let s=Ue(this.config.binaryPath??"claude",t,{env:g.childEnv(),stdio:["pipe","pipe","pipe"]}),i="",l="",p=!1,m=setTimeout(()=>{p||(p=!0,s.kill("SIGKILL"),n(a("claude -p timed out","TIMEOUT",{provider:"claude-code",retryable:!0})))},r);s.stdout.on("data",c=>i+=c.toString()),s.stderr.on("data",c=>l+=c.toString()),s.on("error",c=>{p||(p=!0,clearTimeout(m),n(a(`Failed to spawn claude: ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",retryable:!1,cause:c})))}),s.on("close",c=>{p||(p=!0,clearTimeout(m),o({code:c??0,stdout:i,stderr:l}))}),s.stdin.on("error",()=>{});try{e!==void 0&&s.stdin.write(e),s.stdin.end()}catch{}})}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()}}};import{spawn as Ke}from"node:child_process";import{mkdtempSync as qe,readFileSync as Be,rmSync as $e}from"node:fs";import{tmpdir as Ge}from"node:os";import{join as Ce}from"node:path";var Fe=["OPENAI_API_KEY","CODEX_API_KEY"],D="default",We={model:D,maxTokens:4096,temperature:.7,timeoutMs:18e4,maxRetries:1,binaryPath:"codex",maxConcurrency:2},z=class g{type="codex";name="Codex CLI (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...We,...t};let e=Number.parseInt(process.env.AQE_CODEX_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,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:`Codex CLI ("${this.config.binaryPath}") not found or not runnable. Install Codex and log in with your ChatGPT account (\`codex login\`).`}}async generate(t,e){let r=e?.model??this.config.model??D,o=`codex-${++this.requestId}-${Date.now()}`,{prompt:n}=this.flatten(t,e?.systemPrompt),s=qe(Ce(Ge(),"aqe-codex-")),i=Ce(s,"last-message.txt"),l=["exec","--skip-git-repo-check","--sandbox","read-only","-o",i];r&&r!==D&&l.push("-m",r);let p=Date.now(),m=e?.timeoutMs??this.config.timeoutMs??18e4;try{let{code:c,stderr:u}=await this.withConcurrency(()=>this.runProcess(l,n,void 0,m)),d=Date.now()-p,h="";try{h=Be(i,"utf8").trim()}catch{h=""}if(c!==0&&!h)throw this.classifyError(u||`codex exited with code ${c}`,r);let f=Math.ceil(n.length/4),b=Math.ceil(h.length/4),y={promptTokens:f,completionTokens:b,totalTokens:f+b,cacheCreationTokens:0,cacheReadTokens:0};return v.recordTokenUsage(o,"codex-provider","llm","generate",{inputTokens:y.promptTokens,outputTokens:y.completionTokens,totalTokens:y.totalTokens,estimatedCostUsd:0}),{content:h,model:r===D?"codex-default":r,provider:"codex",usage:y,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"provider-receipt"},latencyMs:d,finishReason:"stop",cached:!1,requestId:o}}finally{$e(s,{recursive:!0,force:!0})}}async embed(t,e){throw a("Codex provider does not support embeddings. Use openai, ollama, or cognitum.","MODEL_NOT_FOUND",{provider:"codex",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:"codex",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return[D,"gpt-5-codex","o3","o4-mini"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}flatten(t,e){if(typeof t=="string")return{prompt:e?`${e}
|
|
27
|
+
|
|
28
|
+
${t}`:t};let r=t.filter(s=>s.role==="system").map(s=>s.content);e&&r.unshift(e);let o=t.filter(s=>s.role!=="system").map(s=>`${s.role==="assistant"?"Assistant":"User"}: ${s.content}`).join(`
|
|
29
|
+
|
|
30
|
+
`);return{prompt:`${r.length>0?`${r.join(`
|
|
31
|
+
|
|
32
|
+
`)}
|
|
33
|
+
|
|
34
|
+
`:""}${o}`}}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:"codex",model:e,retryable:!0,retryAfterMs:6e4}):a(t,"PROVIDER_UNAVAILABLE",{provider:"codex",model:e,retryable:!0})}static childEnv(t=process.env){let e={...t};for(let r of Fe)delete e[r];return e}runProcess(t,e,r,o){return new Promise((n,s)=>{let i=Ke(this.config.binaryPath??"codex",t,{env:g.childEnv(),stdio:["pipe","pipe","pipe"]}),l="",p="",m=!1,c=setTimeout(()=>{m||(m=!0,i.kill("SIGKILL"),s(a("codex exec timed out","TIMEOUT",{provider:"codex",retryable:!0})))},o);i.stdout.on("data",u=>l+=u.toString()),i.stderr.on("data",u=>p+=u.toString()),i.on("error",u=>{m||(m=!0,clearTimeout(c),s(a(`Failed to spawn codex: ${u.message}`,"PROVIDER_UNAVAILABLE",{provider:"codex",retryable:!1,cause:u})))}),i.on("close",u=>{m||(m=!0,clearTimeout(c),n({code:u??0,stdout:l,stderr:p}))}),i.stdin.on("error",()=>{});try{e!==void 0&&i.stdin.write(e),i.stdin.end()}catch{}})}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 ze={model:"cognitum-auto",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0},j=class{type="cognitum";name="Cognitum";billingMode="metered-capped";config;requestId=0;constructor(t={}){this.config={...ze,...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),o=Date.now()-e;return r.ok?{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{billing:"metered-capped",baseUrl:this.getBaseUrl()}}:{healthy:!1,latencyMs:o,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 o=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`cognitum-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.stopSequences?.length&&(m.stop=e.stopSequences);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok)throw await this.toApiError(c,n);let d=await c.json(),h=d.x_cognitum,f={promptTokens:d.usage.prompt_tokens,completionTokens:d.usage.completion_tokens,totalTokens:d.usage.total_tokens,cacheReadTokens:d.usage.cache_read_tokens??0},b=this.receiptCost(h);return v.recordTokenUsage(l,"cognitum-provider","llm","generate",{inputTokens:f.promptTokens,outputTokens:f.completionTokens,totalTokens:f.totalTokens,estimatedCostUsd:b.totalCost}),{content:d.choices[0]?.message?.content??"",model:h?.resolved_model??d.model,provider:"cognitum",usage:f,cost:b,latencyMs:u,finishReason:this.mapFinishReason(d.choices[0]?.finish_reason),cached:h?.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 o=e?.model??"cognitum-embed",n=Date.now();try{let s=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:o,input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!s.ok)throw await this.toApiError(s,o);let l=await s.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(s){throw s instanceof Error&&"code"in s?s:a(s instanceof Error?s.message:"Embedding request failed","NETWORK_ERROR",{provider:"cognitum",model:o,retryable:!0,cause:s})}}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 o=t.some(n=>n.role==="system");e&&!o&&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(()=>""),o=r;try{o=JSON.parse(r).error??r}catch{}switch(t.status){case 401:case 403:return a(o||"Unauthorized","API_KEY_INVALID",{provider:"cognitum",model:e,retryable:!1});case 402:return a(o||"Budget cap reached","COST_LIMIT_EXCEEDED",{provider:"cognitum",model:e,retryable:!1});case 429:return a(o||"Rate limited","RATE_LIMITED",{provider:"cognitum",model:e,retryable:!0,retryAfterMs:6e4});case 500:case 502:case 503:return a(o||"Provider unavailable","PROVIDER_UNAVAILABLE",{provider:"cognitum",model:e,retryable:!0,retryAfterMs:5e3});default:return a(o||`HTTP ${t.status}`,"UNKNOWN",{provider:"cognitum",model:e,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"cognitum",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)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)&&s<o-1){await this.sleep(T(s));continue}return i}catch(i){n=E(i),s<o-1&&await this.sleep(T(s))}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var je={model:"gpt-4o",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0},H=class{type="openai";name="OpenAI";config;requestId=0;constructor(t={}){this.config={...je,...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),o=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:o,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 o=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`openai-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.stopSequences&&e.stopSequences.length>0&&(m.stop=e.stopSequences),this.config.presencePenalty!==void 0&&(m.presence_penalty=this.config.presencePenalty),this.config.frequencyPenalty!==void 0&&(m.frequency_penalty=this.config.frequencyPenalty);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=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 d=await c.json(),h={promptTokens:d.usage.prompt_tokens,completionTokens:d.usage.completion_tokens,totalTokens:d.usage.total_tokens},f=R.calculateCost(n,h);return v.recordTokenUsage(l,"openai-provider","llm","generate",{inputTokens:d.usage.prompt_tokens,outputTokens:d.usage.completion_tokens,totalTokens:d.usage.total_tokens,estimatedCostUsd:f.totalCost}),{content:d.choices[0]?.message?.content??"",model:d.model,provider:"openai",usage:h,cost:f,latencyMs:u,finishReason:this.mapFinishReason(d.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 o=e?.model??"text-embedding-3-small",n=Date.now();try{let s=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:o,input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!s.ok){let p=await s.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(s.status,p,o)}let l=await s.json();return{embedding:l.data[0].embedding,model:l.model,provider:"openai",tokenCount:l.usage.total_tokens,latencyMs:i,cached:!1}}catch(s){throw s instanceof Error&&"code"in s?s:a(s instanceof Error?s.message:"Embedding request failed","NETWORK_ERROR",{provider:"openai",model:o,retryable:!0,cause:s})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
35
|
+
|
|
36
|
+
`]});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 o=t.some(n=>n.role==="system");e&&!o&&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 o=e.error?.message??"Unknown API error",n=e.error?.type??"",s=e.error?.code??"";switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"openai",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"openai",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw s==="context_length_exceeded"||n==="invalid_request_error"?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"openai",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"openai",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"openai",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"openai",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"openai",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)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)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};Me();var U={DEFAULT_TOK_PER_SEC:15,SAFETY_FACTOR:2.5,LOAD_OVERHEAD_MS:15e3,FLOOR_MS:3e4,CEIL_MS:6e5};function Re(g,t=U.DEFAULT_TOK_PER_SEC){let e=t>0?t:U.DEFAULT_TOK_PER_SEC,o=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(o)))}var _e={model:"llama3.1",baseUrl:se("http://localhost:11434"),maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:2,contextLength:4096,keepAlive:"5m",enableCache:!0,enableCircuitBreaker:!0},V=class{type="ollama";name="Ollama (Local)";config;requestId=0;availableModels=[];observedTokPerSec=new Map;constructor(t={}){this.config={..._e,...t}}timeoutFor(t,e){let r=this.config.timeoutMs;return r&&r!==_e.timeoutMs?r:Re(e,this.observedTokPerSec.get(t))}recordThroughput(t,e,r){if(!e||!r||r<=0)return;let o=e/(r/1e9);if(!Number.isFinite(o)||o<=0)return;let n=this.observedTokPerSec.get(t);this.observedTokPerSec.set(t,n?n*.5+o*.5:o)}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 o=await e.json();return this.availableModels=o.models?.map(s=>s.name.split(":")[0])??[],!this.availableModels.some(s=>s===this.config.model||s.startsWith(this.config.model)||this.config.model.startsWith(s))&&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,o=e?.maxTokens??this.config.maxTokens??4096,n=e?.temperature??this.config.temperature??.7,s=`ollama-${++this.requestId}-${Date.now()}`,i=Date.now(),l=Array.isArray(t);try{let p,m,c,u;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:o,stop:e?.stopSequences}})},e?.timeoutMs??this.timeoutFor(r,o)),!p.ok)throw await this.handleApiError(p,r);let y=await p.json();m=y.message.content,this.recordThroughput(r,y.eval_count,y.eval_duration),c=y.prompt_eval_count??this.estimateTokens(JSON.stringify(b)),u=y.eval_count??this.estimateTokens(m)}else{let b=e?.systemPrompt?`${e.systemPrompt}
|
|
37
|
+
|
|
38
|
+
${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:o,stop:e?.stopSequences}})},e?.timeoutMs??this.timeoutFor(r,o)),!p.ok)throw await this.handleApiError(p,r);let y=await p.json();m=y.response,this.recordThroughput(r,y.eval_count,y.eval_duration),c=y.prompt_eval_count??this.estimateTokens(b),u=y.eval_count??this.estimateTokens(m)}let d=Date.now()-i,h={promptTokens:c,completionTokens:u,totalTokens:c+u},f=R.calculateCost(r,h);return v.recordTokenUsage(s,"ollama-provider","llm","generate",{inputTokens:c,outputTokens:u,totalTokens:c+u,estimatedCostUsd:f.totalCost}),{content:m,model:r,provider:"ollama",usage:h,cost:f,latencyMs:d,finishReason:"stop",cached:!1,requestId:s}}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",o=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),s=Date.now()-o;if(!n.ok)throw await this.handleApiError(n,r);return{embedding:(await n.json()).embedding,model:r,provider:"ollama",tokenCount:this.estimateTokens(t),latencyMs:s,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(),o=await this.generate(t,{model:r,temperature:e?.temperature??.1,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
39
|
+
|
|
40
|
+
`,"```","// ","# "]});return{completion:o.content,model:o.model,provider:"ollama",usage:o.usage,latencyMs:o.latencyMs,cached:o.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??se()).replace(/\/$/,"")}formatMessages(t,e){let r=[];e&&r.push({role:"system",content:e});for(let o of t)r.push({role:o.role,content:o.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 o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"ollama",retryable:!0}):s}finally{clearTimeout(n)}}};L();de();var He={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},Y={"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}},J=class{type="openrouter";name="OpenRouter";config;requestId=0;cachedModels=null;constructor(t={}){this.config={...He,...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),o=Date.now()-e;if(!r.ok){let i=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${i}`}}let s=(await r.json()).data?.map(i=>i.id)||[];return this.cachedModels=s,{healthy:!0,latencyMs:o,models:s.slice(0,20),details:{totalModels:s.length,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("OpenRouter API key not configured","API_KEY_MISSING",{provider:"openrouter",retryable:!1});let o=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`openrouter-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.stopSequences&&e.stopSequences.length>0&&(m.stop=e.stopSequences),this.config.allowFallback!==void 0&&(m.route=this.config.allowFallback?"fallback":void 0),this.config.forceProvider&&(m.provider={order:[this.config.forceProvider]});try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=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 d=await c.json(),h={promptTokens:d.usage?.prompt_tokens??0,completionTokens:d.usage?.completion_tokens??0,totalTokens:d.usage?.total_tokens??0},f=this.calculateCost(n,h);return v.recordTokenUsage(l,"openrouter-provider","llm","generate",{inputTokens:h.promptTokens,outputTokens:h.completionTokens,totalTokens:h.totalTokens,estimatedCostUsd:f.totalCost}),{content:d.choices[0]?.message?.content??"",model:d.model,provider:"openrouter",usage:h,cost:f,latencyMs:u,finishReason:this.mapFinishReason(d.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 o=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`openrouter-stream-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o,stream:!0};e?.stopSequences&&e.stopSequences.length>0&&(m.stop=e.stopSequences);let c=await this.fetchWithTimeout(`${this.getBaseUrl()}/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4);if(!c.ok){let w=await c.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(c.status,w,n)}if(!c.body)throw a("No response body for streaming","NETWORK_ERROR",{provider:"openrouter",model:n,retryable:!0});let u="",d="stop",h=n,f=c.body.getReader(),b=new TextDecoder,y="";try{for(;;){let{done:w,value:re}=await f.read();if(w)break;y+=b.decode(re,{stream:!0});let x=y.split(`
|
|
41
|
+
`);y=x.pop()||"";for(let A of x){let P=A.trim();if(!(!P||P==="data: [DONE]")&&P.startsWith("data: "))try{let I=K(P.slice(6)),oe=I.choices[0]?.delta;oe?.content&&(u+=oe.content,yield oe.content),I.choices[0]?.finish_reason&&(d=this.mapFinishReason(I.choices[0].finish_reason)),I.model&&(h=I.model)}catch{}}}}finally{f.releaseLock()}let C=Date.now()-p,k=Math.ceil(JSON.stringify(o).length/4),O=Math.ceil(u.length/4),_={promptTokens:k,completionTokens:O,totalTokens:k+O},S=this.calculateCost(n,_);return v.recordTokenUsage(l,"openrouter-provider","llm","generate-stream",{inputTokens:_.promptTokens,outputTokens:_.completionTokens,totalTokens:_.totalTokens,estimatedCostUsd:S.totalCost}),{content:u,model:h,provider:"openrouter",usage:_,cost:S,latencyMs:C,finishReason:d,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 o=e?.model??"openai/text-embedding-3-small",n=Date.now();try{let s=await this.fetchWithTimeout(`${this.getBaseUrl()}/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:o,input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!s.ok){let p=await s.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(s.status,p,o)}let l=await s.json();return{embedding:l.data[0].embedding,model:l.model,provider:"openrouter",tokenCount:l.usage.total_tokens,latencyMs:i,cached:!1}}catch(s){throw s instanceof Error&&"code"in s?s:a(s instanceof Error?s.message:"Embedding request failed","NETWORK_ERROR",{provider:"openrouter",model:o,retryable:!0,cause:s})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
42
|
+
|
|
43
|
+
`]});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=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,o=e.promptTokens/1e6*r.input,n=e.completionTokens/1e6*r.output;return{inputCost:o,outputCost:n,totalCost:o+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 o=t.some(n=>n.role==="system");e&&!o&&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 o=e.error?.message??"Unknown API error",n=e.error?.type??"",s=e.error?.code;switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"openrouter",model:r,retryable:!1});case 402:throw a(o,"COST_LIMIT_EXCEEDED",{provider:"openrouter",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"openrouter",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw s==="context_length_exceeded"||n==="invalid_request_error"?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"openrouter",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"openrouter",model:r,retryable:!1});case 404:throw a(o,"MODEL_NOT_FOUND",{provider:"openrouter",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"openrouter",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"openrouter",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"openrouter",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)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)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();de();var Ve={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"},X={"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}},Q=class{type="gemini";name="Google Gemini";config;requestId=0;cachedModels=null;constructor(t={}){this.config={...Ve,...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),o=Date.now()-e;if(!r.ok){let i=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${i}`}}let s=(await r.json()).models?.filter(i=>i.supportedGenerationMethods?.includes("generateContent")).map(i=>i.name.replace("models/",""))||[];return this.cachedModels=s,{healthy:!0,latencyMs:o,models:s.slice(0,20),details:{totalModels:s.length,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){let r=this.getApiKey();if(!r)throw a("Gemini API key not configured","API_KEY_MISSING",{provider:"gemini",retryable:!1});let o=this.formatContents(t),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??8192,i=e?.temperature??this.config.temperature??.7,l=`gemini-${++this.requestId}-${Date.now()}`,p=Date.now(),m={contents:o,generationConfig:{maxOutputTokens:s,temperature:i,topP:this.config.topP}};e?.systemPrompt&&(m.systemInstruction={parts:[{text:e.systemPrompt}]}),e?.stopSequences&&e.stopSequences.length>0&&(m.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(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=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 d=await c.json(),h={promptTokens:d.usageMetadata?.promptTokenCount??0,completionTokens:d.usageMetadata?.candidatesTokenCount??0,totalTokens:d.usageMetadata?.totalTokenCount??0},f=this.calculateCost(n,h);return v.recordTokenUsage(l,"gemini-provider","llm","generate",{inputTokens:h.promptTokens,outputTokens:h.completionTokens,totalTokens:h.totalTokens,estimatedCostUsd:f.totalCost}),{content:d.candidates[0]?.content?.parts?.map(y=>y.text??"").join("")??"",model:d.modelVersion??n,provider:"gemini",usage:h,cost:f,latencyMs:u,finishReason:this.mapFinishReason(d.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 o=this.formatContents(t),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??8192,i=e?.temperature??this.config.temperature??.7,l=`gemini-stream-${++this.requestId}-${Date.now()}`,p=Date.now(),m={contents:o,generationConfig:{maxOutputTokens:s,temperature:i}};e?.systemPrompt&&(m.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(m)},e?.timeoutMs??this.config.timeoutMs??6e4);if(!c.ok){let _=await c.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(c.status,_,n)}if(!c.body)throw a("No response body for streaming","NETWORK_ERROR",{provider:"gemini",model:n,retryable:!0});let u="",d="stop",h={promptTokens:0,completionTokens:0,totalTokens:0},f=c.body.getReader(),b=new TextDecoder,y="";try{for(;;){let{done:_,value:S}=await f.read();if(_)break;y+=b.decode(S,{stream:!0});let w=y.split(`
|
|
44
|
+
`);y=w.pop()||"";for(let re of w){let x=re.trim();if(!(!x||!x.startsWith("data: ")))try{let A=K(x.slice(6)),P=A.candidates?.[0]?.content?.parts?.map(I=>I.text??"").join("")??"";P&&(u+=P,yield P),A.candidates?.[0]?.finishReason&&(d=this.mapFinishReason(A.candidates[0].finishReason)),A.usageMetadata&&(h={promptTokens:A.usageMetadata.promptTokenCount,completionTokens:A.usageMetadata.candidatesTokenCount,totalTokens:A.usageMetadata.totalTokenCount})}catch{}}}}finally{f.releaseLock()}let C=Date.now()-p,k=h.totalTokens>0?h:{promptTokens:Math.ceil(JSON.stringify(o).length/4),completionTokens:Math.ceil(u.length/4),totalTokens:0};k.totalTokens=k.promptTokens+k.completionTokens;let O=this.calculateCost(n,k);return v.recordTokenUsage(l,"gemini-provider","llm","generate-stream",{inputTokens:k.promptTokens,outputTokens:k.completionTokens,totalTokens:k.totalTokens,estimatedCostUsd:O.totalCost}),{content:u,model:n,provider:"gemini",usage:k,cost:O,latencyMs:C,finishReason:d,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 o=e?.model??"text-embedding-004",n=Date.now();try{let s=await this.fetchWithTimeout(`${this.getBaseUrl()}/models/${o}: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(!s.ok){let p=await s.json().catch(()=>({error:{message:"Unknown error",code:0,status:"UNKNOWN"}}));throw this.handleApiError(s.status,p,o)}return{embedding:(await s.json()).embedding.values,model:o,provider:"gemini",tokenCount:Math.ceil(t.length/4),latencyMs:i,cached:!1}}catch(s){throw s instanceof Error&&"code"in s?s:a(s instanceof Error?s.message:"Embedding request failed","NETWORK_ERROR",{provider:"gemini",model:o,retryable:!0,cause:s})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
45
|
+
|
|
46
|
+
`]});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=X[this.config.model]||X.default;return{input:t.input/1e6,output:t.output/1e6}}async dispose(){this.cachedModels=null}calculateCost(t,e){let r=X[t]||X.default,o=e.promptTokens/1e6*r.input,n=e.completionTokens/1e6*r.output;return{inputCost:o,outputCost:n,totalCost:o+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 o=e.error?.message??"Unknown API error";switch(t){case 400:throw o.includes("token")||o.includes("length")||o.includes("exceeds")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"gemini",model:r,retryable:!1}):o.includes("API key")?a(o,"API_KEY_INVALID",{provider:"gemini",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"gemini",model:r,retryable:!1});case 401:case 403:throw a(o,"API_KEY_INVALID",{provider:"gemini",model:r,retryable:!1});case 404:throw a(o,"MODEL_NOT_FOUND",{provider:"gemini",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"gemini",model:r,retryable:!0,retryAfterMs:6e4});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"gemini",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"gemini",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"gemini",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)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)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var Ye={model:"gpt-4o",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0,apiVersion:"2024-02-15-preview"},Z=class{type="azure-openai";name="Azure OpenAI";config;requestId=0;constructor(t){this.config={...Ye,...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 o=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(!o.ok){let s=await o.text();return{healthy:!1,latencyMs:n,error:`API error: ${o.status} - ${s}`}}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(o){return{healthy:!1,error:o instanceof Error?o.message:"Unknown error"}}}async generate(t,e){let r=this.getEndpoint(),o=this.getApiKey()||this.getAzureAdToken();if(!r||!o)throw a("Azure OpenAI not configured","API_KEY_MISSING",{provider:"azure-openai",retryable:!1});let n=this.formatMessages(t,e?.systemPrompt),s=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()}`,m=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 u=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),d=Date.now()-m;if(!u.ok){let C=await u.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(u.status,C,s)}let h=await u.json(),f={promptTokens:h.usage.prompt_tokens,completionTokens:h.usage.completion_tokens,totalTokens:h.usage.total_tokens},b=R.calculateCost(s,f);return v.recordTokenUsage(p,"azure-openai-provider","llm","generate",{inputTokens:h.usage.prompt_tokens,outputTokens:h.usage.completion_tokens,totalTokens:h.usage.total_tokens,estimatedCostUsd:b.totalCost}),{content:h.choices[0]?.message?.content??"",model:h.model,provider:"azure-openai",usage:f,cost:b,latencyMs:d,finishReason:this.mapFinishReason(h.choices[0]?.finish_reason),cached:!1,requestId:p}}catch(u){throw u instanceof Error&&"code"in u?u:a(u instanceof Error?u.message:"Request failed","NETWORK_ERROR",{provider:"azure-openai",model:s,retryable:!0,cause:u})}}async embed(t,e){let r=this.getEndpoint(),o=this.getApiKey()||this.getAzureAdToken();if(!r||!o)throw a("Azure OpenAI not configured","API_KEY_MISSING",{provider:"azure-openai",retryable:!1});let n=e?.model??this.config.deploymentId,s=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()-s;if(!i.ok){let m=await i.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(i.status,m,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??[`
|
|
47
|
+
|
|
48
|
+
`]});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(),o=e??this.config.deploymentId,n=this.getApiVersion();return`${r}/openai/deployments/${o}/${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 o=t.some(n=>n.role==="system");e&&!o&&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 o=e.error?.message??"Unknown API error",n=e.error?.code??"",s=e.error?.innererror?.code??"";switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"azure-openai",model:r,retryable:!1});case 403:throw a(o,"API_KEY_INVALID",{provider:"azure-openai",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"azure-openai",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n==="context_length_exceeded"||s==="context_length_exceeded"?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"azure-openai",model:r,retryable:!1}):s==="content_filter"?a(o,"CONTENT_FILTERED",{provider:"azure-openai",model:r,retryable:!1}):a(o,"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(o,"PROVIDER_UNAVAILABLE",{provider:"azure-openai",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"azure-openai",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"azure-openai",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)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)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var Je={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},ue={"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"},Bs=Object.fromEntries(Object.entries(ue).map(([g,t])=>[t,g])),ee=class{type="bedrock";name="AWS Bedrock";config;requestId=0;constructor(t={}){this.config={...Je,...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),o=await this.invokeModel(r,{anthropic_version:"bedrock-2023-05-31",max_tokens:1,messages:[{role:"user",content:"Hi"}]},5e3),n=Date.now()-e;if(!o.ok){let s=await o.text();return{healthy:!1,latencyMs:n,error:`API error: ${o.status} - ${s}`}}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 o=this.formatMessages(t),n=e?.model??this.config.model,s=this.mapToBedrockModel(n),i=e?.maxTokens??this.config.maxTokens??4096,l=e?.temperature??this.config.temperature??.7,p=`bedrock-${++this.requestId}-${Date.now()}`,m=Date.now(),c={anthropic_version:"bedrock-2023-05-31",max_tokens:i,messages:o};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 u=await this.invokeModelWithRetry(s,c,e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),d=Date.now()-m;if(!u.ok){let C=await u.json().catch(()=>({message:"Unknown error"}));throw this.handleApiError(u.status,C,n)}let h=await u.json(),f={promptTokens:h.usage.input_tokens,completionTokens:h.usage.output_tokens,totalTokens:h.usage.input_tokens+h.usage.output_tokens},b=R.calculateCost(s,f);return v.recordTokenUsage(p,"bedrock-provider","llm","generate",{inputTokens:h.usage.input_tokens,outputTokens:h.usage.output_tokens,totalTokens:h.usage.input_tokens+h.usage.output_tokens,estimatedCostUsd:b.totalCost}),{content:h.content.filter(C=>C.type==="text").map(C=>C.text).join(""),model:s,provider:"bedrock",usage:f,cost:b,latencyMs:d,finishReason:this.mapFinishReason(h.stop_reason),cached:!1,requestId:p}}catch(u){throw u instanceof Error&&"code"in u?u:a(u instanceof Error?u.message:"Request failed","NETWORK_ERROR",{provider:"bedrock",model:n,retryable:!0,cause:u})}}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??[`
|
|
49
|
+
|
|
50
|
+
`,"```"]});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(ue)}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=ue[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 o=this.getCredentials();if(!o)throw a("AWS credentials not configured","API_KEY_MISSING",{provider:"bedrock",retryable:!1});let n=this.getEndpointUrl(t),s=JSON.stringify(e),i=await this.signRequest(n,s,o);return this.fetchWithTimeout(n,{method:"POST",headers:i,body:s},r)}async invokeModelWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)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)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}async signRequest(t,e,r){let o=new URL(t),s=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),i=s.substring(0,8),l={"Content-Type":"application/json",Host:o.host,"X-Amz-Date":s};r.sessionToken&&(l["X-Amz-Security-Token"]=r.sessionToken);let p="POST",m=o.pathname,c="",u=Object.keys(l).map(w=>w.toLowerCase()).sort().join(";"),d=Object.keys(l).map(w=>`${w.toLowerCase()}:${l[w].trim()}`).sort().join(`
|
|
51
|
+
`)+`
|
|
52
|
+
`,h=await this.sha256(e),f=[p,m,c,d,u,h].join(`
|
|
53
|
+
`),b="AWS4-HMAC-SHA256",y=`${i}/${r.region}/${r.service}/aws4_request`,C=await this.sha256(f),k=[b,s,y,C].join(`
|
|
54
|
+
`),O=await this.getSignatureKey(r.secretAccessKey,i,r.region,r.service),_=await this.hmacHex(O,k),S=`${b} Credential=${r.accessKeyId}/${y}, SignedHeaders=${u}, Signature=${_}`;return{...l,Authorization:S}}async sha256(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}async hmac(t,e){let r=new TextEncoder,o=t instanceof Uint8Array?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,n=await crypto.subtle.importKey("raw",o,{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(o=>o.toString(16).padStart(2,"0")).join("")}async getSignatureKey(t,e,r,o){let n=new TextEncoder,s=await this.hmac(n.encode(`AWS4${t}`),e),i=await this.hmac(s,r),l=await this.hmac(i,o);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 o=e.message??"Unknown API error",n=e.__type??"";switch(t){case 401:case 403:throw a(o,"API_KEY_INVALID",{provider:"bedrock",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"bedrock",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n.includes("ValidationException")&&o.includes("token")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"bedrock",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"bedrock",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"bedrock",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"bedrock",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"bedrock",retryable:!0}):s}finally{clearTimeout(n)}}sleep(t){return new Promise(e=>setTimeout(e,t))}};L();var Xe={primary:"claude",fallbacks:["openai","ollama"],loadBalancing:"round-robin",providers:{},global:{enableCostTracking:!0,enableMetrics:!0}},te=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={...Xe,...t},this.circuitBreakers=new q(e?.circuitBreakerConfig),this.cache=new B(e?.cacheConfig),this.costTracker=e?.costTracker??me(),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 ve().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=he(t),r=ge(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,o=typeof t=="string"?t:JSON.stringify(t),n=Math.ceil(o.length/4),s=e?.maxTokens??4096,i=this.costTracker.estimateCost(r,n,s).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:m,spent:c,label:u}of p)if(m&&m>0&&c+i>m)throw a(`LLM ${u} budget exceeded: $${c.toFixed(4)} spent + $${i.toFixed(4)} estimated > $${m.toFixed(2)} cap. Raise --max-budget-usd / maxCost* or switch to a local/subscription provider.`,"COST_LIMIT_EXCEEDED",{retryable:!1})}recordSpend(t,e){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,agent:e})}assertWithinBudget(t,e){this.enforceBudget(t,e)}recordResponseSpend(t,e){this.recordSpend(t,e)}async generate(t,e){if(await this.ensureInitialized(),!e?.skipCache){let o=typeof t=="string"?t:JSON.stringify(t),n=this.cache.getGeneration(o,{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 o=>o.generate(t,e),e?.preferredProvider);if(!e?.skipCache){let o=typeof t=="string"?t:JSON.stringify(t);this.cache.setGeneration(o,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"],o=await this.executeWithFailover("embed",async n=>n.embed(t,e),r.find(n=>this.providers.has(n)));return e?.skipCache||this.cache.setEmbedding(t,o,{model:e?.model}),o}async complete(t,e){if(await this.ensureInitialized(),!e?.skipCache){let o=this.cache.getCompletion(t,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});if(o)return{...o,cached:!0}}this.enforceBudget(t,e);let r=await this.executeWithFailover("complete",async o=>o.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 o=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:o.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 F(this.config.providers.claude);case"claude-code":return new W(this.config.providers["claude-code"]);case"codex":return new z(this.config.providers.codex);case"cognitum":return new j(this.config.providers.cognitum);case"openai":return new H(this.config.providers.openai);case"ollama":return new V(this.config.providers.ollama);case"openrouter":return new J(this.config.providers.openrouter);case"gemini":return new Q(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 Z(e)}case"bedrock":return new ee(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 o=this.selectProvider(r),n=new Set,s,i=[o.provider.type,...this.config.fallbacks.filter(l=>l!==o.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 m=this.circuitBreakers.getBreaker(l);if(m.canExecute())try{let c=Date.now(),u=await m.execute(()=>e(p)),d=Date.now()-c;return this.recordSuccess(l,d,u),u}catch(c){if(s=E(c),this.recordFailure(l,s),"retryable"in s&&!s.retryable)throw s}}throw a(`All providers failed for ${t}: ${s?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:s})}selectProvider(t){if(t){let r=this.providers.get(t),o=this.circuitBreakers.getBreaker(t);if(r&&o.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 o of t){let n=this.providers.get(o),{input:s,output:i}=n.getCostPerToken(),l=s+i;l<e&&(e=l,r=o)}return{provider:this.providers.get(r),reason:"cost-optimization",metadata:{estimatedCost:e}}}selectLeastLatency(t){let e=1/0,r=t[0];for(let o of t){let n=this.metrics.get(o);if(n&&n.latencies.length>0){let s=this.calculateAverage(n.latencies);s<e&&(e=s,r=o)}}return{provider:this.providers.get(r),reason:"latency-optimization",metadata:{avgLatency:e}}}selectRandom(t){let e=pe(0,t.length),r=t[e];return{provider:this.providers.get(r),reason:"load-balance"}}recordSuccess(t,e,r){let o=this.metrics.get(t);if(o&&(o.totalRequests++,o.successCount++,o.latencies.push(e),o.latencies.length>1e3&&(o.latencies=o.latencies.slice(-1e3)),r&&typeof r=="object")){let n=r;n.cost?.totalCost&&(o.totalCost+=n.cost.totalCost),n.usage?.totalTokens&&(o.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,s)=>n-s),o=Math.ceil(e/100*r.length)-1;return r[Math.max(0,o)]}};function En(g){return new te(g)}function Cn(){return new te({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{W as a,V as b,Xe as c,te as d,En as e,Cn as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
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.13.0");process.exit(0)}
|
|
2
2
|
function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
|