agentic-qe 3.14.7 → 3.14.8

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.
Files changed (393) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/auto-memory-hook.mjs +18 -9
  3. package/.claude/helpers/helpers.manifest.json +6 -5
  4. package/.claude/helpers/hook-handler.cjs +40 -12
  5. package/.claude/helpers/memory.cjs +86 -0
  6. package/.claude/helpers/router.cjs +105 -0
  7. package/.claude/helpers/session.cjs +166 -0
  8. package/.claude/helpers/statusline.cjs +73 -621
  9. package/.claude/skills/skills-manifest.json +1 -1
  10. package/CHANGELOG.md +130 -0
  11. package/assets/skills/skills-manifest.json +1 -1
  12. package/dist/adapters/a2a/notifications/retry-queue.js +5 -0
  13. package/dist/adapters/claude-flow/pretrain-bridge.js +3 -2
  14. package/dist/agents/claim-verifier/verifiers/file-verifier.js +3 -2
  15. package/dist/cli/bundle.js +6 -6
  16. package/dist/cli/chunks/adapter-XYCOXQCC.js +2 -0
  17. package/dist/cli/chunks/{agent-booster-wasm-AK2W76RG.js → agent-booster-wasm-67OKGDGZ.js} +2 -2
  18. package/dist/cli/chunks/{agent-handler-MGZCWHIY.js → agent-handler-4HZEQ3WQ.js} +2 -2
  19. package/dist/cli/chunks/{agent-memory-branch-JZ54MCSP.js → agent-memory-branch-IBHZQSRN.js} +2 -2
  20. package/dist/cli/chunks/aqe-learning-engine-DTJCROTG.js +2 -0
  21. package/dist/cli/chunks/{arena-CUVH3V7H.js → arena-EJBIGSF4.js} +2 -2
  22. package/dist/cli/chunks/{arena-YSWTKBCL.js → arena-LCLRGUIK.js} +4 -4
  23. package/dist/cli/chunks/{audit-LVU76QGA.js → audit-PY4JNDQQ.js} +3 -3
  24. package/dist/cli/chunks/base-5TQ34GMD.js +2 -0
  25. package/dist/cli/chunks/{better-sqlite3-DB3LOJQU.js → better-sqlite3-2JG5K6XT.js} +2 -2
  26. package/dist/cli/chunks/{brain-handler-SD63KOQ6.js → brain-handler-3UYK55GA.js} +4 -4
  27. package/dist/cli/chunks/{branch-enumerator-4MNOPUC7.js → branch-enumerator-GOSWOX46.js} +2 -2
  28. package/dist/cli/chunks/{browser-OLPNTWQE.js → browser-DC2JV47Z.js} +2 -2
  29. package/dist/cli/chunks/browser-workflow-KWX4ESTJ.js +2 -0
  30. package/dist/cli/chunks/{chunk-QQFQDEUE.js → chunk-25EEIAHS.js} +2 -2
  31. package/dist/cli/chunks/{chunk-DOBKEXMJ.js → chunk-3576QGPP.js} +1 -1
  32. package/dist/cli/chunks/{chunk-3M7J4U74.js → chunk-3EKG7HFV.js} +4 -4
  33. package/dist/cli/chunks/{chunk-DYTQHRUS.js → chunk-3FCHH4VP.js} +1 -1
  34. package/dist/cli/chunks/{chunk-EJ6MMYLK.js → chunk-3S5IIK32.js} +1 -1
  35. package/dist/cli/chunks/{chunk-NOHWJOBS.js → chunk-3X2JSW3R.js} +1 -1
  36. package/dist/cli/chunks/{chunk-7EZ2Z2CK.js → chunk-4HXFPBAA.js} +1 -1
  37. package/dist/cli/chunks/{chunk-XBYQ2BS4.js → chunk-4PY44TKH.js} +2 -2
  38. package/dist/cli/chunks/{chunk-5FSLMYAC.js → chunk-4RNCVSVN.js} +2 -2
  39. package/dist/cli/chunks/{chunk-X7ADKL7T.js → chunk-56M4QNXU.js} +2 -2
  40. package/dist/cli/chunks/{chunk-JHJUSSAU.js → chunk-5X4HDW5W.js} +2 -2
  41. package/dist/cli/chunks/{chunk-7MIOK72I.js → chunk-673XJBGW.js} +7 -7
  42. package/dist/cli/chunks/{chunk-77QZHIVX.js → chunk-6F7MFHTY.js} +2 -2
  43. package/dist/cli/chunks/{chunk-Q6NTEICT.js → chunk-6GJWT2OY.js} +2 -2
  44. package/dist/cli/chunks/{chunk-GV4DYPJP.js → chunk-6GNWVPMR.js} +2 -2
  45. package/dist/cli/chunks/{chunk-V5AK56DA.js → chunk-6VTC3OHD.js} +2 -2
  46. package/dist/cli/chunks/{chunk-MM56VPNE.js → chunk-775WGWLL.js} +3 -3
  47. package/dist/cli/chunks/{chunk-A3DK3XNZ.js → chunk-77WL5HQW.js} +1 -1
  48. package/dist/cli/chunks/chunk-7STWD4KJ.js +3 -0
  49. package/dist/cli/chunks/{chunk-RC2A4JZ5.js → chunk-7TNCEVWX.js} +2 -2
  50. package/dist/cli/chunks/{chunk-XL5KIYE3.js → chunk-7X3LMTRA.js} +2 -2
  51. package/dist/cli/chunks/{chunk-VW6FRMLW.js → chunk-A53MMSGC.js} +2 -2
  52. package/dist/cli/chunks/{chunk-UFSVUBTR.js → chunk-A5CLVZC3.js} +2 -2
  53. package/dist/cli/chunks/{chunk-4INST4ZL.js → chunk-AEYJ4ZLA.js} +1 -1
  54. package/dist/cli/chunks/{chunk-5U6N4V5M.js → chunk-AJ5PCJQ2.js} +4 -4
  55. package/dist/cli/chunks/{chunk-OAZX6WFU.js → chunk-AJMAKUS3.js} +2 -2
  56. package/dist/cli/chunks/{chunk-74IOEOMH.js → chunk-AOD2ES44.js} +2 -2
  57. package/dist/cli/chunks/chunk-AR2S4DOB.js +2 -0
  58. package/dist/cli/chunks/{chunk-PYKY22GC.js → chunk-AUFV2G2J.js} +5 -5
  59. package/dist/cli/chunks/{chunk-KD2BLA5Y.js → chunk-B2QKBQYD.js} +1 -1
  60. package/dist/cli/chunks/{chunk-6EGS77BB.js → chunk-BCCSV3RH.js} +1 -1
  61. package/dist/cli/chunks/{chunk-JOZ47MV6.js → chunk-BFIXUKOR.js} +1 -1
  62. package/dist/cli/chunks/chunk-BHPTHC5O.js +4 -0
  63. package/dist/cli/chunks/{chunk-OIDWDGLG.js → chunk-BITFGVZ4.js} +2 -2
  64. package/dist/cli/chunks/{chunk-ONR2NXXD.js → chunk-BL6273KR.js} +3 -3
  65. package/dist/cli/chunks/{chunk-BLG7SH4A.js → chunk-BOIUENWW.js} +1 -1
  66. package/dist/cli/chunks/{chunk-T77GZF4B.js → chunk-BT3MI2BW.js} +1 -1
  67. package/dist/cli/chunks/{chunk-UYUJT6QO.js → chunk-BTBJ2NLH.js} +2 -2
  68. package/dist/cli/chunks/{chunk-YMW57PEL.js → chunk-BUVJIVFG.js} +1 -1
  69. package/dist/cli/chunks/{chunk-QUORH2MG.js → chunk-BZIPW2PA.js} +8 -8
  70. package/dist/cli/chunks/{chunk-GVVFTFMB.js → chunk-C647D42G.js} +2 -2
  71. package/dist/cli/chunks/{chunk-AJUBT4NP.js → chunk-CBWM5NOO.js} +3 -3
  72. package/dist/cli/chunks/{chunk-F2OPFVQH.js → chunk-CIEXUYY7.js} +1 -1
  73. package/dist/cli/chunks/{chunk-QGOWNVVG.js → chunk-CLUHGBLN.js} +4 -4
  74. package/dist/cli/chunks/{chunk-WOV6XI3A.js → chunk-CQEWL32R.js} +1 -1
  75. package/dist/cli/chunks/{chunk-3QJU4Q4R.js → chunk-CXUC7YKA.js} +2 -2
  76. package/dist/cli/chunks/{chunk-HZY42OVU.js → chunk-D2Y36V5J.js} +2 -2
  77. package/dist/cli/chunks/{chunk-WF6UISKW.js → chunk-DSJJHPPS.js} +4 -4
  78. package/dist/cli/chunks/{chunk-FYPX5WBJ.js → chunk-DZHXCOSK.js} +1 -1
  79. package/dist/cli/chunks/{chunk-TXSPBLBT.js → chunk-EBV3WFIR.js} +2 -2
  80. package/dist/cli/chunks/{chunk-Y6AKKQIQ.js → chunk-EKO5QL2B.js} +1 -1
  81. package/dist/cli/chunks/{chunk-MZB2UV2O.js → chunk-EMOZ5O5S.js} +1 -1
  82. package/dist/cli/chunks/{chunk-23CX7JNL.js → chunk-ES7TAJRJ.js} +2 -2
  83. package/dist/cli/chunks/{chunk-Z4Q5PCRZ.js → chunk-EXQGHTPD.js} +4 -4
  84. package/dist/cli/chunks/{chunk-A2VUCUTT.js → chunk-F2WAB4WK.js} +2 -2
  85. package/dist/cli/chunks/{chunk-CQNMGK6Y.js → chunk-F57FTFWS.js} +2 -2
  86. package/dist/cli/chunks/{chunk-OEPNNLR4.js → chunk-F6JJNBE5.js} +1 -1
  87. package/dist/cli/chunks/{chunk-UBJG3IHT.js → chunk-FRC7AFB4.js} +2 -2
  88. package/dist/cli/chunks/{chunk-2G63VIJE.js → chunk-G36RZF2Y.js} +1 -1
  89. package/dist/cli/chunks/{chunk-YRHTQZU4.js → chunk-G3C7Z6FO.js} +2 -2
  90. package/dist/cli/chunks/{chunk-B4I43GE2.js → chunk-GA63ESNT.js} +2 -2
  91. package/dist/cli/chunks/{chunk-7QYOTUOX.js → chunk-GHMJFICO.js} +2 -2
  92. package/dist/cli/chunks/{chunk-HYOPJHHW.js → chunk-GK5WLUX3.js} +1 -1
  93. package/dist/cli/chunks/{chunk-A5MA7A23.js → chunk-GQJ4QDEN.js} +6 -6
  94. package/dist/cli/chunks/{chunk-UA7TDVL7.js → chunk-GVLRE3BV.js} +4 -4
  95. package/dist/cli/chunks/{chunk-25P6JA6V.js → chunk-H5UH234L.js} +1 -1
  96. package/dist/cli/chunks/{chunk-BE4KALTE.js → chunk-HBAFXWSO.js} +1 -1
  97. package/dist/cli/chunks/{chunk-EGOIIUBD.js → chunk-HE3BDBAO.js} +2 -2
  98. package/dist/cli/chunks/{chunk-P2UPYSDJ.js → chunk-HHANMCD2.js} +1 -1
  99. package/dist/cli/chunks/{chunk-ZUOVNFXK.js → chunk-HPVYJ6JH.js} +2 -2
  100. package/dist/cli/chunks/{chunk-RKI3IQKQ.js → chunk-I6NZFBT3.js} +3 -3
  101. package/dist/cli/chunks/{chunk-QVH5Y7AP.js → chunk-ISBOHF6Y.js} +1 -1
  102. package/dist/cli/chunks/{chunk-IWFFO6VT.js → chunk-J24AJEDE.js} +2 -2
  103. package/dist/cli/chunks/{chunk-5GFKTJ65.js → chunk-J5HTQHJK.js} +2 -2
  104. package/dist/cli/chunks/{chunk-LY7MFGBD.js → chunk-JDOVO4E4.js} +150 -149
  105. package/dist/cli/chunks/chunk-JQAJUXRE.js +2 -0
  106. package/dist/cli/chunks/{chunk-HXXHMLJ5.js → chunk-JRK5GX56.js} +1 -1
  107. package/dist/cli/chunks/{chunk-36VKMAMN.js → chunk-JRLZ7LZ3.js} +2 -2
  108. package/dist/cli/chunks/{chunk-6PJPQGF4.js → chunk-JTOFLDU7.js} +2 -2
  109. package/dist/cli/chunks/{chunk-CVOQ6ESD.js → chunk-K6EOHGKS.js} +2 -2
  110. package/dist/cli/chunks/{chunk-LU2EDWQK.js → chunk-KKXH25IH.js} +2 -2
  111. package/dist/cli/chunks/{chunk-EYXE2XKP.js → chunk-KNSQWM2E.js} +2 -2
  112. package/dist/cli/chunks/{chunk-IEJ7ZV3M.js → chunk-L5T32SRF.js} +1 -1
  113. package/dist/cli/chunks/{chunk-BEFTQVEW.js → chunk-LKFBW2QM.js} +2 -2
  114. package/dist/cli/chunks/{chunk-C3FXFU2T.js → chunk-LMAI74EP.js} +1 -1
  115. package/dist/cli/chunks/{chunk-P7XSPP5D.js → chunk-LQVS5IWH.js} +2 -2
  116. package/dist/cli/chunks/{chunk-4EKV7PHB.js → chunk-LRGTPUJA.js} +2 -2
  117. package/dist/cli/chunks/{chunk-MT7UNBZ7.js → chunk-LTHV4PIG.js} +2 -2
  118. package/dist/cli/chunks/{chunk-B2YGVSOP.js → chunk-M7QKCHLQ.js} +2 -2
  119. package/dist/cli/chunks/{chunk-H5RQPO3X.js → chunk-N3ASALOL.js} +2 -2
  120. package/dist/cli/chunks/{chunk-MQZ53OR3.js → chunk-NEXBTLN6.js} +2 -2
  121. package/dist/cli/chunks/{chunk-BD7FEUN3.js → chunk-NJEEKYEP.js} +3 -3
  122. package/dist/cli/chunks/{chunk-UOI6ULCH.js → chunk-NWUFTLSF.js} +2 -2
  123. package/dist/cli/chunks/{chunk-RT6O2HW2.js → chunk-O4QB2GFL.js} +2 -2
  124. package/dist/cli/chunks/{chunk-MZMG6CUJ.js → chunk-OA75C4HY.js} +2 -2
  125. package/dist/cli/chunks/{chunk-HYFQUWNB.js → chunk-OVMG6EEF.js} +2 -2
  126. package/dist/cli/chunks/{chunk-FSSR6WBE.js → chunk-OX7MJFLC.js} +2 -2
  127. package/dist/cli/chunks/{chunk-ENK44A6Q.js → chunk-OZJQN7YE.js} +2 -2
  128. package/dist/cli/chunks/{chunk-LXZMP3VX.js → chunk-PFXCRRR6.js} +25 -25
  129. package/dist/cli/chunks/{chunk-WIH522AP.js → chunk-PVJLQ2YZ.js} +1 -1
  130. package/dist/cli/chunks/{chunk-ZUB5YOCM.js → chunk-QDRFLM77.js} +2 -2
  131. package/dist/cli/chunks/{chunk-NHUGHAY6.js → chunk-QH7C4PTX.js} +1 -1
  132. package/dist/cli/chunks/{chunk-VXKWNRGA.js → chunk-QKM4XT2F.js} +2 -2
  133. package/dist/cli/chunks/{chunk-ON2UTP2U.js → chunk-QP7EKLWU.js} +2 -2
  134. package/dist/cli/chunks/{chunk-KUHLTVWC.js → chunk-QPACHVDI.js} +1 -1
  135. package/dist/cli/chunks/{chunk-PCJQCEBA.js → chunk-QQVE65ER.js} +2 -2
  136. package/dist/cli/chunks/{chunk-Q3NSU24F.js → chunk-QYCZYJH7.js} +2 -2
  137. package/dist/cli/chunks/{chunk-AEUEMVJK.js → chunk-R6I5I724.js} +2 -2
  138. package/dist/cli/chunks/{chunk-5D7ZFWDS.js → chunk-RJJIPTVH.js} +2 -2
  139. package/dist/cli/chunks/{chunk-ZWEKAEEV.js → chunk-RM6OC35G.js} +1 -1
  140. package/dist/cli/chunks/{chunk-ZELWDJXT.js → chunk-RTD4U7IW.js} +2 -2
  141. package/dist/cli/chunks/{chunk-O5V7RHVG.js → chunk-SKJQKOFJ.js} +2 -2
  142. package/dist/cli/chunks/{chunk-6RD44SCE.js → chunk-SMBGK7XI.js} +1 -1
  143. package/dist/cli/chunks/{chunk-ND4QTZOL.js → chunk-SPS472C5.js} +2 -2
  144. package/dist/cli/chunks/{chunk-TFK2AYIN.js → chunk-SUNXA2UR.js} +2 -2
  145. package/dist/cli/chunks/{chunk-RDGPXENG.js → chunk-SVP3BP52.js} +2 -2
  146. package/dist/cli/chunks/{chunk-NBLDBVAW.js → chunk-T4WQPE77.js} +1 -1
  147. package/dist/cli/chunks/{chunk-ZS4XVJGV.js → chunk-T53ZN4NO.js} +2 -2
  148. package/dist/cli/chunks/chunk-T6W2EYHC.js +2 -0
  149. package/dist/cli/chunks/{chunk-JZT7BU44.js → chunk-T7YCNOW5.js} +2 -2
  150. package/dist/cli/chunks/{chunk-EADSQN5T.js → chunk-TCQWVVSR.js} +1 -1
  151. package/dist/cli/chunks/{chunk-XYLQZWF6.js → chunk-TGRHO4ES.js} +2 -2
  152. package/dist/cli/chunks/{chunk-QPLSYEWJ.js → chunk-TP7L4EX6.js} +2 -2
  153. package/dist/cli/chunks/{chunk-N5XOXPHZ.js → chunk-TT45RCLN.js} +2 -2
  154. package/dist/cli/chunks/{chunk-OZGIOKEA.js → chunk-TUZNWRYC.js} +1 -1
  155. package/dist/cli/chunks/{chunk-53BXTTRO.js → chunk-U2QTL5T2.js} +3 -3
  156. package/dist/cli/chunks/chunk-U64QORFO.js +2 -0
  157. package/dist/cli/chunks/{chunk-SRPLERER.js → chunk-UHLZKH6B.js} +4 -4
  158. package/dist/cli/chunks/{chunk-HPWWYT67.js → chunk-UIWXKRTK.js} +2 -2
  159. package/dist/cli/chunks/{chunk-XWYELBZS.js → chunk-UNFE4RPV.js} +1 -1
  160. package/dist/cli/chunks/{chunk-FW4DJ4FJ.js → chunk-UQGIC5OX.js} +1 -1
  161. package/dist/cli/chunks/{chunk-GLGKQX2V.js → chunk-VAXTPLO3.js} +2 -2
  162. package/dist/cli/chunks/{chunk-VYDVI6FZ.js → chunk-VCSNNLWL.js} +2 -2
  163. package/dist/cli/chunks/{chunk-J7AQZLIH.js → chunk-VSPNIDQK.js} +4 -4
  164. package/dist/cli/chunks/{chunk-EIGRV3J6.js → chunk-VV2JVYOI.js} +2 -2
  165. package/dist/cli/chunks/{chunk-CBONQM5D.js → chunk-VW7AXJQS.js} +2 -2
  166. package/dist/cli/chunks/{chunk-O6MO5KMR.js → chunk-W7JUD4EZ.js} +2 -2
  167. package/dist/cli/chunks/{chunk-QFETNCNN.js → chunk-WFKE7NZ5.js} +2 -2
  168. package/dist/cli/chunks/{chunk-ROVZSZCS.js → chunk-WVEHKAIH.js} +3 -3
  169. package/dist/cli/chunks/{chunk-YO4ESCB4.js → chunk-XAESN54Q.js} +1 -1
  170. package/dist/cli/chunks/{chunk-RKUAWQOF.js → chunk-XECZYQT5.js} +2 -2
  171. package/dist/cli/chunks/{chunk-RLW25X66.js → chunk-XFT4FYTC.js} +2 -2
  172. package/dist/cli/chunks/{chunk-SM2YJ2AL.js → chunk-YHX74M7C.js} +2 -2
  173. package/dist/cli/chunks/chunk-YIWBJ637.js +2 -0
  174. package/dist/cli/chunks/{chunk-IAENZ2DR.js → chunk-Z5UZOYQS.js} +2 -2
  175. package/dist/cli/chunks/{chunk-G367W7XR.js → chunk-Z6G3QVZ4.js} +12 -12
  176. package/dist/cli/chunks/ci-5LIV2HW5.js +82 -0
  177. package/dist/cli/chunks/{ci-output-RLS32FUY.js → ci-output-UO5BDFU4.js} +2 -2
  178. package/dist/cli/chunks/{circuit-breaker-MRCC7WCM.js → circuit-breaker-UQDPXYRD.js} +2 -2
  179. package/dist/cli/chunks/{claude-flow-setup-LIZCEKDF.js → claude-flow-setup-62QES3QX.js} +2 -2
  180. package/dist/cli/chunks/client-AJZKCP4I.js +2 -0
  181. package/dist/cli/chunks/{cline-installer-T7H6R2RC.js → cline-installer-X7VZTSZG.js} +2 -2
  182. package/dist/cli/chunks/{code-XMBLI7OF.js → code-H3BF4L4H.js} +3 -3
  183. package/dist/cli/chunks/{code-index-extractor-QS7BYLEX.js → code-index-extractor-BJGFZGGL.js} +2 -2
  184. package/dist/cli/chunks/{codex-installer-6PGT5FM6.js → codex-installer-KVZWKU6S.js} +2 -2
  185. package/dist/cli/chunks/{completions-2A3WRXY2.js → completions-YMILE6V7.js} +2 -2
  186. package/dist/cli/chunks/{complexity-analyzer-23HOOGJ7.js → complexity-analyzer-J26N2PWG.js} +2 -2
  187. package/dist/cli/chunks/{continuedev-installer-4FSF7B3N.js → continuedev-installer-MAR42OV7.js} +2 -2
  188. package/dist/cli/chunks/{copilot-installer-A5GRQQUU.js → copilot-installer-CVOJF6OT.js} +2 -2
  189. package/dist/cli/chunks/core-handlers-MQHEMGDV.js +2 -0
  190. package/dist/cli/chunks/{cost-tracker-Z4STQ5VB.js → cost-tracker-SXLWXE55.js} +2 -2
  191. package/dist/cli/chunks/{coverage-NUPP6KZZ.js → coverage-D7HCHFP3.js} +3 -3
  192. package/dist/cli/chunks/cross-domain-router-3QNMZV5R.js +2 -0
  193. package/dist/cli/chunks/{cursor-installer-FVJ7ROPJ.js → cursor-installer-X37VHIKW.js} +2 -2
  194. package/dist/cli/chunks/{daemon-D662EX5N.js → daemon-JN7SOH6F.js} +4 -4
  195. package/dist/cli/chunks/{daemon-7ZZA2MMN.js → daemon-LIW47IDM.js} +4 -4
  196. package/dist/cli/chunks/{dag-attention-scheduler-IB4TQ2KA.js → dag-attention-scheduler-QCHHIZBT.js} +2 -2
  197. package/dist/cli/chunks/{detect-LGLBZN4I.js → detect-WRFCWAX5.js} +2 -2
  198. package/dist/cli/chunks/{dist-node-Z3OL42YE.js → dist-node-6FWT4XZO.js} +2 -2
  199. package/dist/cli/chunks/{domain-handler-L3CLNL7U.js → domain-handler-SNFPNMRT.js} +2 -2
  200. package/dist/cli/chunks/{domain-plugins-GQ3V5X6L.js → domain-plugins-MXKHH62P.js} +2 -2
  201. package/dist/cli/chunks/domain-transfer-47UJNERX.js +2 -0
  202. package/dist/cli/chunks/dream-OSWAITPT.js +2 -0
  203. package/dist/cli/chunks/{embed-and-insert-pattern-UGD6USYH.js → embed-and-insert-pattern-LZFAUNBQ.js} +2 -2
  204. package/dist/cli/chunks/{eval-3B7UIYGY.js → eval-AMUXTMJB.js} +2 -2
  205. package/dist/cli/chunks/{experience-capture-middleware-3RQ4NYY3.js → experience-capture-middleware-3D65TR2C.js} +4 -4
  206. package/dist/cli/chunks/{fast-paths-QOSAEPYD.js → fast-paths-Y7BBMM56.js} +2 -2
  207. package/dist/cli/chunks/{feature-flags-TLF4NKOH.js → feature-flags-JMQQ7JW4.js} +2 -2
  208. package/dist/cli/chunks/{feature-flags-3S5TH6P4.js → feature-flags-VESRRQ6V.js} +2 -2
  209. package/dist/cli/chunks/{file-discovery-AEVMJRNB.js → file-discovery-JJKQQUV6.js} +2 -2
  210. package/dist/cli/chunks/{fleet-E6WTXWFL.js → fleet-WIGHICJF.js} +4 -4
  211. package/dist/cli/chunks/{gnn-wrapper-MCKH3AUU.js → gnn-wrapper-BFNPETTT.js} +2 -2
  212. package/dist/cli/chunks/{heartbeat-handler-U7XENHRR.js → heartbeat-handler-HDXKTGUI.js} +4 -4
  213. package/dist/cli/chunks/heartbeat-scheduler-BVRVVIE2.js +2 -0
  214. package/dist/cli/chunks/hnsw-adapter-MZTHXULS.js +2 -0
  215. package/dist/cli/chunks/hnsw-index-KHEX4VDG.js +2 -0
  216. package/dist/cli/chunks/{hnsw-legacy-bridge-5GW4SAEI.js → hnsw-legacy-bridge-6A7OTAPT.js} +2 -2
  217. package/dist/cli/chunks/{hnswlib-node-7BLZBK5T.js → hnswlib-node-LKV2H47B.js} +2 -2
  218. package/dist/cli/chunks/{hooks-F3O2SB6H.js → hooks-KDSFYQQG.js} +10 -10
  219. package/dist/cli/chunks/hybrid-backend-2B3LCLR4.js +2 -0
  220. package/dist/cli/chunks/{hypergraph-engine-PV4EKXHB.js → hypergraph-engine-GDLPEPUC.js} +2 -2
  221. package/dist/cli/chunks/{hypergraph-handler-VOWO5ZTW.js → hypergraph-handler-4UMFA2EW.js} +3 -3
  222. package/dist/cli/chunks/impact-analyzer-4R4VWOGQ.js +2 -0
  223. package/dist/cli/chunks/{init-handler-ENJ5ONJX.js → init-handler-4GCHPQHD.js} +6 -6
  224. package/dist/cli/chunks/init-wizard-TAOPXHHD.js +2 -0
  225. package/dist/cli/chunks/kernel-6I6VZUWY.js +2 -0
  226. package/dist/cli/chunks/{kilocode-installer-HNNJOOPE.js → kilocode-installer-HJZMT2G5.js} +2 -2
  227. package/dist/cli/chunks/{kiro-installer-UZBIQ3IC.js → kiro-installer-WUPY67HG.js} +2 -2
  228. package/dist/cli/chunks/knowledge-graph-KFMTTUR5.js +2 -0
  229. package/dist/cli/chunks/{learning-YMLCVFUT.js → learning-AXKIS7IG.js} +4 -4
  230. package/dist/cli/chunks/{llm-router-YWTARCCT.js → llm-router-HUDPNZLJ.js} +4 -4
  231. package/dist/cli/chunks/llm-router-service-2D74XVM3.js +2 -0
  232. package/dist/cli/chunks/{load-DKE3F3IP.js → load-RM44POD7.js} +2 -2
  233. package/dist/cli/chunks/load-test-53FWOWNS.js +2 -0
  234. package/dist/cli/chunks/{mcp-5PSGIUCW.js → mcp-5JVQRBOP.js} +2 -2
  235. package/dist/cli/chunks/{memory-3L3O6JMM.js → memory-VGZ2V6PL.js} +5 -5
  236. package/dist/cli/chunks/memory-backend-KFJDDPEZ.js +2 -0
  237. package/dist/cli/chunks/memory-handlers-EI537Z32.js +2 -0
  238. package/dist/cli/chunks/{multi-model-executor-AEEO7IA4.js → multi-model-executor-WPRKCSCM.js} +2 -2
  239. package/dist/cli/chunks/{opencode-installer-ABBO355U.js → opencode-installer-YAJMRCQO.js} +2 -2
  240. package/dist/cli/chunks/{orchestrator-E36Q7MKE.js → orchestrator-MUGWBUYP.js} +6 -6
  241. package/dist/cli/chunks/pattern-null-store-7DMU5CJ4.js +2 -0
  242. package/dist/cli/chunks/{pattern-usage-recorder-H4XKSID4.js → pattern-usage-recorder-ZQJJ2YNG.js} +2 -2
  243. package/dist/cli/chunks/{pipeline-BGFEHXIN.js → pipeline-F4DXDUDC.js} +2 -2
  244. package/dist/cli/chunks/{platform-GK7ZVDJI.js → platform-HI3A3OWF.js} +2 -2
  245. package/dist/cli/chunks/{plugin-CAH2CKI6.js → plugin-XRITPTR7.js} +2 -2
  246. package/dist/cli/chunks/{prime-radiant-advanced-wasm-M5EYRONA.js → prime-radiant-advanced-wasm-HHNJP7CQ.js} +2 -2
  247. package/dist/cli/chunks/{project-root-BSNZC243.js → project-root-2VN4WO2A.js} +2 -2
  248. package/dist/cli/chunks/protocol-executor-2EMTBTMG.js +2 -0
  249. package/dist/cli/chunks/{protocol-handler-JDSSC2SF.js → protocol-handler-ZEVHSEBG.js} +2 -2
  250. package/dist/cli/chunks/{prove-ANPTOZJE.js → prove-C4BLZWBS.js} +2 -2
  251. package/dist/cli/chunks/qe-reasoning-bank-VZHZZPHE.js +2 -0
  252. package/dist/cli/chunks/{quality-SXWGYRQR.js → quality-M3DTE4KK.js} +2 -2
  253. package/dist/cli/chunks/quality-gate-V6KS7ML3.js +7 -0
  254. package/dist/cli/chunks/queen-coordinator-7MYTTUHI.js +2 -0
  255. package/dist/cli/chunks/{real-embeddings-WSRYAOZM.js → real-embeddings-YWSE3IRT.js} +2 -2
  256. package/dist/cli/chunks/{ref-validation-AZ3LRWEK.js → ref-validation-ZWOTFA3T.js} +2 -2
  257. package/dist/cli/chunks/{roocode-installer-2QKGFIEU.js → roocode-installer-GJBIWETD.js} +2 -2
  258. package/dist/cli/chunks/router-ZD4LXAWA.js +2 -0
  259. package/dist/cli/chunks/routing-feedback-FSLMDVGD.js +2 -0
  260. package/dist/cli/chunks/{routing-handler-UYDC5MMD.js → routing-handler-CFYLGNAR.js} +2 -2
  261. package/dist/cli/chunks/{ruvector-commands-QXADPVEY.js → ruvector-commands-EDKG456B.js} +2 -2
  262. package/dist/cli/chunks/rvf-dual-writer-LTKTDRFS.js +2 -0
  263. package/dist/cli/chunks/rvf-migration-adapter-IF24EVC5.js +2 -0
  264. package/dist/cli/chunks/{rvf-migration-coordinator-GD4NBFKT.js → rvf-migration-coordinator-ZMEYMAI6.js} +2 -2
  265. package/dist/cli/chunks/rvf-native-adapter-E6JNBKMZ.js +2 -0
  266. package/dist/cli/chunks/{rvf-store-integrity-7SXG66IL.js → rvf-store-integrity-AH6PNJP6.js} +2 -2
  267. package/dist/cli/chunks/safe-db-F6TRB5KZ.js +2 -0
  268. package/dist/cli/chunks/schedule-HBD4BYTE.js +2 -0
  269. package/dist/cli/chunks/scheduler-6FYWPMQC.js +2 -0
  270. package/dist/cli/chunks/{security-YKB622PK.js → security-ZU2GW3ZM.js} +3 -3
  271. package/dist/cli/chunks/{shared-rvf-adapter-KMLAV7JK.js → shared-rvf-adapter-5FOVSL3T.js} +2 -2
  272. package/dist/cli/chunks/{shared-rvf-dual-writer-OYY27DFV.js → shared-rvf-dual-writer-IO4DC4XV.js} +2 -2
  273. package/dist/cli/chunks/sqlite-persistence-DOU72F5Z.js +2 -0
  274. package/dist/cli/chunks/{standalone-memory-2DOABVLC.js → standalone-memory-3UXDZ7HI.js} +2 -2
  275. package/dist/cli/chunks/{status-handler-EXRKETV7.js → status-handler-264CHTWS.js} +2 -2
  276. package/dist/cli/chunks/{structural-health-2SKK6DU6.js → structural-health-E2QPUOZE.js} +2 -2
  277. package/dist/cli/chunks/{sync-UW7SX7GO.js → sync-2ACMWM7D.js} +2 -2
  278. package/dist/cli/chunks/{sync-DQ2YUNI6.js → sync-N2L2OST4.js} +2 -2
  279. package/dist/cli/chunks/{task-handler-LYQ6WYUY.js → task-handler-IB5CVOTY.js} +2 -2
  280. package/dist/cli/chunks/{task-handlers-DIJO232S.js → task-handlers-QBMYNJHE.js} +3 -3
  281. package/dist/cli/chunks/{test-WRHZMUCW.js → test-7RGLRDSP.js} +6 -6
  282. package/dist/cli/chunks/{test-scheduling-HI23RXFK.js → test-scheduling-RJABJT2W.js} +3 -3
  283. package/dist/cli/chunks/{token-bootstrap-23SA6SWZ.js → token-bootstrap-JVHMHB72.js} +2 -2
  284. package/dist/cli/chunks/{token-usage-M7RRDPXO.js → token-usage-3ECHQVCY.js} +2 -2
  285. package/dist/cli/chunks/{transformers-4TC35KKS.js → transformers-KJH3IJWI.js} +2 -2
  286. package/dist/cli/chunks/{tree-sitter-wasm-parser-F4LTKAWD.js → tree-sitter-wasm-parser-XN6PFI32.js} +2 -2
  287. package/dist/cli/chunks/{types-NBXV6LXQ.js → types-5BAPXOLS.js} +2 -2
  288. package/dist/cli/chunks/unified-memory-GHAYAXWZ.js +2 -0
  289. package/dist/cli/chunks/unified-memory-hnsw-CCC63YXT.js +2 -0
  290. package/dist/cli/chunks/unified-persistence-HKRHI5PG.js +2 -0
  291. package/dist/cli/chunks/{upgrade-4BGOU5RM.js → upgrade-S5NFQZID.js} +2 -2
  292. package/dist/cli/chunks/{validate-EDWAR63H.js → validate-BIBWOLJD.js} +2 -2
  293. package/dist/cli/chunks/{validate-swarm-VI72CPR7.js → validate-swarm-WAA3LBHH.js} +2 -2
  294. package/dist/cli/chunks/visual-security-APOXJ3Q3.js +2 -0
  295. package/dist/cli/chunks/{web-tree-sitter-Y5XBRQXF.js → web-tree-sitter-OTBQTHAV.js} +2 -2
  296. package/dist/cli/chunks/{windsurf-installer-VEX23WAF.js → windsurf-installer-NNQ22EW6.js} +2 -2
  297. package/dist/cli/chunks/witness-chain-7IP5IJGT.js +2 -0
  298. package/dist/cli/chunks/{witness-chain-3YNL6YGY.js → witness-chain-E7MUBOJW.js} +2 -2
  299. package/dist/cli/chunks/{witness-chain-repair-MJZGZRWT.js → witness-chain-repair-FW4QSN4C.js} +2 -2
  300. package/dist/cli/chunks/{witness-chain-verifier-TTJYXTBE.js → witness-chain-verifier-YMROEBVL.js} +2 -2
  301. package/dist/cli/chunks/{witness-key-manager-EM6YXYOY.js → witness-key-manager-4CGRNDMJ.js} +2 -2
  302. package/dist/cli/chunks/{workflow-2RBDOM7V.js → workflow-4VRSTRAN.js} +4 -4
  303. package/dist/cli/chunks/workflow-orchestrator-2HNW5ZMQ.js +2 -0
  304. package/dist/cli/chunks/{wrappers-5OTAVVOV.js → wrappers-4M4UTGEU.js} +2 -2
  305. package/dist/cli/commands/ci.js +17 -6
  306. package/dist/cli/commands/quality-gate.js +6 -1
  307. package/dist/cli/index.js +7 -2
  308. package/dist/cli/process-store-cleanup.d.ts +7 -0
  309. package/dist/cli/process-store-cleanup.js +27 -0
  310. package/dist/cli/utils/ci-config.d.ts +3 -3
  311. package/dist/cli/utils/ci-config.js +202 -68
  312. package/dist/domains/quality-assessment/quality-evidence.d.ts +3 -1
  313. package/dist/domains/quality-assessment/quality-evidence.js +7 -2
  314. package/dist/domains/test-execution/services/retry-handler.js +32 -13
  315. package/dist/domains/test-execution/services/test-executor.d.ts +3 -3
  316. package/dist/domains/test-execution/services/test-executor.js +66 -22
  317. package/dist/init/fleet-integration.js +3 -2
  318. package/dist/init/init-wizard-steps.js +3 -2
  319. package/dist/init/phases/06-code-intelligence.js +6 -4
  320. package/dist/integrations/ruvector/sona-persistence.d.ts +1 -0
  321. package/dist/integrations/ruvector/sona-persistence.js +74 -20
  322. package/dist/integrations/ruvector/sona-wrapper.d.ts +2 -0
  323. package/dist/integrations/ruvector/sona-wrapper.js +13 -0
  324. package/dist/kernel/memory-backend.js +5 -4
  325. package/dist/kernel/unified-memory.js +3 -2
  326. package/dist/learning/aqe-learning-engine.js +3 -2
  327. package/dist/mcp/bundle.js +440 -439
  328. package/dist/mcp/connection-pool.d.ts +2 -0
  329. package/dist/mcp/connection-pool.js +13 -2
  330. package/dist/mcp/handlers/memory-handlers.d.ts +1 -0
  331. package/dist/mcp/handlers/memory-handlers.js +16 -6
  332. package/dist/mcp/protocol-server.js +29 -8
  333. package/dist/mcp/types.d.ts +2 -0
  334. package/dist/optimization/session-cache.js +13 -11
  335. package/dist/plugins/cache.js +10 -3
  336. package/dist/shared/embeddings/embedding-cache.js +4 -4
  337. package/dist/shared/llm/cache.js +7 -10
  338. package/dist/shared/retry-engine.js +4 -0
  339. package/dist/shared/test-runner-process.d.ts +10 -0
  340. package/dist/shared/test-runner-process.js +210 -0
  341. package/dist/validation/quality-verdict.js +3 -2
  342. package/dist/workers/quality-daemon/priority-queue.js +4 -1
  343. package/package.json +4 -4
  344. package/dist/cli/chunks/adapter-TVQKH65T.js +0 -2
  345. package/dist/cli/chunks/aqe-learning-engine-ULGTVVWE.js +0 -2
  346. package/dist/cli/chunks/base-W42BURDL.js +0 -2
  347. package/dist/cli/chunks/browser-workflow-HKGHFFFT.js +0 -2
  348. package/dist/cli/chunks/chunk-2IMSJ7IO.js +0 -2
  349. package/dist/cli/chunks/chunk-FBZC4IGB.js +0 -2
  350. package/dist/cli/chunks/chunk-MNQN7UZX.js +0 -4
  351. package/dist/cli/chunks/chunk-OXHF3L2T.js +0 -2
  352. package/dist/cli/chunks/chunk-PELENDDQ.js +0 -2
  353. package/dist/cli/chunks/chunk-TW3SR4TS.js +0 -2
  354. package/dist/cli/chunks/chunk-V6RE4YRQ.js +0 -2
  355. package/dist/cli/chunks/chunk-ZQZD55MN.js +0 -3
  356. package/dist/cli/chunks/ci-J3TDK5RA.js +0 -81
  357. package/dist/cli/chunks/client-3BD2DI4N.js +0 -2
  358. package/dist/cli/chunks/core-handlers-C3H2ZCS2.js +0 -2
  359. package/dist/cli/chunks/cross-domain-router-JCQ7SWDP.js +0 -2
  360. package/dist/cli/chunks/domain-transfer-MFCI76IY.js +0 -2
  361. package/dist/cli/chunks/dream-FTP33IJB.js +0 -2
  362. package/dist/cli/chunks/heartbeat-scheduler-HXBJVJL2.js +0 -2
  363. package/dist/cli/chunks/hnsw-adapter-TU6WG2ME.js +0 -2
  364. package/dist/cli/chunks/hnsw-index-MS5KODD7.js +0 -2
  365. package/dist/cli/chunks/hybrid-backend-HT45LBHC.js +0 -2
  366. package/dist/cli/chunks/impact-analyzer-AP4AGTG5.js +0 -2
  367. package/dist/cli/chunks/init-wizard-I5DFZUQL.js +0 -2
  368. package/dist/cli/chunks/kernel-MISPSPPA.js +0 -2
  369. package/dist/cli/chunks/knowledge-graph-L26JESGE.js +0 -2
  370. package/dist/cli/chunks/llm-router-service-MWGC43ZA.js +0 -2
  371. package/dist/cli/chunks/load-test-H5ISNNM5.js +0 -2
  372. package/dist/cli/chunks/memory-backend-HWDNOBKW.js +0 -2
  373. package/dist/cli/chunks/memory-handlers-ZFDVQZM5.js +0 -2
  374. package/dist/cli/chunks/pattern-null-store-GQP6ICWK.js +0 -2
  375. package/dist/cli/chunks/protocol-executor-AD5A4DAI.js +0 -2
  376. package/dist/cli/chunks/qe-reasoning-bank-W3Z2PKTR.js +0 -2
  377. package/dist/cli/chunks/quality-gate-GYNCA4ZY.js +0 -7
  378. package/dist/cli/chunks/queen-coordinator-HQRHLIJX.js +0 -2
  379. package/dist/cli/chunks/router-MTP5LH4H.js +0 -2
  380. package/dist/cli/chunks/routing-feedback-GWETVB4L.js +0 -2
  381. package/dist/cli/chunks/rvf-dual-writer-4UE5S7WP.js +0 -2
  382. package/dist/cli/chunks/rvf-migration-adapter-PHH3HF4Q.js +0 -2
  383. package/dist/cli/chunks/rvf-native-adapter-KTLZBUWV.js +0 -2
  384. package/dist/cli/chunks/safe-db-FWWGAPVE.js +0 -2
  385. package/dist/cli/chunks/schedule-TPA4V4D5.js +0 -2
  386. package/dist/cli/chunks/scheduler-5ZTEPNDD.js +0 -2
  387. package/dist/cli/chunks/sqlite-persistence-HPTT624C.js +0 -2
  388. package/dist/cli/chunks/unified-memory-OVFEPRPS.js +0 -2
  389. package/dist/cli/chunks/unified-memory-hnsw-KKRSCZHR.js +0 -2
  390. package/dist/cli/chunks/unified-persistence-7GLR4RI3.js +0 -2
  391. package/dist/cli/chunks/visual-security-2FUM5GLI.js +0 -2
  392. package/dist/cli/chunks/witness-chain-MH6GA5L6.js +0 -2
  393. package/dist/cli/chunks/workflow-orchestrator-H6G65YKU.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.14.7");process.exit(0)}
2
- import{i as b,l as D,n as Q}from"./chunk-TFK2AYIN.js";import{s as X}from"./chunk-QUORH2MG.js";import{b as w}from"./chunk-IAENZ2DR.js";import{f as _,g as Y}from"./chunk-5GFKTJ65.js";var W=["claude","claude-code","codex","openai","ollama","openrouter","bedrock","azure-openai","gemini","cognitum"];function x(r){return W.includes(r)}function p(r,o,e){let t=new Error(r);return t.name="LLMError",t.code=o,t.provider=e?.provider,t.model=e?.model,t.retryable=e?.retryable??!1,t.retryAfterMs=e?.retryAfterMs,t.cause=e?.cause,t}function Te(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var y=new Map,Z=new Set(["anthropic"]),N=/^[a-z0-9][a-z0-9-]{0,62}$/;function M(r){if(typeof r!="string"||r.trim().length===0)return"provider type must be a non-empty string";if(r!==r.toLowerCase())return`provider type "${r}" must be lowercase (AQE_LLM_PROVIDER is matched case-insensitively)`;if(!N.test(r))return`provider type "${r}" must match ${N.source} (lowercase alphanumeric and dashes)`;if(x(r))return`provider type "${r}" is built in and cannot be overridden`;if(Z.has(r))return`provider type "${r}" is reserved`}function ee(r,o,e={}){let t=M(r);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});if(typeof o!="function")throw p(`provider "${r}" must be registered with a factory function`,"INVALID_REGISTRATION",{retryable:!1});y.set(r,{...e,type:r,factory:o,source:e.source??"api"})}function F(r,o,e={}){try{ee(r,o,e);return}catch(t){return t instanceof Error?t.message:String(t)}}function B(r){return y.delete(r)}function $(r){return y.has(r)}function ke(r){return y.get(r)}function h(){return[...y.keys()]}var re=["isAvailable","healthCheck","generate","complete","getConfig","getSupportedModels","getCostPerToken","dispose"];function te(r,o){if(!o||typeof o!="object")return`provider "${r}" factory returned ${o===null?"null":typeof o}, expected an LLMProvider`;let e=o,t=re.filter(i=>typeof e[i]!="function");if(t.length>0)return`provider "${r}" is missing required LLMProvider method(s): ${t.join(", ")}`;if(typeof e.type!="string"||e.type.length===0)return`provider "${r}" must expose a non-empty \`type\``;if(e.type!==r)return`provider "${r}" reports type "${e.type}" \u2014 a provider must not claim an identity other than the one it was registered under`}function Le(r){let o=y.get(r);if(!o)throw p(`Unknown provider type: ${r}`,"PROVIDER_UNAVAILABLE",{retryable:!1});let e=o.factory(o.config),t=te(r,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});return e}function Ae(r){let o=y.get(r);if(o)return{mode:o.billingMode??"metered-api",source:o.source,detail:o.sourceDetail}}Q();function q(r){return r==="onnx"||x(r)}var T=["claude","claude-code","codex","openai","ollama","openrouter","gemini","azure-openai","bedrock","cognitum","onnx"];var oe={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},ne=[{provider:"claude",models:[b,D[1]],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-6-sol","gpt-6-luna"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-5","openai/gpt-6-sol"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["qwen3-coder:30b","qwen3:30b-a3b"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],ie={id:"default-fallback-chain",entries:ne,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},U={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:b,fallbackChain:ie,fallbackBehavior:oe,providers:{claude:{enabled:!0,defaultModel:b},"claude-code":{enabled:!1,defaultModel:b},openai:{enabled:!0,defaultModel:"gpt-6-sol"},ollama:{enabled:!0,defaultModel:"qwen3-coder:30b"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-5"},gemini:{enabled:!1,defaultModel:"gemini-2.5-flash"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},cognitum:{enabled:!1,defaultModel:"cognitum-auto"},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},Ue=[{canonicalId:"claude-opus-5",canonicalName:"Claude Opus 5",providerIds:{claude:"claude-opus-5",openrouter:"anthropic/claude-opus-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-5",canonicalName:"Claude Sonnet 5",providerIds:{claude:"claude-sonnet-5",openrouter:"anthropic/claude-sonnet-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:2,outputCostPer1M:10},{canonicalId:"claude-opus-5-5",canonicalName:"Claude Opus 5.5",providerIds:{claude:"claude-opus-5-5",openrouter:"anthropic/claude-opus-5.5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:4,outputCostPer1M:20},{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];import{spawn as se}from"node:child_process";import{accessSync as ae,constants as de,statSync as le}from"node:fs";import{delimiter as ue,join as pe}from"node:path";var ce=18e4,me=2,E="default";function R(r,o){if(!o||typeof o!="object")return`externalProviders["${r}"] must be an object`;let e=o;if(e.kind!=="cli")return`externalProviders["${r}"].kind must be "cli" (got ${JSON.stringify(e.kind)})`;if(!Array.isArray(e.command)||e.command.length===0)return`externalProviders["${r}"].command must be a non-empty string array`;if(!e.command.every(t=>typeof t=="string"&&t.length>0))return`externalProviders["${r}"].command must contain only non-empty strings`;if(e.billingMode!==void 0&&!["subscription","metered-api","metered-capped","local"].includes(e.billingMode))return`externalProviders["${r}"].billingMode "${String(e.billingMode)}" is not a valid billing mode`;if(e.models!==void 0&&(!Array.isArray(e.models)||e.models.some(t=>typeof t!="string")))return`externalProviders["${r}"].models must be a string array`;if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||e.timeoutMs<=0))return`externalProviders["${r}"].timeoutMs must be a positive number`;if(e.maxConcurrency!==void 0&&(typeof e.maxConcurrency!="number"||e.maxConcurrency<1))return`externalProviders["${r}"].maxConcurrency must be >= 1`;if(e.stripEnv!==void 0&&(!Array.isArray(e.stripEnv)||e.stripEnv.some(t=>typeof t!="string")))return`externalProviders["${r}"].stripEnv must be a string array`;if("apiKey"in e)return`externalProviders["${r}"] must not contain an apiKey \u2014 keys belong in the environment, not in llm-config.json`}var P=class r{type;name;billingMode;config;requestCounter=0;availabilityCache;active=0;queue=[];constructor(o,e){let t=R(o,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});this.type=o,this.config=e,this.name=e.displayName??o,this.billingMode=e.billingMode??"metered-api"}async isAvailable(){let o=Date.now();if(this.availabilityCache&&o-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=ge(this.config.command[0]);return this.availabilityCache={at:o,available:e},e}async healthCheck(){let o=Date.now(),e=await this.isAvailable(),t=Date.now()-o;return e?{healthy:!0,latencyMs:t,models:this.getSupportedModels(),details:{command:this.config.command[0],billing:this.billingMode,external:!0}}:{healthy:!1,latencyMs:t,error:`External provider "${this.type}" could not run "${this.config.command[0]}". Check that the host is installed and on PATH.`}}async generate(o,e){let t=e?.model??this.defaultModel(),i=`${this.type}-${++this.requestCounter}-${Date.now()}`,n=ye(o,e?.systemPrompt),s=e?.timeoutMs??this.config.timeoutMs??ce,l=[];this.config.modelFlag&&t&&t!==E&&l.push(this.config.modelFlag,t);let a=Date.now(),{code:d,stdout:u,stderr:f}=await this.withConcurrency(()=>this.spawnHost(l,n,s)),g=Date.now()-a,v=u.trim();if(d!==0&&!v)throw this.classifyError(f||`${this.type} exited with code ${d}`,t);let c=Math.ceil(n.length/4),S=Math.ceil(v.length/4),J={promptTokens:c,completionTokens:S,totalTokens:c+S};return{content:v,model:t,provider:this.type,usage:J,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"local-estimate"},latencyMs:g,finishReason:"stop",cached:!1,requestId:i}}async embed(o,e){throw p(`External provider "${this.type}" does not support embeddings. Use a provider with an embeddings endpoint (openai, ollama, cognitum).`,"EMBEDDING_UNSUPPORTED",{provider:this.type,retryable:!1})}async complete(o,e){let t=await this.generate(o,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});return{completion:t.content,model:t.model,provider:this.type,usage:t.usage,latencyMs:t.latencyMs,cached:t.cached}}getConfig(){return{...this.config}}getSupportedModels(){return[...this.config.models??[E]]}getCostPerToken(){return{input:0,output:0}}async dispose(){}defaultModel(){return this.config.defaultModel??this.config.models?.[0]??E}static childEnv(o=[],e=process.env){let t={...e};for(let i of o)delete t[i];return t}classifyError(o,e){let t=o.toLowerCase();return t.includes("rate limit")||t.includes("usage limit")||t.includes("429")||t.includes("quota")?p(o,"RATE_LIMITED",{provider:this.type,model:e,retryable:!0,retryAfterMs:6e4}):p(o,"PROVIDER_UNAVAILABLE",{provider:this.type,model:e,retryable:!0})}spawnHost(o,e,t){let[i,...n]=this.config.command,s=[...n,...o];return new Promise((l,a)=>{let d=se(i,s,{env:r.childEnv(this.config.stripEnv),stdio:["pipe","pipe","pipe"]}),u="",f="",g=!1,v=setTimeout(()=>{g||(g=!0,d.kill("SIGKILL"),a(p(`${this.type} timed out after ${t}ms`,"TIMEOUT",{provider:this.type,retryable:!0})))},t);d.stdout.on("data",c=>u+=c.toString()),d.stderr.on("data",c=>f+=c.toString()),d.on("error",c=>{g||(g=!0,clearTimeout(v),a(p(`Failed to spawn "${i}" for provider "${this.type}": ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:this.type,retryable:!1,cause:c})))}),d.on("close",c=>{g||(g=!0,clearTimeout(v),l({code:c??0,stdout:u,stderr:f}))}),d.stdin.on("error",()=>{});try{d.stdin.write(e),d.stdin.end()}catch{}})}async withConcurrency(o){let e=this.config.maxConcurrency??me;this.active>=e&&await new Promise(t=>this.queue.push(t)),this.active++;try{return await o()}finally{this.active--;let t=this.queue.shift();t&&t()}}};function ge(r,o=process.env){let e=n=>{try{return ae(n,de.X_OK),le(n).isFile()}catch{return!1}};if(r.includes("/")||r.includes("\\"))return e(r);let t=(o.PATH??"").split(ue).filter(Boolean),i=process.platform==="win32"?["",...(o.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]:[""];return t.some(n=>i.some(s=>e(pe(n,r+s))))}function ye(r,o){if(typeof r=="string")return o?`${o}
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.14.8");process.exit(0)}
2
+ import{i as b,l as D,n as Q}from"./chunk-SUNXA2UR.js";import{s as X}from"./chunk-BZIPW2PA.js";import{f as _,g as Y}from"./chunk-J5HTQHJK.js";import{b as w}from"./chunk-Z5UZOYQS.js";var W=["claude","claude-code","codex","openai","ollama","openrouter","bedrock","azure-openai","gemini","cognitum"];function x(r){return W.includes(r)}function p(r,o,e){let t=new Error(r);return t.name="LLMError",t.code=o,t.provider=e?.provider,t.model=e?.model,t.retryable=e?.retryable??!1,t.retryAfterMs=e?.retryAfterMs,t.cause=e?.cause,t}function Te(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var y=new Map,Z=new Set(["anthropic"]),N=/^[a-z0-9][a-z0-9-]{0,62}$/;function M(r){if(typeof r!="string"||r.trim().length===0)return"provider type must be a non-empty string";if(r!==r.toLowerCase())return`provider type "${r}" must be lowercase (AQE_LLM_PROVIDER is matched case-insensitively)`;if(!N.test(r))return`provider type "${r}" must match ${N.source} (lowercase alphanumeric and dashes)`;if(x(r))return`provider type "${r}" is built in and cannot be overridden`;if(Z.has(r))return`provider type "${r}" is reserved`}function ee(r,o,e={}){let t=M(r);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});if(typeof o!="function")throw p(`provider "${r}" must be registered with a factory function`,"INVALID_REGISTRATION",{retryable:!1});y.set(r,{...e,type:r,factory:o,source:e.source??"api"})}function F(r,o,e={}){try{ee(r,o,e);return}catch(t){return t instanceof Error?t.message:String(t)}}function B(r){return y.delete(r)}function $(r){return y.has(r)}function ke(r){return y.get(r)}function h(){return[...y.keys()]}var re=["isAvailable","healthCheck","generate","complete","getConfig","getSupportedModels","getCostPerToken","dispose"];function te(r,o){if(!o||typeof o!="object")return`provider "${r}" factory returned ${o===null?"null":typeof o}, expected an LLMProvider`;let e=o,t=re.filter(i=>typeof e[i]!="function");if(t.length>0)return`provider "${r}" is missing required LLMProvider method(s): ${t.join(", ")}`;if(typeof e.type!="string"||e.type.length===0)return`provider "${r}" must expose a non-empty \`type\``;if(e.type!==r)return`provider "${r}" reports type "${e.type}" \u2014 a provider must not claim an identity other than the one it was registered under`}function Le(r){let o=y.get(r);if(!o)throw p(`Unknown provider type: ${r}`,"PROVIDER_UNAVAILABLE",{retryable:!1});let e=o.factory(o.config),t=te(r,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});return e}function Ae(r){let o=y.get(r);if(o)return{mode:o.billingMode??"metered-api",source:o.source,detail:o.sourceDetail}}Q();function q(r){return r==="onnx"||x(r)}var T=["claude","claude-code","codex","openai","ollama","openrouter","gemini","azure-openai","bedrock","cognitum","onnx"];var oe={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},ne=[{provider:"claude",models:[b,D[1]],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-6-sol","gpt-6-luna"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-5","openai/gpt-6-sol"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["qwen3-coder:30b","qwen3:30b-a3b"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],ie={id:"default-fallback-chain",entries:ne,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},U={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:b,fallbackChain:ie,fallbackBehavior:oe,providers:{claude:{enabled:!0,defaultModel:b},"claude-code":{enabled:!1,defaultModel:b},openai:{enabled:!0,defaultModel:"gpt-6-sol"},ollama:{enabled:!0,defaultModel:"qwen3-coder:30b"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-5"},gemini:{enabled:!1,defaultModel:"gemini-2.5-flash"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},cognitum:{enabled:!1,defaultModel:"cognitum-auto"},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},Ue=[{canonicalId:"claude-opus-5",canonicalName:"Claude Opus 5",providerIds:{claude:"claude-opus-5",openrouter:"anthropic/claude-opus-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-5",canonicalName:"Claude Sonnet 5",providerIds:{claude:"claude-sonnet-5",openrouter:"anthropic/claude-sonnet-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:2,outputCostPer1M:10},{canonicalId:"claude-opus-5-5",canonicalName:"Claude Opus 5.5",providerIds:{claude:"claude-opus-5-5",openrouter:"anthropic/claude-opus-5.5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:4,outputCostPer1M:20},{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];import{spawn as se}from"node:child_process";import{accessSync as ae,constants as de,statSync as le}from"node:fs";import{delimiter as ue,join as pe}from"node:path";var ce=18e4,me=2,E="default";function R(r,o){if(!o||typeof o!="object")return`externalProviders["${r}"] must be an object`;let e=o;if(e.kind!=="cli")return`externalProviders["${r}"].kind must be "cli" (got ${JSON.stringify(e.kind)})`;if(!Array.isArray(e.command)||e.command.length===0)return`externalProviders["${r}"].command must be a non-empty string array`;if(!e.command.every(t=>typeof t=="string"&&t.length>0))return`externalProviders["${r}"].command must contain only non-empty strings`;if(e.billingMode!==void 0&&!["subscription","metered-api","metered-capped","local"].includes(e.billingMode))return`externalProviders["${r}"].billingMode "${String(e.billingMode)}" is not a valid billing mode`;if(e.models!==void 0&&(!Array.isArray(e.models)||e.models.some(t=>typeof t!="string")))return`externalProviders["${r}"].models must be a string array`;if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||e.timeoutMs<=0))return`externalProviders["${r}"].timeoutMs must be a positive number`;if(e.maxConcurrency!==void 0&&(typeof e.maxConcurrency!="number"||e.maxConcurrency<1))return`externalProviders["${r}"].maxConcurrency must be >= 1`;if(e.stripEnv!==void 0&&(!Array.isArray(e.stripEnv)||e.stripEnv.some(t=>typeof t!="string")))return`externalProviders["${r}"].stripEnv must be a string array`;if("apiKey"in e)return`externalProviders["${r}"] must not contain an apiKey \u2014 keys belong in the environment, not in llm-config.json`}var P=class r{type;name;billingMode;config;requestCounter=0;availabilityCache;active=0;queue=[];constructor(o,e){let t=R(o,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});this.type=o,this.config=e,this.name=e.displayName??o,this.billingMode=e.billingMode??"metered-api"}async isAvailable(){let o=Date.now();if(this.availabilityCache&&o-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=ge(this.config.command[0]);return this.availabilityCache={at:o,available:e},e}async healthCheck(){let o=Date.now(),e=await this.isAvailable(),t=Date.now()-o;return e?{healthy:!0,latencyMs:t,models:this.getSupportedModels(),details:{command:this.config.command[0],billing:this.billingMode,external:!0}}:{healthy:!1,latencyMs:t,error:`External provider "${this.type}" could not run "${this.config.command[0]}". Check that the host is installed and on PATH.`}}async generate(o,e){let t=e?.model??this.defaultModel(),i=`${this.type}-${++this.requestCounter}-${Date.now()}`,n=ye(o,e?.systemPrompt),s=e?.timeoutMs??this.config.timeoutMs??ce,l=[];this.config.modelFlag&&t&&t!==E&&l.push(this.config.modelFlag,t);let a=Date.now(),{code:d,stdout:u,stderr:f}=await this.withConcurrency(()=>this.spawnHost(l,n,s)),g=Date.now()-a,v=u.trim();if(d!==0&&!v)throw this.classifyError(f||`${this.type} exited with code ${d}`,t);let c=Math.ceil(n.length/4),S=Math.ceil(v.length/4),J={promptTokens:c,completionTokens:S,totalTokens:c+S};return{content:v,model:t,provider:this.type,usage:J,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"local-estimate"},latencyMs:g,finishReason:"stop",cached:!1,requestId:i}}async embed(o,e){throw p(`External provider "${this.type}" does not support embeddings. Use a provider with an embeddings endpoint (openai, ollama, cognitum).`,"EMBEDDING_UNSUPPORTED",{provider:this.type,retryable:!1})}async complete(o,e){let t=await this.generate(o,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});return{completion:t.content,model:t.model,provider:this.type,usage:t.usage,latencyMs:t.latencyMs,cached:t.cached}}getConfig(){return{...this.config}}getSupportedModels(){return[...this.config.models??[E]]}getCostPerToken(){return{input:0,output:0}}async dispose(){}defaultModel(){return this.config.defaultModel??this.config.models?.[0]??E}static childEnv(o=[],e=process.env){let t={...e};for(let i of o)delete t[i];return t}classifyError(o,e){let t=o.toLowerCase();return t.includes("rate limit")||t.includes("usage limit")||t.includes("429")||t.includes("quota")?p(o,"RATE_LIMITED",{provider:this.type,model:e,retryable:!0,retryAfterMs:6e4}):p(o,"PROVIDER_UNAVAILABLE",{provider:this.type,model:e,retryable:!0})}spawnHost(o,e,t){let[i,...n]=this.config.command,s=[...n,...o];return new Promise((l,a)=>{let d=se(i,s,{env:r.childEnv(this.config.stripEnv),stdio:["pipe","pipe","pipe"]}),u="",f="",g=!1,v=setTimeout(()=>{g||(g=!0,d.kill("SIGKILL"),a(p(`${this.type} timed out after ${t}ms`,"TIMEOUT",{provider:this.type,retryable:!0})))},t);d.stdout.on("data",c=>u+=c.toString()),d.stderr.on("data",c=>f+=c.toString()),d.on("error",c=>{g||(g=!0,clearTimeout(v),a(p(`Failed to spawn "${i}" for provider "${this.type}": ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:this.type,retryable:!1,cause:c})))}),d.on("close",c=>{g||(g=!0,clearTimeout(v),l({code:c??0,stdout:u,stderr:f}))}),d.stdin.on("error",()=>{});try{d.stdin.write(e),d.stdin.end()}catch{}})}async withConcurrency(o){let e=this.config.maxConcurrency??me;this.active>=e&&await new Promise(t=>this.queue.push(t)),this.active++;try{return await o()}finally{this.active--;let t=this.queue.shift();t&&t()}}};function ge(r,o=process.env){let e=n=>{try{return ae(n,de.X_OK),le(n).isFile()}catch{return!1}};if(r.includes("/")||r.includes("\\"))return e(r);let t=(o.PATH??"").split(ue).filter(Boolean),i=process.platform==="win32"?["",...(o.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]:[""];return t.some(n=>i.some(s=>e(pe(n,r+s))))}function ye(r,o){if(typeof r=="string")return o?`${o}
3
3
 
4
4
  ${r}`:r;let e=r.filter(n=>n.role==="system").map(n=>n.content);o&&e.unshift(o);let t=r.filter(n=>n.role!=="system").map(n=>`${n.role==="assistant"?"Assistant":"User"}: ${n.content}`).join(`
5
5
 
@@ -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.14.7");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
2
  var i=class r{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new r(e)}};var s=class r{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new r(e)}static fromPercentage(e){return new r(e/100)}},u=class r{constructor(e,t){this._start=e;this._end=t;if(e>t)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,t){return new r(e,t)}static lastNDays(e){let t=new Date,n=new Date(t.getTime()-e*24*60*60*1e3);return new r(n,t)}},o=class r{constructor(e,t,n,a){this._major=e;this._minor=t;this._patch=n;this._prerelease=a}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,t,n,a){return new r(e,t,n,a)}static parse(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw new Error(`Invalid version format: ${e}`);return new r(parseInt(t[1]),parseInt(t[2]),parseInt(t[3]),t[4])}};export{i as a,s as b,u as c,o as d};
@@ -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.14.7");process.exit(0)}
2
- import{a as N,d as P}from"./chunk-RDGPXENG.js";import{b,e as k}from"./chunk-VYDVI6FZ.js";import{a as p,d as F}from"./chunk-HYFQUWNB.js";import{a as T,b as E}from"./chunk-B4I43GE2.js";import{a as H,b as O}from"./chunk-CBONQM5D.js";import{b as z,f as S}from"./chunk-YO4ESCB4.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
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.14.8");process.exit(0)}
2
+ import{a as N,d as P}from"./chunk-SVP3BP52.js";import{b,e as k}from"./chunk-VCSNNLWL.js";import{a as T,b as E}from"./chunk-GA63ESNT.js";import{a as H,b as O}from"./chunk-VW7AXJQS.js";import{a as p,d as F}from"./chunk-OVMG6EEF.js";import{b as z,f as S}from"./chunk-XAESN54Q.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
@@ -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.14.7");process.exit(0)}
2
- import{o as f,s as P}from"./chunk-QUORH2MG.js";import{b as h,d as U}from"./chunk-OIDWDGLG.js";import{f as p,g as y}from"./chunk-5GFKTJ65.js";import{a as T,e as C}from"./chunk-ZUOVNFXK.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
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.14.8");process.exit(0)}
2
+ import{o as f,s as P}from"./chunk-BZIPW2PA.js";import{b as h,d as U}from"./chunk-BITFGVZ4.js";import{f as p,g as y}from"./chunk-J5HTQHJK.js";import{a as T,e as C}from"./chunk-HPVYJ6JH.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
3
3
  ${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
@@ -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.14.7");process.exit(0)}
2
- import{b as c,d as p}from"./chunk-OIDWDGLG.js";import{a as f}from"./chunk-YO4ESCB4.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
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.14.8");process.exit(0)}
2
+ import{b as c,d as p}from"./chunk-BITFGVZ4.js";import{a as f}from"./chunk-XAESN54Q.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
3
3
  `)}export{S as a,b,x as c,P as d};
@@ -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.14.7");process.exit(0)}
2
- import{b as y}from"./chunk-36VKMAMN.js";import{a as R,c as N,d as m,e as f,f as A,j as I}from"./chunk-4INST4ZL.js";import{o as g,s as O}from"./chunk-QUORH2MG.js";O();var h=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=g();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.readonly||(this.db.exec(`
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.14.8");process.exit(0)}
2
+ import{b as y}from"./chunk-JRLZ7LZ3.js";import{a as R,c as N,d as m,e as f,f as A,j as I}from"./chunk-AEYJ4ZLA.js";import{o as g,s as O}from"./chunk-BZIPW2PA.js";O();var h=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=g();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.readonly||(this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
@@ -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.14.7");process.exit(0)}
2
- import{o as C,s as M}from"./chunk-QUORH2MG.js";import{i as b}from"./chunk-FW4DJ4FJ.js";M();import{createRequire as H}from"node:module";var w=H(import.meta.url),_=null;function T(){if(_)return _;let E=w("hnswlib-node");if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function U(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=U(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=w("../../../kernel/hnsw-adapter.js"),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=T(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=T(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var O={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...O,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=C();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
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.14.8");process.exit(0)}
2
+ import{o as C,s as M}from"./chunk-BZIPW2PA.js";import{i as b}from"./chunk-UQGIC5OX.js";M();import{createRequire as H}from"node:module";var w=H(import.meta.url),_=null;function T(){if(_)return _;let E=w("hnswlib-node");if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function U(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=U(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=w("../../../kernel/hnsw-adapter.js"),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=T(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=T(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var O={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...O,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=C();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
3
3
  SELECT id, task, domain, quality, success, application_count,
4
4
  consolidation_count, reuse_success_count, reuse_failure_count,
5
5
  embedding, embedding_dimension, started_at
@@ -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.14.7");process.exit(0)}
2
- import{c as g,n as S,o as _}from"./chunk-3M7J4U74.js";function q(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??S()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-KTLZBUWV.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}this.activeSpaceId()||await _();let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-7SXG66IL.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=q(n,this.config.dimensions),g(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
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.14.8");process.exit(0)}
2
+ import{c as g,n as S,o as _}from"./chunk-3EKG7HFV.js";function q(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??S()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-E6JNBKMZ.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}this.activeSpaceId()||await _();let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-AH6PNJP6.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=q(n,this.config.dimensions),g(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
3
3
  SELECT COUNT(*) AS incompatible
4
4
  FROM qe_pattern_embeddings
5
5
  WHERE space_id IS NULL OR space_id <> ?
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
2
- import{d as C}from"./chunk-Z4Q5PCRZ.js";import{a as T}from"./chunk-HYOPJHHW.js";import{a as w,b as S}from"./chunk-4EKV7PHB.js";import{r as D,s as F}from"./chunk-QUORH2MG.js";import{a as R,e as A}from"./chunk-ZUOVNFXK.js";import{f as O}from"./chunk-YO4ESCB4.js";import{createHash as M}from"crypto";function I(){let s="3.14.7",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${s}+${e}`:s}var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function x(s){if(s==null||typeof s!="object")return JSON.stringify(s);if(Array.isArray(s))return"["+s.map(i=>x(i)).join(",")+"]";let e=s;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+x(e[i])).join(",")+"}"}var b=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=x({action:t,build:I(),domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let o={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,o),this.config.persistToDb&&this.persistEntry(o)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
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.14.8");process.exit(0)}
2
+ import{d as C}from"./chunk-EXQGHTPD.js";import{a as T}from"./chunk-GK5WLUX3.js";import{a as R,b as S}from"./chunk-LRGTPUJA.js";import{r as A,s as D}from"./chunk-BZIPW2PA.js";import{a as k,e as O}from"./chunk-HPVYJ6JH.js";import{f as z}from"./chunk-XAESN54Q.js";import{createHash as F}from"crypto";function M(){let a="3.14.8",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${a}+${e}`:a}var I={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function $(a){let e=JSON.parse(JSON.stringify(a));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}var x=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...I,...e}}computeFingerprint(e,t,r){let i=$({action:t,build:M(),domain:e,input:r});return F("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.generation++}getGeneration(){return this.generation}invalidateAll(){let e=this.cache.size;if(this.cache.clear(),this.generation++,this.config.persistToDb)try{d()?.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache'").run()}catch{}return e}invalidateDomain(e){this.generation++;let t=0;for(let[r,i]of this.cache)i.domain===e&&(this.cache.delete(r),this.deletePersisted(i.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=d();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
6
- VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}deletePersisted(e){try{let t=d();if(!t)return;t.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache' AND key = ?").run(`session_cache:${e}`)}catch{}}};function d(){try{let{getUnifiedMemory:s}=(F(),O(D)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function p(s){return f||(f=new b(s),f.loadFromDb()),f}import{randomUUID as H}from"crypto";A();var v={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},j={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},G={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},g=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...v,...t}}async checkEarlyExit(e){let t=performance.now(),r=new Date;try{let i=e.domain??T(e.description)??void 0,n={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};i&&(n.domain=i),e.context&&(n.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let o=e.embedding??e.description,m=await this.patternStore.search(o,n),l=performance.now()-t;if(!m.success){let a="error"in m?m.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${a}`,l);return this.recordAttempt("search_error",i),h}let c=m.value;if(c.length===0){let a=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",l);return this.recordAttempt("no_matching_pattern",i),a}let u=null;for(let{pattern:a,score:h}of c){let y=this.evaluatePatternEligibility(a,h,r);if(y.eligible){let E=this.estimateTokensSaved(a),z={canExit:!0,reusedPattern:a,estimatedTokensSaved:E,confidence:a.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${a.name}" with ${(a.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:l};return this.recordReuse(a.id,E,a.confidence,h,l,i),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${a.name} (confidence: ${a.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${E})`),z}u===null&&(u={reason:y.reason,explanation:y.explanation})}if(u){let a=this.createResult(!1,u.reason,u.explanation,l);return this.recordAttempt(u.reason,i),a}let P=this.createResult(!1,"no_matching_pattern",`Found ${c.length} patterns but none met eligibility criteria`,l);return this.recordAttempt("no_matching_pattern",i),P}catch(i){let n=performance.now()-t,o=this.createResult(!1,"search_error",`Error during pattern search: ${R(i)}`,n);return this.recordAttempt("search_error"),o}}evaluatePatternEligibility(e,t,r){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let i=r.getTime()-e.lastUsedAt.getTime();if(i>this.config.maxPatternAge){let n=Math.floor(i/864e5),o=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${n} days > max ${o} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,r=Math.ceil(e.template.content.length/4);t+=r,t+=50;let o={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*o)}createResult(e,t,r,i){return{canExit:e,reason:t,explanation:r,searchLatencyMs:i}}recordReuse(e,t,r,i,n,o){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:r,similarity:i,latencyMs:n,domain:o,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:o,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,r=0,i=0,n=0,o=0;for(let c of this.reuseHistory)r+=c.tokensSaved,i+=c.confidence,n+=c.similarity,o+=c.latencyMs;let m={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let c of this.attemptHistory)m[c.reason]++;let l={};for(let c of this.reuseHistory){let u=c.domain??"unknown";l[u]||(l[u]={reuses:0,tokens:0}),l[u].reuses++,l[u].tokens+=c.tokensSaved}return{totalReuses:e,tokensSaved:r,avgConfidence:e>0?i/e:0,avgSimilarity:e>0?n/e:0,avgSearchLatencyMs:e>0?o/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:m,domainBreakdown:l}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var _={enabled:!0,earlyExit:v,verbose:!1},k=class{optimizer=null;patternStore=null;config=_;initialized=!1;readyPromise=null;memoryBackend=null;async initialize(e,t){this.initialized||(this.readyPromise=null,this.patternStore=null,this.optimizer=null,this.config={..._,...t},this.memoryBackend=e,this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Registered (lazy \u2014 pattern store not yet created)"))}async ensurePatternStoreReady(){if(!this.optimizer&&!(!this.initialized||!this.config.enabled||!this.memoryBackend))return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{try{this.patternStore=C(this.memoryBackend),await this.patternStore.initialize(),this.optimizer=new g(this.patternStore,this.config.earlyExit),this.config.verbose&&console.log("[TokenOptimizerService] Pattern store ready (lazy init)")}catch(e){console.warn("[TokenOptimizerService] Lazy pattern store init failed:",e)}})(),this.readyPromise)}async checkEarlyExit(e){if(!this.initialized||!this.config.enabled)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let r=p(),i=r.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),n=r.get(i);if(n)return S.recordEarlyExit(n.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${i.slice(0,8)}... (saved ${n.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:n.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${i.slice(0,8)}...)`,searchLatencyMs:0}}catch{}if(await this.ensurePatternStoreReady(),!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Pattern store unavailable (lazy init failed or disabled)",searchLatencyMs:0};let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(S.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(await this.ensurePatternStoreReady(),!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${H().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return w()}cacheOperationResult(e,t,r,i,n){try{let o=p(),m=o.computeFingerprint(e,t,r);o.set(m,e,t,i,n)}catch{}}getSessionCacheStats(){try{return p().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.readyPromise=null,this.memoryBackend=null,this.config=_}},L=new k;async function ie(s,e){await L.initialize(s,e)}export{p as a,L as b,ie as c};
6
+ VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}deletePersisted(e){try{let t=d();if(!t)return;t.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache' AND key = ?").run(`session_cache:${e}`)}catch{}}};function d(){try{let{getUnifiedMemory:a}=(D(),z(A)),e=a();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function p(a){return f||(f=new x(a),f.loadFromDb()),f}import{randomUUID as H}from"crypto";O();var v={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},j={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},G={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},g=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...v,...t}}async checkEarlyExit(e){let t=performance.now(),r=new Date;try{let i=e.domain??T(e.description)??void 0,n={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};i&&(n.domain=i),e.context&&(n.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let s=e.embedding??e.description,m=await this.patternStore.search(s,n),l=performance.now()-t;if(!m.success){let o="error"in m?m.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${o}`,l);return this.recordAttempt("search_error",i),h}let c=m.value;if(c.length===0){let o=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",l);return this.recordAttempt("no_matching_pattern",i),o}let u=null;for(let{pattern:o,score:h}of c){let y=this.evaluatePatternEligibility(o,h,r);if(y.eligible){let E=this.estimateTokensSaved(o),P={canExit:!0,reusedPattern:o,estimatedTokensSaved:E,confidence:o.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${o.name}" with ${(o.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:l};return this.recordReuse(o.id,E,o.confidence,h,l,i),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${o.name} (confidence: ${o.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${E})`),P}u===null&&(u={reason:y.reason,explanation:y.explanation})}if(u){let o=this.createResult(!1,u.reason,u.explanation,l);return this.recordAttempt(u.reason,i),o}let w=this.createResult(!1,"no_matching_pattern",`Found ${c.length} patterns but none met eligibility criteria`,l);return this.recordAttempt("no_matching_pattern",i),w}catch(i){let n=performance.now()-t,s=this.createResult(!1,"search_error",`Error during pattern search: ${k(i)}`,n);return this.recordAttempt("search_error"),s}}evaluatePatternEligibility(e,t,r){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let i=r.getTime()-e.lastUsedAt.getTime();if(i>this.config.maxPatternAge){let n=Math.floor(i/864e5),s=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${n} days > max ${s} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,r=Math.ceil(e.template.content.length/4);t+=r,t+=50;let s={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*s)}createResult(e,t,r,i){return{canExit:e,reason:t,explanation:r,searchLatencyMs:i}}recordReuse(e,t,r,i,n,s){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:r,similarity:i,latencyMs:n,domain:s,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:s,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,r=0,i=0,n=0,s=0;for(let c of this.reuseHistory)r+=c.tokensSaved,i+=c.confidence,n+=c.similarity,s+=c.latencyMs;let m={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let c of this.attemptHistory)m[c.reason]++;let l={};for(let c of this.reuseHistory){let u=c.domain??"unknown";l[u]||(l[u]={reuses:0,tokens:0}),l[u].reuses++,l[u].tokens+=c.tokensSaved}return{totalReuses:e,tokensSaved:r,avgConfidence:e>0?i/e:0,avgSimilarity:e>0?n/e:0,avgSearchLatencyMs:e>0?s/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:m,domainBreakdown:l}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var b={enabled:!0,earlyExit:v,verbose:!1},_=class{optimizer=null;patternStore=null;config=b;initialized=!1;readyPromise=null;memoryBackend=null;async initialize(e,t){this.initialized||(this.readyPromise=null,this.patternStore=null,this.optimizer=null,this.config={...b,...t},this.memoryBackend=e,this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Registered (lazy \u2014 pattern store not yet created)"))}async ensurePatternStoreReady(){if(!this.optimizer&&!(!this.initialized||!this.config.enabled||!this.memoryBackend))return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{try{this.patternStore=C(this.memoryBackend),await this.patternStore.initialize(),this.optimizer=new g(this.patternStore,this.config.earlyExit),this.config.verbose&&console.log("[TokenOptimizerService] Pattern store ready (lazy init)")}catch(e){console.warn("[TokenOptimizerService] Lazy pattern store init failed:",e)}})(),this.readyPromise)}async checkEarlyExit(e){if(!this.initialized||!this.config.enabled)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let r=p(),i=r.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),n=r.get(i);if(n)return S.recordEarlyExit(n.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${i.slice(0,8)}... (saved ${n.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:n.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${i.slice(0,8)}...)`,searchLatencyMs:0}}catch{}if(await this.ensurePatternStoreReady(),!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Pattern store unavailable (lazy init failed or disabled)",searchLatencyMs:0};let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(S.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(await this.ensurePatternStoreReady(),!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${H().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return R()}cacheOperationResult(e,t,r,i,n){try{let s=p(),m=s.computeFingerprint(e,t,r);s.set(m,e,t,i,n)}catch{}}getSessionCacheStats(){try{return p().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.readyPromise=null,this.memoryBackend=null,this.config=b}},L=new _;async function ie(a,e){await L.initialize(a,e)}export{p as a,L as b,ie as c};
@@ -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.14.7");process.exit(0)}
2
- import{l as d}from"./chunk-LU2EDWQK.js";import{a as u,e as g}from"./chunk-ZUOVNFXK.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
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.14.8");process.exit(0)}
2
+ import{l as d}from"./chunk-KKXH25IH.js";import{a as u,e as g}from"./chunk-HPVYJ6JH.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};