promptfoo 0.125.0 → 0.125.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/src/accounts-BOxNYxVN.js +229 -0
- package/dist/src/accounts-BezXLdAW.cjs +276 -0
- package/dist/src/accounts-CPISMNlh.js +227 -0
- package/dist/src/accounts-vJBPs89d.js +222 -0
- package/dist/src/agentWorkspace-Bom7SpF2.js +592 -0
- package/dist/src/agentWorkspace-CEomAcws.cjs +619 -0
- package/dist/src/agentWorkspace-DPtMLrlI.js +593 -0
- package/dist/src/agentWorkspace-DkAeEYLz.js +592 -0
- package/dist/src/agentic-utils-121v7mJo.js +197 -0
- package/dist/src/agentic-utils-CBWD_rcd.cjs +237 -0
- package/dist/src/agentic-utils-D8wyQwPG.js +198 -0
- package/dist/src/agentic-utils-EP1QkQCs.js +197 -0
- package/dist/src/agents-Br3ah8iA.js +778 -0
- package/dist/src/agents-C5wj_UTv.js +777 -0
- package/dist/src/agents-C9Efp4mC.js +266 -0
- package/dist/src/agents-CQYwaVCO.js +267 -0
- package/dist/src/agents-CjCd4Vo8.js +777 -0
- package/dist/src/agents-DRWiCHYz.js +266 -0
- package/dist/src/agents-F2rhx0iL.cjs +266 -0
- package/dist/src/agents-RTYyy69h.cjs +777 -0
- package/dist/src/agents-api-CY72O86e.js +711 -0
- package/dist/src/agents-api-CsSsC21b.js +710 -0
- package/dist/src/agents-api-DN-ibDc8.js +710 -0
- package/dist/src/agents-api-cNDsCCv1.cjs +710 -0
- package/dist/src/ai.studio-Bj6Dyi6o.js +2 -0
- package/dist/src/ai.studio-C-e0LzyW.js +369 -0
- package/dist/src/ai.studio-CR8M6Aqf.cjs +391 -0
- package/dist/src/ai.studio-YKk7F0tv.js +374 -0
- package/dist/src/aimlapi-BGunsuTu.js +30 -0
- package/dist/src/aimlapi-BkzcfBsL.js +29 -0
- package/dist/src/aimlapi-DXFcEdP8.js +28 -0
- package/dist/src/aimlapi-r-8iCcAw.cjs +29 -0
- package/dist/src/anthropicMessages-7-YNRgQR.js +114 -0
- package/dist/src/anthropicMessages-C8m9Whrd.cjs +114 -0
- package/dist/src/anthropicMessages-DS1vXD0f.js +115 -0
- package/dist/src/anthropicMessages-DmvGkz-0.js +114 -0
- package/dist/src/app/assets/index-CrdXWTXm.js +392 -0
- package/dist/src/app/browser-inventory.json +4 -4
- package/dist/src/app/index.html +1 -1
- package/dist/src/audio-BLgFgyw-.cjs +104 -0
- package/dist/src/audio-C2sibT7Q.js +104 -0
- package/dist/src/audio-DXEXb03H.js +104 -0
- package/dist/src/audio-TkvojpwO.js +105 -0
- package/dist/src/authoritativeMarkupInjection-BAT9B-Wj.js +79 -0
- package/dist/src/authoritativeMarkupInjection-B_yHETKT.js +78 -0
- package/dist/src/authoritativeMarkupInjection-BfjecQ3Q.cjs +78 -0
- package/dist/src/authoritativeMarkupInjection-D-hDKrhD.js +78 -0
- package/dist/src/aws-B_9unI_-.js +1149 -0
- package/dist/src/aws-D0FY3qkc.js +2433 -0
- package/dist/src/aws-Dh1-a90n.js +2433 -0
- package/dist/src/aws-qskKGczY.cjs +2454 -0
- package/dist/src/base-CaWlBkVz.js +462 -0
- package/dist/src/base-CcViNwVs.js +255 -0
- package/dist/src/base-CsVbPJkU.cjs +467 -0
- package/dist/src/base-DNK9py25.js +255 -0
- package/dist/src/base-DlH5tjEZ.js +463 -0
- package/dist/src/base-DyLOZ_iX.js +256 -0
- package/dist/src/base-RRYXfG7l.cjs +305 -0
- package/dist/src/base-oXVgvtVn.js +462 -0
- package/dist/src/bedrock-BP17ZXbR.cjs +2 -0
- package/dist/src/bedrock-CsjM1dOt.js +1300 -0
- package/dist/src/bedrock-CzPwj8GO.js +1 -0
- package/dist/src/bedrock-eGXZw8oh.js +1 -0
- package/dist/src/bedrock-tSWjmXdj.js +2 -0
- package/dist/src/bestOfN-BQ93nUKV.js +160 -0
- package/dist/src/bestOfN-ByGGwlcb.cjs +161 -0
- package/dist/src/bestOfN-CbP7csHr.js +159 -0
- package/dist/src/bestOfN-xn6i2Xs2.js +159 -0
- package/dist/src/cache-CHq9hPz9.js +2 -0
- package/dist/src/cache-D-9eZN3I.js +754 -0
- package/dist/src/cache-DSm6t1MZ.js +741 -0
- package/dist/src/cache-DeF5zIEN.js +782 -0
- package/dist/src/cache-iG87oYan.cjs +856 -0
- package/dist/src/cerebras-CTtM4yMH.js +98 -0
- package/dist/src/cerebras-CogcJ3ce.cjs +97 -0
- package/dist/src/cerebras-DmkRypTh.js +97 -0
- package/dist/src/cerebras-GUp0B8JY.js +97 -0
- package/dist/src/chat-B4ihd3fw.js +226 -0
- package/dist/src/chat-B9cAQ_rS.js +227 -0
- package/dist/src/chat-BU7EB4R-.cjs +76 -0
- package/dist/src/chat-C8yxJ2-s.cjs +226 -0
- package/dist/src/chat-ClTFM3qq.js +934 -0
- package/dist/src/chat-Cnq0Is68.js +123 -0
- package/dist/src/chat-CwrurR57.cjs +987 -0
- package/dist/src/chat-D0lsojPv.js +124 -0
- package/dist/src/chat-D7_8yFIx.js +76 -0
- package/dist/src/chat-DCoETlLG.js +226 -0
- package/dist/src/chat-DHE7xaTR.js +76 -0
- package/dist/src/chat-DmhT6rz2.cjs +123 -0
- package/dist/src/chat-DvfMe8KI.js +123 -0
- package/dist/src/chat-DwP5kVnl.js +935 -0
- package/dist/src/chat-MB7U-QE2.js +77 -0
- package/dist/src/chat-zCWuBKAj.js +934 -0
- package/dist/src/claude-agent-sdk-23bIVI75.js +999 -0
- package/dist/src/claude-agent-sdk-BACpnIJi.cjs +1005 -0
- package/dist/src/claude-agent-sdk-BlYlmcEr.js +999 -0
- package/dist/src/claude-agent-sdk-Cr-jqJZl.js +1000 -0
- package/dist/src/client-BktbiPx9.cjs +357 -0
- package/dist/src/client-CjztEBmW.js +351 -0
- package/dist/src/client-mRs2UvH9.js +351 -0
- package/dist/src/client-uCz0ydjC.js +352 -0
- package/dist/src/cloud-BtYF555L.js +2 -0
- package/dist/src/cloud-CVSUEmAy.js +287 -0
- package/dist/src/cloud-D7Ifb-Fl.js +599 -0
- package/dist/src/cloud-DB5oK5NX.cjs +666 -0
- package/dist/src/cloud-ecu989Em.js +657 -0
- package/dist/src/cloud-ramjGURF.js +599 -0
- package/dist/src/cloudflare-ai-BfDkIjO8.js +133 -0
- package/dist/src/cloudflare-ai-D9HaXz1M.js +134 -0
- package/dist/src/cloudflare-ai-HrD5WUK8.js +132 -0
- package/dist/src/cloudflare-ai-Qdj8aKP2.cjs +133 -0
- package/dist/src/cloudflare-gateway-C81uKETQ.js +276 -0
- package/dist/src/cloudflare-gateway-CX5Z9X0k.js +276 -0
- package/dist/src/cloudflare-gateway-DW-og8gb.js +277 -0
- package/dist/src/cloudflare-gateway-iRyXo9n2.cjs +276 -0
- package/dist/src/codex-app-server-BFIrSgdy.js +2155 -0
- package/dist/src/codex-app-server-By1eDVD4.js +2 -0
- package/dist/src/codex-app-server-DKsF4qmY.js +2156 -0
- package/dist/src/codex-app-server-n7n4uZzC.cjs +2162 -0
- package/dist/src/codex-app-server-xAoELVxu.js +2155 -0
- package/dist/src/codex-sdk-C2ZLxa6r.js +1552 -0
- package/dist/src/codex-sdk-CzG02tQt.cjs +1588 -0
- package/dist/src/codex-sdk-DNxAOhiV.js +2 -0
- package/dist/src/codex-sdk-DT3aQezK.js +1557 -0
- package/dist/src/codex-sdk-pw9DpcJP.js +1557 -0
- package/dist/src/codex-security-B0bLmXJF.js +406 -0
- package/dist/src/codex-security-BhYs-3iY.js +406 -0
- package/dist/src/codex-security-DQcOfxYW.js +407 -0
- package/dist/src/codex-security-DsCWr6GZ.cjs +411 -0
- package/dist/src/cometapi-B16asPLX.cjs +55 -0
- package/dist/src/cometapi-MgTbZA_H.js +53 -0
- package/dist/src/cometapi-i33vKzPV.js +55 -0
- package/dist/src/cometapi-wK2UWK0X.js +56 -0
- package/dist/src/compatible-COj8ZCy9.js +24 -0
- package/dist/src/compatible-CRSsIUGb.cjs +24 -0
- package/dist/src/compatible-Dy1vCcNF.js +25 -0
- package/dist/src/compatible-aUItQrpk.js +24 -0
- package/dist/src/completion-Bn7COFMk.js +119 -0
- package/dist/src/completion-Bub2N48b.js +118 -0
- package/dist/src/completion-Cf2G9OlM.cjs +123 -0
- package/dist/src/conversationScoring-BiTYJ9MD.js +374 -0
- package/dist/src/conversationScoring-CKL47uIu.js +373 -0
- package/dist/src/conversationScoring-DCvQKp6k.cjs +398 -0
- package/dist/src/conversationScoring-DLNJtDZI.js +373 -0
- package/dist/src/crescendo-5iLk9WiJ.cjs +734 -0
- package/dist/src/crescendo-B5ylG7kW.js +733 -0
- package/dist/src/crescendo-BD7k6TIx.js +730 -0
- package/dist/src/crescendo-DqO2Ch0P.js +732 -0
- package/dist/src/custom-8rv_aG2K.js +617 -0
- package/dist/src/custom-BOtrIHFN.js +619 -0
- package/dist/src/custom-BvN8seCs.cjs +620 -0
- package/dist/src/custom-Cld9v_Y4.js +618 -0
- package/dist/src/dataUrl-BdHUey2l.cjs +3187 -0
- package/dist/src/dataUrl-DBMifX6C.js +3133 -0
- package/dist/src/dataUrl-DUSr-ZvI.js +2868 -0
- package/dist/src/decisions-CLazADTw.js +516 -0
- package/dist/src/decisions-D5X93awq.js +515 -0
- package/dist/src/decisions-DmaeArEn.js +515 -0
- package/dist/src/decisions-DyQJyHJz.cjs +514 -0
- package/dist/src/docker-C9NYQFeu.js +94 -0
- package/dist/src/docker-CGq3mMol.cjs +94 -0
- package/dist/src/docker-DOm7nmpl.js +95 -0
- package/dist/src/docker-skFN-Kfo.js +93 -0
- package/dist/src/embedding-0UbzkTk9.js +82 -0
- package/dist/src/embedding-DTrSDt7k.cjs +86 -0
- package/dist/src/embedding-j2ORNl5H.js +81 -0
- package/dist/src/envoy-BvS8XTQO.js +60 -0
- package/dist/src/envoy-Cn6Hzw0e.js +60 -0
- package/dist/src/envoy-DC3KWcUY.cjs +60 -0
- package/dist/src/envoy-DetHjo5B.js +61 -0
- package/dist/src/eval-Cer9dPe9.js +1920 -0
- package/dist/src/eval-CytYmI2Z.js +2 -0
- package/dist/src/evalResult-DzOq5wt9.js +1300 -0
- package/dist/src/evaluator-BxCmvGtv.js +10578 -0
- package/dist/src/evaluator-Ct7YDELm.js +2 -0
- package/dist/src/evaluatorHelpers-B_AwIrsl.js +600 -0
- package/dist/src/evaluatorHelpers-D1Tpc7gd.js +601 -0
- package/dist/src/evaluatorHelpers-DRR3rLq0.cjs +622 -0
- package/dist/src/fetch-B5KxZuKu.js +1559 -0
- package/dist/src/fetch-BG_Jl7ty.js +1556 -0
- package/dist/src/fetch-BKlgUg08.cjs +1853 -0
- package/dist/src/fetch-C9Fsja0R.js +2 -0
- package/dist/src/fetch-CM7P8KWA.cjs +14 -0
- package/dist/src/fetch-D0FkIB3G.js +9 -0
- package/dist/src/fetch-RXHsZF-J.js +1280 -0
- package/dist/src/fetch-rSECy8jR.js +10 -0
- package/dist/src/functionCallbackUtils-BB9tmf6a.cjs +262 -0
- package/dist/src/functionCallbackUtils-BXk2iY01.js +246 -0
- package/dist/src/functionCallbackUtils-B_cYp7P5.js +245 -0
- package/dist/src/functionCallbackUtils-BfXnPo0o.js +245 -0
- package/dist/src/gemini-image-BXLMADDz.js +471 -0
- package/dist/src/gemini-image-BYUZyEUx.js +472 -0
- package/dist/src/gemini-image-DSt1QubZ.cjs +471 -0
- package/dist/src/gemini-image-DdNDMiZ_.js +471 -0
- package/dist/src/goat-9b-uU_k6.js +514 -0
- package/dist/src/goat-BCJuiDd0.js +515 -0
- package/dist/src/goat-CmAHbemm.js +512 -0
- package/dist/src/goat-DdOTdyoS.cjs +515 -0
- package/dist/src/goblin-Bp5C5lyb.js +22 -0
- package/dist/src/goblin-Dmr7GItI.js +23 -0
- package/dist/src/goblin-DpM8wxlf.cjs +22 -0
- package/dist/src/goblin-cJyH6Pq-.js +22 -0
- package/dist/src/google-B6eaPAbE.js +142 -0
- package/dist/src/google-D-FStdN6.cjs +142 -0
- package/dist/src/google-DAC7BsCW.js +142 -0
- package/dist/src/google-Id18H0Va.js +143 -0
- package/dist/src/graders-BjNQWkaB.js +2 -0
- package/dist/src/graders-CqdIp_vl.js +15470 -0
- package/dist/src/hydra-6Ouh74DE.js +610 -0
- package/dist/src/hydra-BHjhZnLB.cjs +612 -0
- package/dist/src/hydra-BL6k2REV.js +2 -0
- package/dist/src/hydra-BWUc0o67.js +613 -0
- package/dist/src/hydra-CUkEOLKw.js +612 -0
- package/dist/src/image-B6hG_xhb.js +481 -0
- package/dist/src/image-BFaq7Krd.cjs +209 -0
- package/dist/src/image-Bql5C0N9.cjs +504 -0
- package/dist/src/image-BtZfI2pT.js +163 -0
- package/dist/src/image-CIM4oN7Z.cjs +163 -0
- package/dist/src/image-CbAl7Jpu.js +209 -0
- package/dist/src/image-CiYm_yFw.js +209 -0
- package/dist/src/image-DCMNvBiV.js +163 -0
- package/dist/src/image-DL7pIuUZ.js +210 -0
- package/dist/src/image-ey0kxF8o.js +164 -0
- package/dist/src/image-smgIk3rE.js +482 -0
- package/dist/src/index.cjs +27 -27
- package/dist/src/index.d.cts +8 -8
- package/dist/src/index.js +27 -27
- package/dist/src/indirectWebPwn-B_-UpWY5.js +285 -0
- package/dist/src/indirectWebPwn-Cz3SLiEq.js +434 -0
- package/dist/src/indirectWebPwn-D2s8zGiM.cjs +463 -0
- package/dist/src/indirectWebPwn-DXbj2wGu.cjs +285 -0
- package/dist/src/indirectWebPwn-D_4H44E6.js +285 -0
- package/dist/src/indirectWebPwn-L044SrpV.js +434 -0
- package/dist/src/indirectWebPwn-cnmvdavH.js +435 -0
- package/dist/src/indirectWebPwn-zUBzsqTt.js +286 -0
- package/dist/src/interactions-Bu3oVQ-j.js +850 -0
- package/dist/src/interactions-CND010Lh.cjs +850 -0
- package/dist/src/interactions-DAx7tqUz.js +851 -0
- package/dist/src/interactions-DPkIumeh.js +850 -0
- package/dist/src/iterative-BO4JRnpG.js +545 -0
- package/dist/src/iterative-CAK-k9rz.js +548 -0
- package/dist/src/iterative-CDgHc0xO.cjs +549 -0
- package/dist/src/iterative-CXJlHLl9.js +547 -0
- package/dist/src/iterativeImage-BEdGKSmh.cjs +419 -0
- package/dist/src/iterativeImage-BfL0QZw5.js +417 -0
- package/dist/src/iterativeImage-C9KhnibC.js +417 -0
- package/dist/src/iterativeImage-btjkOfWG.js +418 -0
- package/dist/src/iterativeMeta-B5Bdw6QA.js +437 -0
- package/dist/src/iterativeMeta-C3mI4gpT.js +440 -0
- package/dist/src/iterativeMeta-Co2BKyqS.cjs +439 -0
- package/dist/src/iterativeMeta-DD8ihRWD.js +439 -0
- package/dist/src/iterativeTree-AMi4GV2O.js +878 -0
- package/dist/src/iterativeTree-C8FJOEje.cjs +879 -0
- package/dist/src/iterativeTree-CvrY1f2Z.js +877 -0
- package/dist/src/iterativeTree-bPtESmaD.js +876 -0
- package/dist/src/knowledgeBase-Cf5871e3.js +163 -0
- package/dist/src/knowledgeBase-D2PQhqLH.js +164 -0
- package/dist/src/knowledgeBase-DpoMw1IH.cjs +163 -0
- package/dist/src/knowledgeBase-npGFl763.js +163 -0
- package/dist/src/litellm-BBB5DQdt.cjs +146 -0
- package/dist/src/litellm-Bo43ow7r.js +145 -0
- package/dist/src/litellm-CaU8CMLS.js +146 -0
- package/dist/src/litellm-wY7Unh8o.js +147 -0
- package/dist/src/live-5g2w-M-E.js +891 -0
- package/dist/src/live-BfaXsDyD.cjs +891 -0
- package/dist/src/live-C1xewnGD.js +2 -0
- package/dist/src/live-DaF7nYy5.js +892 -0
- package/dist/src/live-lp3urLUw.js +891 -0
- package/dist/src/luma-ray-B7zvKGVG.js +309 -0
- package/dist/src/luma-ray-DCf5fnrz.cjs +309 -0
- package/dist/src/luma-ray-DepBcn6z.js +309 -0
- package/dist/src/luma-ray-XQC4M1pt.js +310 -0
- package/dist/src/main.js +26 -26
- package/dist/src/mantleChat-7xm95vSV.js +154 -0
- package/dist/src/mantleChat-CXhAs5RD.js +155 -0
- package/dist/src/mantleChat-CcE-zjfj.cjs +154 -0
- package/dist/src/mantleChat-Cpefl7Zm.js +154 -0
- package/dist/src/mcp-B0V0ikdM.js +84 -0
- package/dist/src/mcp-CV2k2gwj.js +85 -0
- package/dist/src/memoryPoisoning-BC5FQQWZ.js +111 -0
- package/dist/src/memoryPoisoning-BDwrtZKX.js +111 -0
- package/dist/src/memoryPoisoning-BFemS_FF.js +112 -0
- package/dist/src/memoryPoisoning-DRs2rbVV.cjs +111 -0
- package/dist/src/messages-Bc5oZoAJ.js +1128 -0
- package/dist/src/messages-BkaH8fRW.js +1127 -0
- package/dist/src/messages-CoHlziS5.js +1127 -0
- package/dist/src/messages-Cv_m6kYs.cjs +1161 -0
- package/dist/src/mischievousUser-BcyFxrqJ.js +51 -0
- package/dist/src/mischievousUser-BlhOQSd2.js +52 -0
- package/dist/src/mischievousUser-BuQiKE8D.js +51 -0
- package/dist/src/mischievousUser-ChIOk6cT.cjs +51 -0
- package/dist/src/modelslab-BXIWBTgX.js +171 -0
- package/dist/src/modelslab-ChVsUiaJ.js +170 -0
- package/dist/src/modelslab-DZ6BFlDv.js +170 -0
- package/dist/src/modelslab-DhRr-vyo.cjs +170 -0
- package/dist/src/nova-reel-BL8DrN4_.js +272 -0
- package/dist/src/nova-reel-BiOMUm5q.cjs +272 -0
- package/dist/src/nova-reel-CTsya1hV.js +273 -0
- package/dist/src/nova-reel-kgBY4Svd.js +272 -0
- package/dist/src/nova-sonic-CaSSA3Jq.cjs +374 -0
- package/dist/src/nova-sonic-DLpmoGsR.js +375 -0
- package/dist/src/nova-sonic-DwWc4SoN.js +374 -0
- package/dist/src/nova-sonic-qnReTaXm.js +374 -0
- package/dist/src/novita-B5mAt3Ui.js +114 -0
- package/dist/src/novita-D57vCjDD.js +116 -0
- package/dist/src/novita-ITRtG8IJ.js +115 -0
- package/dist/src/novita-Rh3T13YO.cjs +115 -0
- package/dist/src/nscale-8V7iZ_pI.js +210 -0
- package/dist/src/nscale-BQnMv4pH.cjs +209 -0
- package/dist/src/nscale-BWZXHZVF.js +209 -0
- package/dist/src/nscale-BqrHiUqU.js +207 -0
- package/dist/src/openaiResponses-BMtGTu8R.js +317 -0
- package/dist/src/openaiResponses-CvcI_viE.js +318 -0
- package/dist/src/openaiResponses-DYPZEMX1.cjs +318 -0
- package/dist/src/openaiResponses-DZTg1-kb.js +319 -0
- package/dist/src/openclaw-BeKuig4g.js +1338 -0
- package/dist/src/openclaw-COkdQ83y.js +1337 -0
- package/dist/src/openclaw-CSoX_HQ5.cjs +1344 -0
- package/dist/src/openclaw-DJlhPGCb.js +1336 -0
- package/dist/src/opencode-sdk-BEJftEs6.cjs +1018 -0
- package/dist/src/opencode-sdk-DMvBB3V7.js +1013 -0
- package/dist/src/opencode-sdk-Df7hMjLO.js +1012 -0
- package/dist/src/opencode-sdk-bQp5Xf3W.js +1012 -0
- package/dist/src/openinterpreter-B3GgVZjK.js +431 -0
- package/dist/src/openinterpreter-BiGcU-HN.cjs +435 -0
- package/dist/src/openinterpreter-Buj2l3Eh.js +432 -0
- package/dist/src/openinterpreter-C3_Cg5b_.js +431 -0
- package/dist/src/pricing-0Pampf0q.cjs +999 -0
- package/dist/src/pricing-B8VdhEhY.js +976 -0
- package/dist/src/pricing-CtLA-rKA.js +976 -0
- package/dist/src/promptfoo-4OkHtH9P.cjs +341 -0
- package/dist/src/promptfoo-Bhpm7sH6.js +286 -0
- package/dist/src/promptfoo-BqV8ogVA.js +285 -0
- package/dist/src/promptfoo-S1Q9OHk_.js +286 -0
- package/dist/src/providers-B5zs1ZRv.js +24437 -0
- package/dist/src/providers-Cd6CJh6m.js +2 -0
- package/dist/src/providers-CpJlgHET.js +24039 -0
- package/dist/src/providers-CzvLvK6G.cjs +24180 -0
- package/dist/src/quiverai-1E_IvLHn.js +325 -0
- package/dist/src/quiverai-BXH004Vv.js +325 -0
- package/dist/src/quiverai-Ccya2z8Y.cjs +325 -0
- package/dist/src/quiverai-Cez57oe-.js +326 -0
- package/dist/src/registry-3zX_M9Ik.js +131 -0
- package/dist/src/registry-AuCrKTvS.js +132 -0
- package/dist/src/registry-CxXWKtQG.js +131 -0
- package/dist/src/registry-DG3o66JQ.cjs +131 -0
- package/dist/src/remoteGeneration-CAtvamG6.js +370 -0
- package/dist/src/remoteGeneration-CF225pDl.cjs +482 -0
- package/dist/src/remoteGeneration-DtnqocnL.js +370 -0
- package/dist/src/remoteGeneration-g3KvW-sP.js +371 -0
- package/dist/src/responses-BMbaUXQI.js +1098 -0
- package/dist/src/responses-B_TOSof-.js +1099 -0
- package/dist/src/responses-v-yANwTA.cjs +1109 -0
- package/dist/src/runtimeTransform-BBZv-oUZ.js +156 -0
- package/dist/src/runtimeTransform-DT2v5ovW.js +156 -0
- package/dist/src/runtimeTransform-GXXEIXdS.cjs +161 -0
- package/dist/src/runtimeTransform-JTwBQc-P.js +157 -0
- package/dist/src/sagemaker-B8D0L4rj.cjs +716 -0
- package/dist/src/sagemaker-CR2_AGdB.js +713 -0
- package/dist/src/sagemaker-Cd9qSQUV.js +714 -0
- package/dist/src/sagemaker-mKlltN4p.js +713 -0
- package/dist/src/scanner-PG_8lh8r.js +1971 -0
- package/dist/src/server/index.js +55 -55
- package/dist/src/server-Bmh7sd9F.js +155 -0
- package/dist/src/server-C7b8z6aC.js +63 -0
- package/dist/src/server-CAcovgtL.js +2 -0
- package/dist/src/server-CuuMfKlh.cjs +74 -0
- package/dist/src/server-DMPCj9jy.js +189 -0
- package/dist/src/session-BksXvRH_.cjs +69 -0
- package/dist/src/session-DOxUjqGQ.js +63 -0
- package/dist/src/session-Dujsc-b9.js +62 -0
- package/dist/src/session-VjtIxREd.js +62 -0
- package/dist/src/shared-Bkyz_7e5.cjs +2185 -0
- package/dist/src/shared-DDJg8ycC.js +1929 -0
- package/dist/src/shared-Dh3yfRBd.js +1927 -0
- package/dist/src/shared-tfPT8Tna.js +1928 -0
- package/dist/src/simulatedUser-6JdkyL3k.cjs +252 -0
- package/dist/src/simulatedUser-CFr2mr3M.js +248 -0
- package/dist/src/simulatedUser-DjwwUqx-.js +247 -0
- package/dist/src/slack-C_gIYiUs.js +144 -0
- package/dist/src/slack-DhNbz9CM.cjs +144 -0
- package/dist/src/slack-Dm2iI1zu.js +145 -0
- package/dist/src/strategies-BIY-bNul.js +2248 -0
- package/dist/src/strategies-C1KQQj9G.cjs +2420 -0
- package/dist/src/strategies-DM_3mReG.js +2385 -0
- package/dist/src/telemetry-BhMTibZO.js +2 -0
- package/dist/src/telemetry-C04d25BM.cjs +216 -0
- package/dist/src/telemetry-CIqy4fSC.js +201 -0
- package/dist/src/telemetry-CXozp_6C.js +205 -0
- package/dist/src/telemetry-g7PkBxmY.js +205 -0
- package/dist/src/togetherai-BvCim68-.js +50 -0
- package/dist/src/togetherai-CWyDCA9m.cjs +49 -0
- package/dist/src/togetherai-CeSE31vK.js +49 -0
- package/dist/src/togetherai-_2W0URf8.js +48 -0
- package/dist/src/traceContext-Brw3Oe41.js +1016 -0
- package/dist/src/traceContext-DpAYv27G.js +1015 -0
- package/dist/src/traceContext-KSqhzZI2.cjs +1032 -0
- package/dist/src/transcription-BySopazW.js +175 -0
- package/dist/src/transcription-DO4UPkRI.cjs +178 -0
- package/dist/src/transcription-RJGBa-pC.js +176 -0
- package/dist/src/transcription-fZenF3G5.js +175 -0
- package/dist/src/transform-BzhRc5z2.js +125 -0
- package/dist/src/transform-CPQu05u6.cjs +154 -0
- package/dist/src/transform-DAED8imp.js +126 -0
- package/dist/src/transform-DIOIQDmM.js +125 -0
- package/dist/src/typesafe-ByE0Kxfg.js +253 -0
- package/dist/src/typesafe-CFqGFY34.js +253 -0
- package/dist/src/typesafe-DCWIw-CP.cjs +253 -0
- package/dist/src/typesafe-DyHFV5Qk.js +254 -0
- package/dist/src/util-BHkj9joz.js +2049 -0
- package/dist/src/util-CICwIpmu.cjs +934 -0
- package/dist/src/util-CePiY2xZ.js +286 -0
- package/dist/src/util-CgT3uf4p.js +743 -0
- package/dist/src/util-Cj9drvOY.js +1770 -0
- package/dist/src/util-ClJRjlQA.cjs +357 -0
- package/dist/src/util-Cxf8VF2M.js +395 -0
- package/dist/src/util-D7RdV7rS.js +395 -0
- package/dist/src/util-DMNFhk47.js +351 -0
- package/dist/src/util-DNzh3M0z.js +396 -0
- package/dist/src/util-Df7rfMGb.cjs +2305 -0
- package/dist/src/util-Kf0KnG_6.js +2051 -0
- package/dist/src/util-LEbeiYw_.js +743 -0
- package/dist/src/util-WH8CgVs4.js +352 -0
- package/dist/src/util-cx6Xw8Lw.cjs +478 -0
- package/dist/src/util-qzBqirBH.js +2050 -0
- package/dist/src/vertex-CBAMfRz3.js +854 -0
- package/dist/src/vertex-CMP2IpN9.js +2 -0
- package/dist/src/vertex-CZ5YOotT.js +848 -0
- package/dist/src/vertex-DNsh1F1M.cjs +871 -0
- package/dist/src/vertexLive-BTXYj3-F.js +55 -0
- package/dist/src/vertexLive-Ba_LAqEF.cjs +55 -0
- package/dist/src/vertexLive-DM4sFaaj.js +56 -0
- package/dist/src/vertexLive-JqZOw7HC.js +55 -0
- package/dist/src/video-BY7Q2Gii.cjs +706 -0
- package/dist/src/video-CYElP-CK.js +703 -0
- package/dist/src/video-C_AdEDH0.js +702 -0
- package/dist/src/video-DGvjQ_4j.js +702 -0
- package/package.json +1 -1
- package/dist/src/accounts-Dpb43yde.cjs +0 -276
- package/dist/src/accounts-GKrO1olH.js +0 -229
- package/dist/src/accounts-e4FGOsji.js +0 -227
- package/dist/src/accounts-sUiEJfkB.js +0 -222
- package/dist/src/agentWorkspace-B8A_wuMR.cjs +0 -619
- package/dist/src/agentWorkspace-DSPIscXR.js +0 -593
- package/dist/src/agentWorkspace-DxUqd-XK.js +0 -592
- package/dist/src/agentWorkspace-n0uOJXhD.js +0 -592
- package/dist/src/agentic-utils-9bCj4twQ.js +0 -197
- package/dist/src/agentic-utils-CyCLuLoj.js +0 -197
- package/dist/src/agentic-utils-D23qtOlx.cjs +0 -237
- package/dist/src/agentic-utils-DuBMMNCw.js +0 -198
- package/dist/src/agents-6hDRNoYD.js +0 -777
- package/dist/src/agents-B8w2o7Sc.cjs +0 -777
- package/dist/src/agents-Ck0NXl7v.js +0 -777
- package/dist/src/agents-CwT3B1qB.js +0 -778
- package/dist/src/agents-DOLjfOEq.js +0 -266
- package/dist/src/agents-OcF9hq--.js +0 -267
- package/dist/src/agents-api-CnZZt8bn.cjs +0 -710
- package/dist/src/agents-api-D04u3bmL.js +0 -711
- package/dist/src/agents-api-DWw0_Vio.js +0 -710
- package/dist/src/agents-api-IWHEwp8i.js +0 -710
- package/dist/src/agents-mHt2Mh9O.cjs +0 -266
- package/dist/src/agents-sICccZCA.js +0 -266
- package/dist/src/ai.studio-Ci4rypDT.js +0 -2
- package/dist/src/ai.studio-KkQ6KaHa.js +0 -369
- package/dist/src/ai.studio-gSXK2cGI.js +0 -374
- package/dist/src/ai.studio-nQF_B4DH.cjs +0 -391
- package/dist/src/aimlapi-BeSk5BDV.js +0 -30
- package/dist/src/aimlapi-CzNUhdKu.cjs +0 -29
- package/dist/src/aimlapi-DCkazDPI.js +0 -29
- package/dist/src/aimlapi-WeH5B6K1.js +0 -28
- package/dist/src/anthropicMessages-AcNWTpYO.js +0 -115
- package/dist/src/anthropicMessages-BUtvzbpL.js +0 -114
- package/dist/src/anthropicMessages-DTWhZDCd.js +0 -114
- package/dist/src/anthropicMessages-lGVnSgyx.cjs +0 -114
- package/dist/src/app/assets/index-CyEI5aDN.js +0 -392
- package/dist/src/audio-BE_Duiu1.js +0 -104
- package/dist/src/audio-CiUd00k2.cjs +0 -104
- package/dist/src/audio-Dop6omna.js +0 -105
- package/dist/src/audio-EZNTInr_.js +0 -104
- package/dist/src/authoritativeMarkupInjection-BUqH6hNk.js +0 -78
- package/dist/src/authoritativeMarkupInjection-BmbJdJO0.cjs +0 -78
- package/dist/src/authoritativeMarkupInjection-Cpz12Y3w.js +0 -78
- package/dist/src/authoritativeMarkupInjection-W4XfcH91.js +0 -79
- package/dist/src/aws-B2Jqbnet.js +0 -2433
- package/dist/src/aws-DHtuUIzQ.js +0 -1149
- package/dist/src/aws-DLqXP6wY.js +0 -2433
- package/dist/src/aws-DfduhmwL.cjs +0 -2454
- package/dist/src/base-B9L2Xvpc.js +0 -255
- package/dist/src/base-BTZnIsuH.cjs +0 -305
- package/dist/src/base-BhaWNQPJ.js +0 -462
- package/dist/src/base-Br-G_Xou.js +0 -256
- package/dist/src/base-Bzo8hiUS.cjs +0 -467
- package/dist/src/base-C82fd2jq.js +0 -463
- package/dist/src/base-CRdQwC1W.js +0 -462
- package/dist/src/base-CjGwZNOQ.js +0 -255
- package/dist/src/bedrock-BdMru_ro.js +0 -1300
- package/dist/src/bedrock-CBUmfLX1.cjs +0 -2
- package/dist/src/bedrock-DBDxBaF9.js +0 -2
- package/dist/src/bedrock-DDrECM21.js +0 -1
- package/dist/src/bedrock-DVwkgvRS.js +0 -1
- package/dist/src/bestOfN-AKF5beq4.js +0 -159
- package/dist/src/bestOfN-C1UIVGJV.js +0 -160
- package/dist/src/bestOfN-DlkETbXy.cjs +0 -161
- package/dist/src/bestOfN-XIfEgU-g.js +0 -159
- package/dist/src/cache-BZaVoKaA.js +0 -2
- package/dist/src/cache-CEYhFUsH.js +0 -741
- package/dist/src/cache-Cbw1zH6q.js +0 -782
- package/dist/src/cache-CdaZNb75.js +0 -754
- package/dist/src/cache-DpuIzPxh.cjs +0 -856
- package/dist/src/cerebras-Bpn6FPkJ.js +0 -97
- package/dist/src/cerebras-CqJ0BRCJ.cjs +0 -97
- package/dist/src/cerebras-D4ILa_TY.js +0 -97
- package/dist/src/cerebras-DR8uc7ee.js +0 -98
- package/dist/src/chat-B7PZfaYp.cjs +0 -987
- package/dist/src/chat-BVuSjdEb.js +0 -227
- package/dist/src/chat-BsaZRjXN.js +0 -76
- package/dist/src/chat-C5liqe3Y.js +0 -226
- package/dist/src/chat-C9hyHf5B.js +0 -124
- package/dist/src/chat-CFLalAck.js +0 -226
- package/dist/src/chat-CN8JGrHu.js +0 -76
- package/dist/src/chat-CaHBBpCb.js +0 -123
- package/dist/src/chat-CcbLSghx.js +0 -123
- package/dist/src/chat-CoSN6sr2.js +0 -934
- package/dist/src/chat-CsJRFX8a.cjs +0 -226
- package/dist/src/chat-DFoZLvO_.js +0 -934
- package/dist/src/chat-DiLQvL7r.js +0 -77
- package/dist/src/chat-F6qVSDk3.cjs +0 -123
- package/dist/src/chat-Oq4FaJgI.cjs +0 -76
- package/dist/src/chat-knMfQUKz.js +0 -935
- package/dist/src/claude-agent-sdk-CJkOLpnI.js +0 -999
- package/dist/src/claude-agent-sdk-Ckn76PRD.js +0 -999
- package/dist/src/claude-agent-sdk-DX0gTr11.cjs +0 -1005
- package/dist/src/claude-agent-sdk-LMeikxoR.js +0 -1000
- package/dist/src/client-BFf1r6Z8.js +0 -352
- package/dist/src/client-CdXyDdDi.js +0 -351
- package/dist/src/client-DV8XMu7i.js +0 -351
- package/dist/src/client-iEXtOBKW.cjs +0 -357
- package/dist/src/cloud-B02qcpjf.js +0 -2
- package/dist/src/cloud-BlHP-g1v.cjs +0 -666
- package/dist/src/cloud-C9BI4isF.js +0 -287
- package/dist/src/cloud-CTTLNdvj.js +0 -657
- package/dist/src/cloud-D5X5yQ_d.js +0 -599
- package/dist/src/cloud-QxPkpsHA.js +0 -599
- package/dist/src/cloudflare-ai-DRTRT1fc.js +0 -132
- package/dist/src/cloudflare-ai-DgaXapAV.cjs +0 -133
- package/dist/src/cloudflare-ai-DkuJXijS.js +0 -134
- package/dist/src/cloudflare-ai-wy9QCHku.js +0 -133
- package/dist/src/cloudflare-gateway-9cAN8g29.cjs +0 -276
- package/dist/src/cloudflare-gateway-BVFMD292.js +0 -277
- package/dist/src/cloudflare-gateway-BuUI4p6I.js +0 -276
- package/dist/src/cloudflare-gateway-TlYHizbW.js +0 -276
- package/dist/src/codex-app-server-BPz_feug.cjs +0 -2162
- package/dist/src/codex-app-server-C9noXM9C.js +0 -2155
- package/dist/src/codex-app-server-CEmD-Y5U.js +0 -2
- package/dist/src/codex-app-server-DZolc18r.js +0 -2156
- package/dist/src/codex-app-server-Dd0A37nO.js +0 -2155
- package/dist/src/codex-sdk-BbxjBvBk.cjs +0 -1588
- package/dist/src/codex-sdk-BpXeIs-_.js +0 -1557
- package/dist/src/codex-sdk-BtQp5X0f.js +0 -1552
- package/dist/src/codex-sdk-CH0v9Bk1.js +0 -2
- package/dist/src/codex-sdk-CgrN7JB8.js +0 -1557
- package/dist/src/codex-security-B5fENNUr.js +0 -406
- package/dist/src/codex-security-C6uuJx-y.cjs +0 -411
- package/dist/src/codex-security-CifWtZR_.js +0 -407
- package/dist/src/codex-security-Kg2bOEKy.js +0 -406
- package/dist/src/cometapi-BFpIDLIx.js +0 -55
- package/dist/src/cometapi-C6O2PIrN.js +0 -56
- package/dist/src/cometapi-D5Yupc6F.js +0 -53
- package/dist/src/cometapi-DzgIwJzJ.cjs +0 -55
- package/dist/src/compatible-0jhmVfOp.js +0 -25
- package/dist/src/compatible-DdtwWdJi.cjs +0 -24
- package/dist/src/compatible-Di4nR3sU.js +0 -24
- package/dist/src/compatible-iJKLWdnf.js +0 -24
- package/dist/src/completion-B0_hVUDG.js +0 -119
- package/dist/src/completion-BdI6v0-Q.cjs +0 -123
- package/dist/src/completion-CWcJscwv.js +0 -118
- package/dist/src/conversationScoring-99EOPJRa.js +0 -373
- package/dist/src/conversationScoring-BIq4J0Cq.js +0 -374
- package/dist/src/conversationScoring-DARyeATr.cjs +0 -398
- package/dist/src/conversationScoring-DS48t4Hb.js +0 -373
- package/dist/src/crescendo-CebvXIu4.js +0 -730
- package/dist/src/crescendo-CxrLS0oo.js +0 -732
- package/dist/src/crescendo-DZQXBSkj.js +0 -733
- package/dist/src/crescendo-wjEx68uD.cjs +0 -734
- package/dist/src/custom-BiQ-aUNw.cjs +0 -620
- package/dist/src/custom-ByyB5Z93.js +0 -619
- package/dist/src/custom-C5jOevNb.js +0 -617
- package/dist/src/custom-CCrsCz8o.js +0 -618
- package/dist/src/dataUrl-C9J7wz9H.js +0 -3133
- package/dist/src/dataUrl-CGsBT7UZ.cjs +0 -3187
- package/dist/src/dataUrl-CzKvvWNO.js +0 -2868
- package/dist/src/decisions-BTusXCUx.cjs +0 -514
- package/dist/src/decisions-BYtL9edD.js +0 -515
- package/dist/src/decisions-jYix_gCF.js +0 -515
- package/dist/src/decisions-nxxfHRAN.js +0 -516
- package/dist/src/docker-DDIv4zkg.js +0 -93
- package/dist/src/docker-DVLp_5OG.js +0 -94
- package/dist/src/docker-INm9w0SY.cjs +0 -94
- package/dist/src/docker-sGuoCul_.js +0 -95
- package/dist/src/embedding-CAhqLLrR.js +0 -82
- package/dist/src/embedding-D94GAsti.cjs +0 -86
- package/dist/src/embedding-zb4MAzQy.js +0 -81
- package/dist/src/envoy-BMPszwEa.cjs +0 -60
- package/dist/src/envoy-Bp-s39_8.js +0 -60
- package/dist/src/envoy-BswDt-Ou.js +0 -61
- package/dist/src/envoy-rVbYcV80.js +0 -60
- package/dist/src/eval-B1-XfrC7.js +0 -2
- package/dist/src/eval-pC4qCvLw.js +0 -1920
- package/dist/src/evalResult-CzjCb5bd.js +0 -1300
- package/dist/src/evaluator-CNq2K7J_.js +0 -10578
- package/dist/src/evaluator-LtfxdxEu.js +0 -2
- package/dist/src/evaluatorHelpers-C5J0NYpQ.js +0 -601
- package/dist/src/evaluatorHelpers-DcdCglCs.cjs +0 -622
- package/dist/src/evaluatorHelpers-Rvb88W6B.js +0 -600
- package/dist/src/fetch-5HtnNhHg.js +0 -1556
- package/dist/src/fetch-BCwjoIFd.js +0 -1559
- package/dist/src/fetch-BhfUnKen.js +0 -1280
- package/dist/src/fetch-C08w4vVl.js +0 -9
- package/dist/src/fetch-DBxy8Tlb.cjs +0 -14
- package/dist/src/fetch-DYte6oQX.cjs +0 -1853
- package/dist/src/fetch-ElpfcAVG.js +0 -10
- package/dist/src/fetch-lM1OIaSt.js +0 -2
- package/dist/src/functionCallbackUtils-BCAdWfHO.js +0 -246
- package/dist/src/functionCallbackUtils-BYq9qOhG.js +0 -245
- package/dist/src/functionCallbackUtils-ByWkmVud.cjs +0 -262
- package/dist/src/functionCallbackUtils-D_C_JaFd.js +0 -245
- package/dist/src/gemini-image-CAlwaJhZ.js +0 -471
- package/dist/src/gemini-image-DJoVoOnZ.cjs +0 -471
- package/dist/src/gemini-image-Waio-9Xx.js +0 -472
- package/dist/src/gemini-image-vbY6Ftbf.js +0 -471
- package/dist/src/goat-BWbtyY9c.js +0 -512
- package/dist/src/goat-CXzzeCOQ.cjs +0 -515
- package/dist/src/goat-CfgvzSgZ.js +0 -514
- package/dist/src/goat-DLeoIHBp.js +0 -515
- package/dist/src/goblin-CmfCfwqk.cjs +0 -22
- package/dist/src/goblin-CtcaORRH.js +0 -22
- package/dist/src/goblin-DF6DDhM-.js +0 -22
- package/dist/src/goblin-Nai0xxBV.js +0 -23
- package/dist/src/google-ClpkLtKL.cjs +0 -142
- package/dist/src/google-CrFgKu9k.js +0 -143
- package/dist/src/google-Dj_EIBqS.js +0 -142
- package/dist/src/google-e4-vARv6.js +0 -142
- package/dist/src/graders-BN1IIa71.js +0 -15470
- package/dist/src/graders-C5sCfSP5.js +0 -2
- package/dist/src/hydra-B7RfXVBK.js +0 -2
- package/dist/src/hydra-C1cFN-Jg.js +0 -613
- package/dist/src/hydra-CK6Uc1ia.js +0 -612
- package/dist/src/hydra-Dg65rAP_.js +0 -610
- package/dist/src/hydra-Fqx8l_Xu.cjs +0 -612
- package/dist/src/image-BdlUDAtp.js +0 -163
- package/dist/src/image-C-KwEhwt.cjs +0 -163
- package/dist/src/image-C76fp6NK.cjs +0 -209
- package/dist/src/image-D75ehv3D.js +0 -482
- package/dist/src/image-DKtc5v5W.js +0 -209
- package/dist/src/image-DT_xOkJY.js +0 -163
- package/dist/src/image-DVpdllEE.js +0 -209
- package/dist/src/image-DXZ8AzMf.js +0 -481
- package/dist/src/image-DZl_1mvy.js +0 -164
- package/dist/src/image-DcTD7Ak0.cjs +0 -504
- package/dist/src/image-ndxEvBKB.js +0 -210
- package/dist/src/indirectWebPwn-70WA5x_q.js +0 -435
- package/dist/src/indirectWebPwn-BRVyd3qV.cjs +0 -463
- package/dist/src/indirectWebPwn-BsJVsu0q.js +0 -285
- package/dist/src/indirectWebPwn-Cw6yJu0i.js +0 -285
- package/dist/src/indirectWebPwn-D-PhJzo4.js +0 -286
- package/dist/src/indirectWebPwn-DRPHt2I8.js +0 -434
- package/dist/src/indirectWebPwn-DXtfFhd9.cjs +0 -285
- package/dist/src/indirectWebPwn-DvpNouzc.js +0 -434
- package/dist/src/interactions-5ixfW7Cl.js +0 -850
- package/dist/src/interactions-BOUzfmg1.cjs +0 -850
- package/dist/src/interactions-CSSXcGNc.js +0 -851
- package/dist/src/interactions-WB_sgkN0.js +0 -850
- package/dist/src/iterative-BShRNqjC.cjs +0 -549
- package/dist/src/iterative-BcW_ELtB.js +0 -548
- package/dist/src/iterative-BpHbHz8B.js +0 -547
- package/dist/src/iterative-YcchP12d.js +0 -545
- package/dist/src/iterativeImage-BMFE5Hl7.cjs +0 -419
- package/dist/src/iterativeImage-CkSaYLMY.js +0 -417
- package/dist/src/iterativeImage-DAEUlQX_.js +0 -418
- package/dist/src/iterativeImage-DeUSkEnj.js +0 -417
- package/dist/src/iterativeMeta-DbdaKdEO.cjs +0 -439
- package/dist/src/iterativeMeta-DcF9JWEK.js +0 -437
- package/dist/src/iterativeMeta-DkfPqWIC.js +0 -439
- package/dist/src/iterativeMeta-DkrpnVSs.js +0 -440
- package/dist/src/iterativeTree-CEMY1FhE.cjs +0 -879
- package/dist/src/iterativeTree-Cv5W4tX9.js +0 -877
- package/dist/src/iterativeTree-DGvomd3M.js +0 -876
- package/dist/src/iterativeTree-KbtC2Mkz.js +0 -878
- package/dist/src/knowledgeBase-AYRXn4wO.js +0 -163
- package/dist/src/knowledgeBase-BNqQfx01.js +0 -163
- package/dist/src/knowledgeBase-C0IaCCVs.js +0 -164
- package/dist/src/knowledgeBase-C2uj6wK4.cjs +0 -163
- package/dist/src/litellm-CN1ScAwZ.js +0 -147
- package/dist/src/litellm-CTjwiKSa.js +0 -146
- package/dist/src/litellm-Cd4Nj5ue.js +0 -145
- package/dist/src/litellm-DMqLpEBg.cjs +0 -146
- package/dist/src/live-Bt50-InO.cjs +0 -891
- package/dist/src/live-Bu2ujadG.js +0 -2
- package/dist/src/live-C3M52i3p.js +0 -891
- package/dist/src/live-CRfHMO3B.js +0 -892
- package/dist/src/live-iCIpO14m.js +0 -891
- package/dist/src/luma-ray-B8eHC4c8.cjs +0 -309
- package/dist/src/luma-ray-BIvkPw0s.js +0 -309
- package/dist/src/luma-ray-ChsiBxMA.js +0 -309
- package/dist/src/luma-ray-DAvKrInz.js +0 -310
- package/dist/src/mantleChat-5YeEXAZI.js +0 -154
- package/dist/src/mantleChat-D--mW3hl.js +0 -154
- package/dist/src/mantleChat-DHP3siNg.cjs +0 -154
- package/dist/src/mantleChat-wBfAX46o.js +0 -155
- package/dist/src/mcp-49jlEcTQ.js +0 -85
- package/dist/src/mcp-__PIz81I.js +0 -84
- package/dist/src/memoryPoisoning-Chxge74M.js +0 -111
- package/dist/src/memoryPoisoning-QH6NCUVE.js +0 -112
- package/dist/src/memoryPoisoning-tCxZt8Nz.js +0 -111
- package/dist/src/memoryPoisoning-ymrRItRR.cjs +0 -111
- package/dist/src/messages-BE_eZ7NA.js +0 -1127
- package/dist/src/messages-Bo638ShI.js +0 -1127
- package/dist/src/messages-BzR0-NQ1.js +0 -1128
- package/dist/src/messages-Cbg5Pfd0.cjs +0 -1161
- package/dist/src/mischievousUser-BtED2Z5Z.cjs +0 -51
- package/dist/src/mischievousUser-KqSOjrDJ.js +0 -51
- package/dist/src/mischievousUser-YMD41YNZ.js +0 -51
- package/dist/src/mischievousUser-zBxlNdCu.js +0 -52
- package/dist/src/modelslab-B8gZxtfE.js +0 -171
- package/dist/src/modelslab-C7bmVpTB.js +0 -170
- package/dist/src/modelslab-CCeQCTZg.js +0 -170
- package/dist/src/modelslab-CvBJGv7y.cjs +0 -170
- package/dist/src/nova-reel-BOEWsEKA.cjs +0 -272
- package/dist/src/nova-reel-BtyBXq5M.js +0 -273
- package/dist/src/nova-reel-C1eF3-EE.js +0 -272
- package/dist/src/nova-reel-YhgrxEKT.js +0 -272
- package/dist/src/nova-sonic-BaERP20w.js +0 -374
- package/dist/src/nova-sonic-CxgM3O-P.cjs +0 -374
- package/dist/src/nova-sonic-DJS22fC3.js +0 -375
- package/dist/src/nova-sonic-DwvwHyRX.js +0 -374
- package/dist/src/novita-D1l2tG0O.js +0 -116
- package/dist/src/novita-D84VM3v0.cjs +0 -115
- package/dist/src/novita-DGInvwfR.js +0 -115
- package/dist/src/novita-vXHkXhTg.js +0 -114
- package/dist/src/nscale-CU0Ldr00.js +0 -209
- package/dist/src/nscale-ClfKlQeM.cjs +0 -209
- package/dist/src/nscale-DxaVnF0x.js +0 -210
- package/dist/src/nscale-_poVxIrO.js +0 -207
- package/dist/src/openaiResponses-CJGsneNj.js +0 -317
- package/dist/src/openaiResponses-CKSl5Sdg.js +0 -319
- package/dist/src/openaiResponses-DC8rzFUc.js +0 -318
- package/dist/src/openaiResponses-rMHIA3dV.cjs +0 -318
- package/dist/src/openclaw-CCbvsNFW.cjs +0 -1344
- package/dist/src/openclaw-CZw1lCDZ.js +0 -1336
- package/dist/src/openclaw-ChFLgC-a.js +0 -1338
- package/dist/src/openclaw-DrPMoRrH.js +0 -1337
- package/dist/src/opencode-sdk-2EfIDhFp.cjs +0 -1018
- package/dist/src/opencode-sdk-CHw3F845.js +0 -1013
- package/dist/src/opencode-sdk-D0EGGxvy.js +0 -1012
- package/dist/src/opencode-sdk-jSS7NI2Q.js +0 -1012
- package/dist/src/openinterpreter-CY622xHC.js +0 -431
- package/dist/src/openinterpreter-DATyhuhP.js +0 -432
- package/dist/src/openinterpreter-DDUMyIf1.js +0 -431
- package/dist/src/openinterpreter-s5Tz6Lid.cjs +0 -435
- package/dist/src/pricing-C498twd2.js +0 -976
- package/dist/src/pricing-DBd_bMIh.cjs +0 -999
- package/dist/src/pricing-ISrMCskv.js +0 -976
- package/dist/src/promptfoo-6p0WG2ih.js +0 -286
- package/dist/src/promptfoo-BQRfgNs_.js +0 -285
- package/dist/src/promptfoo-Bqo88z20.cjs +0 -341
- package/dist/src/promptfoo-Cq5AVI3I.js +0 -286
- package/dist/src/providers-ATbeMX5E.cjs +0 -24180
- package/dist/src/providers-B7F1FiNI.js +0 -2
- package/dist/src/providers-DazIw8mI.js +0 -24039
- package/dist/src/providers-QvGlNAD0.js +0 -24437
- package/dist/src/quiverai-BPlNcLkV.cjs +0 -325
- package/dist/src/quiverai-By99-YmJ.js +0 -325
- package/dist/src/quiverai-CmmByDqo.js +0 -325
- package/dist/src/quiverai-HZkoJJqw.js +0 -326
- package/dist/src/registry-BLTnTfjT.cjs +0 -131
- package/dist/src/registry-BMC-COHT.js +0 -132
- package/dist/src/registry-C8UZtmBp.js +0 -131
- package/dist/src/registry-CfwEUYXG.js +0 -131
- package/dist/src/remoteGeneration-Bgg6kC5V.js +0 -370
- package/dist/src/remoteGeneration-CKJFE960.cjs +0 -482
- package/dist/src/remoteGeneration-DaxwJDKv.js +0 -370
- package/dist/src/remoteGeneration-vHMGVKr1.js +0 -371
- package/dist/src/responses-BvnyIHrq.js +0 -1099
- package/dist/src/responses-CERAgvf-.js +0 -1098
- package/dist/src/responses-CwgjeuOg.cjs +0 -1109
- package/dist/src/runtimeTransform-3RF9Avyg.cjs +0 -161
- package/dist/src/runtimeTransform-C51Z5j4H.js +0 -156
- package/dist/src/runtimeTransform-CKE_Iyv8.js +0 -157
- package/dist/src/runtimeTransform-Cs11xJpj.js +0 -156
- package/dist/src/sagemaker-BJ4dOCxE.js +0 -713
- package/dist/src/sagemaker-Bt3JUAWq.js +0 -714
- package/dist/src/sagemaker-QVKyLgLF.cjs +0 -716
- package/dist/src/sagemaker-l3IB8iTs.js +0 -713
- package/dist/src/scanner-DGjIiTZ1.js +0 -1971
- package/dist/src/server-BNaLZH6u.js +0 -63
- package/dist/src/server-CBMuQul3.js +0 -189
- package/dist/src/server-CMKKIzKv.cjs +0 -74
- package/dist/src/server-CN2IS9Cs.js +0 -155
- package/dist/src/server-ua4cqbjC.js +0 -2
- package/dist/src/session-CQIjq_HZ.cjs +0 -69
- package/dist/src/session-FTlg8sEu.js +0 -62
- package/dist/src/session-GBQXtPWp.js +0 -63
- package/dist/src/session-_0-rTdwY.js +0 -62
- package/dist/src/shared-BtuO-OAM.js +0 -1927
- package/dist/src/shared-Ci78wTZX.js +0 -1928
- package/dist/src/shared-Dd3rimdM.js +0 -1929
- package/dist/src/shared-KAjFxRre.cjs +0 -2185
- package/dist/src/simulatedUser--OjW6xCx.js +0 -247
- package/dist/src/simulatedUser-D0-slRye.cjs +0 -252
- package/dist/src/simulatedUser-D1Kh_cwA.js +0 -248
- package/dist/src/slack-BX0FUevO.js +0 -144
- package/dist/src/slack-CcwXFiJE.cjs +0 -144
- package/dist/src/slack-CnfqKfXp.js +0 -145
- package/dist/src/strategies-2ntcK4tN.js +0 -2248
- package/dist/src/strategies-DZIW7Zcs.js +0 -2385
- package/dist/src/strategies-YRDF2j-N.cjs +0 -2420
- package/dist/src/telemetry-CL8CVA4p.js +0 -205
- package/dist/src/telemetry-Cix90qqz.js +0 -201
- package/dist/src/telemetry-CkmlqTjV.js +0 -205
- package/dist/src/telemetry-DQH7l5bb.js +0 -2
- package/dist/src/telemetry-DUCXc1-r.cjs +0 -216
- package/dist/src/togetherai-3yUt5Ck7.js +0 -49
- package/dist/src/togetherai-BJUByLwt.cjs +0 -49
- package/dist/src/togetherai-Bh6KZkmd.js +0 -50
- package/dist/src/togetherai-DDl9yk3b.js +0 -48
- package/dist/src/traceContext-BiJVppjT.cjs +0 -1032
- package/dist/src/traceContext-CKKluULP.js +0 -1016
- package/dist/src/traceContext-D3Sk8fO-.js +0 -1015
- package/dist/src/transcription-BoVQKIVz.js +0 -175
- package/dist/src/transcription-Bs5u8780.js +0 -175
- package/dist/src/transcription-Dl654d1p.cjs +0 -178
- package/dist/src/transcription-VEvhM1Fu.js +0 -176
- package/dist/src/transform-BAbkGpvl.js +0 -125
- package/dist/src/transform-C_j4hUH8.js +0 -126
- package/dist/src/transform-Da86hs4M.cjs +0 -154
- package/dist/src/transform-_i1raQNo.js +0 -125
- package/dist/src/typesafe-CKXBeh82.cjs +0 -253
- package/dist/src/typesafe-D3VaGeNm.js +0 -253
- package/dist/src/typesafe-DYM-SFNH.js +0 -253
- package/dist/src/typesafe-LXmSbw8F.js +0 -254
- package/dist/src/util-41rb0XHX.js +0 -743
- package/dist/src/util-B0WlHYFM.js +0 -2049
- package/dist/src/util-BD1R_PsR.js +0 -1770
- package/dist/src/util-BLbM_ItC.js +0 -395
- package/dist/src/util-C72P0iIa.js +0 -352
- package/dist/src/util-C7MpGlJ6.cjs +0 -2305
- package/dist/src/util-CCtqagKc.js +0 -286
- package/dist/src/util-CM2Ec_uY.js +0 -2051
- package/dist/src/util-CSSAWO8v.js +0 -351
- package/dist/src/util-CkQc-fx3.cjs +0 -934
- package/dist/src/util-DcOlFTFa.cjs +0 -478
- package/dist/src/util-DluGTGVB.js +0 -395
- package/dist/src/util-PfQ60chz.js +0 -743
- package/dist/src/util-f14-CPij.js +0 -396
- package/dist/src/util-l9pXX3Eu.cjs +0 -357
- package/dist/src/util-o_BnlYqS.js +0 -2050
- package/dist/src/vertex-B_-gQgzc.js +0 -2
- package/dist/src/vertex-CU4gqoYa.js +0 -854
- package/dist/src/vertex-DZ42UHb3.js +0 -848
- package/dist/src/vertex-DsYQJA0T.cjs +0 -871
- package/dist/src/vertexLive-BvIaHKGB.js +0 -55
- package/dist/src/vertexLive-CTULqNx7.js +0 -56
- package/dist/src/vertexLive-DjJ_YQBe.cjs +0 -55
- package/dist/src/vertexLive-STUGcteB.js +0 -55
- package/dist/src/video-CAQGmtEV.js +0 -703
- package/dist/src/video-_FSTWlwX.js +0 -702
- package/dist/src/video-aBPJPWdt.js +0 -702
- package/dist/src/video-gDjkWv5m.cjs +0 -706
|
@@ -1,1927 +0,0 @@
|
|
|
1
|
-
import { B as safeJsonStringify, G as state, J as getEnvInt, K as getEnvBool, N as isApiProvider, P as isProviderOptions, o as logger, q as getEnvFloat } from "./logger-Gff7RMNF.js";
|
|
2
|
-
import { A as sanitizeProviderIdForLog } from "./dataUrl-C9J7wz9H.js";
|
|
3
|
-
import { F as isTransientConnectionError, N as isHttpRateLimitError, R as parseRateLimitHeaders, l as withFetchRetryContext, v as cloudConfig, z as parseRetryAfter } from "./fetch-BCwjoIFd.js";
|
|
4
|
-
import { t as invariant } from "./invariant-CHP0zrix.js";
|
|
5
|
-
import { l as isLoggedIntoCloud } from "./accounts-e4FGOsji.js";
|
|
6
|
-
import { S as isCallerAbortError } from "./shared-BBI-NXjW.js";
|
|
7
|
-
import { X as isSafeCost, Z as isSafeTokenCount } from "./util-CsTD_ROg.js";
|
|
8
|
-
import "./tables-D7gZdWrS.js";
|
|
9
|
-
import { t as BaseTokenUsageSchema } from "./shared-CPig5o70.js";
|
|
10
|
-
import { h as remoteGenerationContextPayload } from "./remoteGeneration-DaxwJDKv.js";
|
|
11
|
-
import { a as accumulateGradingResponseTokenUsage, c as accumulateTokenUsage, d as createEmptyTokenUsage, s as accumulateResponseTokenUsage } from "./tokenUsageUtils-BfzeNdYY.js";
|
|
12
|
-
import { n as isBlobStorageEnabled, t as extractAndStoreBinaryData } from "./extractor-NglB5koy.js";
|
|
13
|
-
import { a as createResponseHeadersObserver, c as preserveResponseHeadersObserverError, i as composeResponseHeadersObservers, l as preserveResponseHeadersObserverErrorResponse, o as isResponseHeadersObserverError, s as isResponseHeadersObserverErrorResponse, t as OpenAiChatCompletionProvider } from "./chat-DFoZLvO_.js";
|
|
14
|
-
import { t as PromptfooChatCompletionProvider } from "./promptfoo-BQRfgNs_.js";
|
|
15
|
-
import { o as transform, r as TransformInputType } from "./transform-BClOmD-Z.js";
|
|
16
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
17
|
-
import { createHash, randomUUID } from "crypto";
|
|
18
|
-
import { EventEmitter } from "events";
|
|
19
|
-
//#region src/blobs/remoteUpload.ts
|
|
20
|
-
function buildRemoteUploadTarget() {
|
|
21
|
-
if (getEnvBool("PROMPTFOO_DISABLE_SHARING")) return null;
|
|
22
|
-
const baseUrl = cloudConfig.getApiHost();
|
|
23
|
-
const authHeaders = cloudConfig.getAuthHeaders();
|
|
24
|
-
if (!baseUrl || !authHeaders || !isLoggedIntoCloud()) return null;
|
|
25
|
-
try {
|
|
26
|
-
return {
|
|
27
|
-
url: new URL("/api/blobs", baseUrl).toString(),
|
|
28
|
-
authHeaders
|
|
29
|
-
};
|
|
30
|
-
} catch (error) {
|
|
31
|
-
logger.debug("[RemoteBlob] Invalid remote blob URL", {
|
|
32
|
-
error: error instanceof Error ? error.message : String(error),
|
|
33
|
-
baseUrl
|
|
34
|
-
});
|
|
35
|
-
return null;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
function shouldAttemptRemoteBlobUpload() {
|
|
39
|
-
return buildRemoteUploadTarget() !== null;
|
|
40
|
-
}
|
|
41
|
-
async function uploadBlobRemote(buffer, mimeType, context) {
|
|
42
|
-
const target = buildRemoteUploadTarget();
|
|
43
|
-
if (!target) return null;
|
|
44
|
-
try {
|
|
45
|
-
const { fetchWithProxy } = await import("./fetch-BCwjoIFd.js").then((n) => n.i);
|
|
46
|
-
const response = await fetchWithProxy(target.url, {
|
|
47
|
-
method: "POST",
|
|
48
|
-
headers: {
|
|
49
|
-
"Content-Type": "application/json",
|
|
50
|
-
...target.authHeaders
|
|
51
|
-
},
|
|
52
|
-
body: JSON.stringify({
|
|
53
|
-
data: buffer.toString("base64"),
|
|
54
|
-
mimeType,
|
|
55
|
-
context
|
|
56
|
-
})
|
|
57
|
-
});
|
|
58
|
-
if (response.status === 404 || response.status === 400) {
|
|
59
|
-
logger.debug("[RemoteBlob] Remote blob upload unavailable", { status: response.status });
|
|
60
|
-
return null;
|
|
61
|
-
}
|
|
62
|
-
if (!response.ok) {
|
|
63
|
-
const text = await response.text();
|
|
64
|
-
logger.debug("[RemoteBlob] Failed to upload blob", {
|
|
65
|
-
status: response.status,
|
|
66
|
-
statusText: response.statusText,
|
|
67
|
-
body: text
|
|
68
|
-
});
|
|
69
|
-
return null;
|
|
70
|
-
}
|
|
71
|
-
const data = await response.json();
|
|
72
|
-
if (!data?.ref?.hash) {
|
|
73
|
-
logger.debug("[RemoteBlob] Remote upload returned malformed response");
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
return data;
|
|
77
|
-
} catch (error) {
|
|
78
|
-
logger.debug("[RemoteBlob] Error uploading blob", { error: error instanceof Error ? error.message : String(error) });
|
|
79
|
-
return null;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
//#endregion
|
|
83
|
-
//#region src/scheduler/providerCallExecutionContext.ts
|
|
84
|
-
const providerCallExecutionContext = new AsyncLocalStorage();
|
|
85
|
-
const providerCallTracingContext = new AsyncLocalStorage();
|
|
86
|
-
function getProviderCallExecutionContext() {
|
|
87
|
-
return providerCallExecutionContext.getStore();
|
|
88
|
-
}
|
|
89
|
-
function withProviderCallExecutionContext(context, fn) {
|
|
90
|
-
return providerCallExecutionContext.run(context, fn);
|
|
91
|
-
}
|
|
92
|
-
function runProviderCallWithAbort(call, signal) {
|
|
93
|
-
if (!signal) return call();
|
|
94
|
-
signal.throwIfAborted();
|
|
95
|
-
return new Promise((resolve, reject) => {
|
|
96
|
-
let settled = false;
|
|
97
|
-
let pendingAbort;
|
|
98
|
-
const finish = (complete) => {
|
|
99
|
-
if (settled) return;
|
|
100
|
-
settled = true;
|
|
101
|
-
signal.removeEventListener("abort", onAbort);
|
|
102
|
-
if (pendingAbort) clearImmediate(pendingAbort);
|
|
103
|
-
complete();
|
|
104
|
-
};
|
|
105
|
-
const onAbort = () => {
|
|
106
|
-
pendingAbort = setImmediate(() => finish(() => reject(signal.reason)));
|
|
107
|
-
};
|
|
108
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
109
|
-
try {
|
|
110
|
-
call().then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
|
|
111
|
-
} catch (error) {
|
|
112
|
-
finish(() => reject(error));
|
|
113
|
-
}
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
function getProviderCallTracingContext() {
|
|
117
|
-
return providerCallTracingContext.getStore();
|
|
118
|
-
}
|
|
119
|
-
function withProviderCallTracingContext(tracingContext, fn) {
|
|
120
|
-
return providerCallTracingContext.run(tracingContext, fn);
|
|
121
|
-
}
|
|
122
|
-
//#endregion
|
|
123
|
-
//#region src/scheduler/types.ts
|
|
124
|
-
/**
|
|
125
|
-
* Shared types for the scheduler module.
|
|
126
|
-
*/
|
|
127
|
-
const HTTP_429_RE = /\b429\b/;
|
|
128
|
-
/**
|
|
129
|
-
* Default rate limit detection for ProviderResponse.
|
|
130
|
-
*
|
|
131
|
-
* Returns true when a result/error indicates a *retryable* rate limit. Hard
|
|
132
|
-
* quota failures (billing exhaustion, daily limits) match the same `429` /
|
|
133
|
-
* `too many requests` substrings but must NOT be classified as retryable —
|
|
134
|
-
* doing so amplifies load against an exhausted account, which is the exact
|
|
135
|
-
* regression PR 8896 closes at the transport layer. The result-path check
|
|
136
|
-
* here mirrors that fail-fast contract for providers that fold the
|
|
137
|
-
* structured error into `ProviderResponse.error`.
|
|
138
|
-
*/
|
|
139
|
-
function isProviderResponseRateLimited(result, error) {
|
|
140
|
-
if (isResponseHeadersObserverErrorResponse(result)) return false;
|
|
141
|
-
const responseError = result?.metadata?.errorOrigin === "tool" ? void 0 : result?.error;
|
|
142
|
-
if (result?.metadata?.rateLimitRetryable === false || result?.metadata?.rateLimitKind === "quota") return false;
|
|
143
|
-
if (result?.metadata?.rateLimitKind === "rate_limit") return true;
|
|
144
|
-
if (isHttpRateLimitError(error) && error.kind === "quota") return false;
|
|
145
|
-
if (responseError?.includes("Quota exceeded:")) return false;
|
|
146
|
-
if (error?.message?.includes("Quota exceeded:")) return false;
|
|
147
|
-
return Boolean(result?.metadata?.http?.status === 429 || HTTP_429_RE.test(responseError ?? "") || responseError?.toLowerCase?.().includes?.("rate limit") || HTTP_429_RE.test(error?.message ?? "") || error?.message?.toLowerCase().includes("rate limit") || error?.message?.toLowerCase().includes("too many requests"));
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Extract rate limit headers from ProviderResponse.
|
|
151
|
-
* Headers can be at metadata.http.headers or metadata.headers.
|
|
152
|
-
*/
|
|
153
|
-
function getProviderResponseHeaders(result) {
|
|
154
|
-
return result?.metadata?.http?.headers || result?.metadata?.headers;
|
|
155
|
-
}
|
|
156
|
-
//#endregion
|
|
157
|
-
//#region src/scheduler/providerWrapper.ts
|
|
158
|
-
/**
|
|
159
|
-
* Provider wrapper that adds rate limiting to any ApiProvider.
|
|
160
|
-
*
|
|
161
|
-
* Use this to wrap providers before passing them to redteam/assertion
|
|
162
|
-
* code paths that bypass the main evaluator.
|
|
163
|
-
*/
|
|
164
|
-
/**
|
|
165
|
-
* Symbol to mark providers that have already been wrapped.
|
|
166
|
-
* Prevents double-wrapping which could cause issues.
|
|
167
|
-
*/
|
|
168
|
-
const WRAPPED_SYMBOL = Symbol.for("promptfoo.rateLimitWrapped");
|
|
169
|
-
const TOKEN_USAGE_FIELDS = [
|
|
170
|
-
"prompt",
|
|
171
|
-
"completion",
|
|
172
|
-
"cached",
|
|
173
|
-
"total"
|
|
174
|
-
];
|
|
175
|
-
const COMPLETION_DETAIL_FIELDS = [
|
|
176
|
-
"reasoning",
|
|
177
|
-
"acceptedPrediction",
|
|
178
|
-
"rejectedPrediction",
|
|
179
|
-
"cacheReadInputTokens",
|
|
180
|
-
"cacheCreationInputTokens"
|
|
181
|
-
];
|
|
182
|
-
function addSafeTokenMetric(current, value) {
|
|
183
|
-
if (!isSafeTokenCount(value)) return;
|
|
184
|
-
const total = (current ?? 0) + value;
|
|
185
|
-
return Number.isSafeInteger(total) ? total : void 0;
|
|
186
|
-
}
|
|
187
|
-
function accumulateRetryTokenUsage(target, response) {
|
|
188
|
-
const usage = response.tokenUsage;
|
|
189
|
-
for (const field of TOKEN_USAGE_FIELDS) {
|
|
190
|
-
const total = addSafeTokenMetric(target[field], usage?.[field]);
|
|
191
|
-
if (total !== void 0) target[field] = total;
|
|
192
|
-
}
|
|
193
|
-
for (const field of COMPLETION_DETAIL_FIELDS) {
|
|
194
|
-
const value = usage?.completionDetails?.[field];
|
|
195
|
-
const total = addSafeTokenMetric(target.completionDetails?.[field], value);
|
|
196
|
-
if (total !== void 0) {
|
|
197
|
-
target.completionDetails ??= {};
|
|
198
|
-
target.completionDetails[field] = total;
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
const requests = response.cached ? 0 : isSafeTokenCount(usage?.numRequests) ? usage.numRequests : 1;
|
|
202
|
-
const totalRequests = addSafeTokenMetric(target.numRequests, requests);
|
|
203
|
-
if (totalRequests !== void 0) target.numRequests = totalRequests;
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Check if a provider is already wrapped with rate limiting.
|
|
207
|
-
*/
|
|
208
|
-
function isRateLimitWrapped(provider) {
|
|
209
|
-
return provider[WRAPPED_SYMBOL] === true;
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Create rate limit detection options for ProviderResponse.
|
|
213
|
-
* Shared between providerWrapper and evaluator for consistency.
|
|
214
|
-
*/
|
|
215
|
-
function createProviderRateLimitOptions(abortSignal) {
|
|
216
|
-
return {
|
|
217
|
-
...abortSignal && { abortSignal },
|
|
218
|
-
onRateLimitExhausted: (result, error) => result.error ? result : {
|
|
219
|
-
...result,
|
|
220
|
-
error: error.message
|
|
221
|
-
},
|
|
222
|
-
getHeaders: (result) => result?.metadata?.rateLimitRetryable === false || result?.metadata?.rateLimitKind === "quota" ? void 0 : getProviderResponseHeaders(result),
|
|
223
|
-
isRateLimited: isProviderResponseRateLimited,
|
|
224
|
-
getRetryAfter: (result, error) => {
|
|
225
|
-
if (result?.metadata?.rateLimitRetryable === false) return;
|
|
226
|
-
const rawHeaders = getProviderResponseHeaders(result);
|
|
227
|
-
if (rawHeaders) {
|
|
228
|
-
const headers = {};
|
|
229
|
-
for (const [key, value] of Object.entries(rawHeaders)) headers[key.toLowerCase()] = value;
|
|
230
|
-
if (headers["retry-after-ms"]) {
|
|
231
|
-
const ms = Number.parseInt(headers["retry-after-ms"], 10);
|
|
232
|
-
if (Number.isFinite(ms) && ms >= 0) return ms;
|
|
233
|
-
}
|
|
234
|
-
if (headers["retry-after"]) {
|
|
235
|
-
const parsed = parseRetryAfter(headers["retry-after"]);
|
|
236
|
-
if (parsed !== null) return parsed;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
const match = error?.message?.match(/\bretry after (\d+)\b/i);
|
|
240
|
-
if (match) {
|
|
241
|
-
const retryAfterMs = Number.parseInt(match[1], 10) * 1e3;
|
|
242
|
-
return Number.isFinite(retryAfterMs) ? retryAfterMs : void 0;
|
|
243
|
-
}
|
|
244
|
-
},
|
|
245
|
-
isRetryableResult: (result) => {
|
|
246
|
-
return result.metadata?.retryableErrorKind === "transient_availability";
|
|
247
|
-
},
|
|
248
|
-
finalizeResult: (result, retryResults) => {
|
|
249
|
-
if (retryResults.length === 0) return result;
|
|
250
|
-
const tokenUsage = {};
|
|
251
|
-
let combinedCost = 0;
|
|
252
|
-
let hasCost = false;
|
|
253
|
-
for (const response of [...retryResults, result]) {
|
|
254
|
-
accumulateRetryTokenUsage(tokenUsage, response);
|
|
255
|
-
if (isSafeCost(response.cost)) {
|
|
256
|
-
combinedCost += response.cost;
|
|
257
|
-
hasCost = true;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
const resultWithoutCost = { ...result };
|
|
261
|
-
delete resultWithoutCost.cost;
|
|
262
|
-
return {
|
|
263
|
-
...resultWithoutCost,
|
|
264
|
-
tokenUsage,
|
|
265
|
-
...hasCost && Number.isFinite(combinedCost) && { cost: combinedCost }
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
/**
|
|
271
|
-
* Wrap a provider with rate limiting.
|
|
272
|
-
*
|
|
273
|
-
* The wrapped provider will use the registry for all callApi calls,
|
|
274
|
-
* automatically handling rate limits, retries, and adaptive concurrency.
|
|
275
|
-
*
|
|
276
|
-
* @param provider - The provider to wrap
|
|
277
|
-
* @param registry - The rate limit registry to use
|
|
278
|
-
* @returns A wrapped provider that applies rate limiting
|
|
279
|
-
*/
|
|
280
|
-
function wrapProviderWithRateLimiting(provider, registry) {
|
|
281
|
-
if (isRateLimitWrapped(provider)) return provider;
|
|
282
|
-
const originalCallApi = provider.callApi.bind(provider);
|
|
283
|
-
const wrappedProvider = {
|
|
284
|
-
...provider,
|
|
285
|
-
id: () => provider.id(),
|
|
286
|
-
callApi: async (prompt, context, options) => {
|
|
287
|
-
return registry.execute(provider, (onResponseHeaders) => originalCallApi(prompt, context, onResponseHeaders ? {
|
|
288
|
-
...options,
|
|
289
|
-
onResponseHeaders: composeResponseHeadersObservers(onResponseHeaders, options?.onResponseHeaders)
|
|
290
|
-
} : options), createProviderRateLimitOptions(options?.abortSignal));
|
|
291
|
-
}
|
|
292
|
-
};
|
|
293
|
-
wrappedProvider[WRAPPED_SYMBOL] = true;
|
|
294
|
-
return wrappedProvider;
|
|
295
|
-
}
|
|
296
|
-
//#endregion
|
|
297
|
-
//#region src/scheduler/adaptiveConcurrency.ts
|
|
298
|
-
const DEFAULT_MIN_CONCURRENCY = 1;
|
|
299
|
-
const BACKOFF_FACTOR = .5;
|
|
300
|
-
const RECOVERY_FACTOR = 1.5;
|
|
301
|
-
const RECOVERY_THRESHOLD = 5;
|
|
302
|
-
const WARNING_THRESHOLD = .1;
|
|
303
|
-
function concurrencyChange(previous, current, reason, changed = previous !== current) {
|
|
304
|
-
return {
|
|
305
|
-
changed,
|
|
306
|
-
previous,
|
|
307
|
-
current,
|
|
308
|
-
reason
|
|
309
|
-
};
|
|
310
|
-
}
|
|
311
|
-
/**
|
|
312
|
-
* Manages adaptive concurrency based on rate limit feedback.
|
|
313
|
-
*
|
|
314
|
-
* Recovery path with constants (initial=10, min=1):
|
|
315
|
-
* 1 → ceil(1.5) = 2 (5 successes)
|
|
316
|
-
* 2 → ceil(3.0) = 3 (5 successes)
|
|
317
|
-
* 3 → ceil(4.5) = 5 (5 successes)
|
|
318
|
-
* 5 → ceil(7.5) = 8 (5 successes)
|
|
319
|
-
* 8 → ceil(12) = 10 (5 successes, capped at initial)
|
|
320
|
-
*
|
|
321
|
-
* Total: 25 requests to fully recover from min=1 to initial=10
|
|
322
|
-
*/
|
|
323
|
-
var AdaptiveConcurrency = class {
|
|
324
|
-
current;
|
|
325
|
-
initial;
|
|
326
|
-
min;
|
|
327
|
-
consecutiveSuccesses = 0;
|
|
328
|
-
constructor(initial, min = DEFAULT_MIN_CONCURRENCY) {
|
|
329
|
-
this.initial = initial;
|
|
330
|
-
this.current = initial;
|
|
331
|
-
this.min = Math.min(initial, Math.max(1, min));
|
|
332
|
-
}
|
|
333
|
-
/**
|
|
334
|
-
* Called on successful request.
|
|
335
|
-
* May increase concurrency after sustained success.
|
|
336
|
-
*/
|
|
337
|
-
recordSuccess() {
|
|
338
|
-
this.consecutiveSuccesses++;
|
|
339
|
-
if (this.consecutiveSuccesses >= RECOVERY_THRESHOLD && this.current < this.initial) {
|
|
340
|
-
const previous = this.current;
|
|
341
|
-
this.current = Math.min(this.initial, Math.ceil(this.current * RECOVERY_FACTOR));
|
|
342
|
-
this.consecutiveSuccesses = 0;
|
|
343
|
-
return concurrencyChange(previous, this.current, "recovery");
|
|
344
|
-
}
|
|
345
|
-
return concurrencyChange(this.current, this.current, "recovery", false);
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Called on rate limit (429).
|
|
349
|
-
* Reduces concurrency immediately.
|
|
350
|
-
*/
|
|
351
|
-
recordRateLimit() {
|
|
352
|
-
this.consecutiveSuccesses = 0;
|
|
353
|
-
const previous = this.current;
|
|
354
|
-
this.current = Math.max(this.min, Math.floor(this.current * BACKOFF_FACTOR));
|
|
355
|
-
return concurrencyChange(previous, this.current, "ratelimit");
|
|
356
|
-
}
|
|
357
|
-
/**
|
|
358
|
-
* Called when approaching rate limit.
|
|
359
|
-
* Proactively reduces concurrency based on remaining ratio.
|
|
360
|
-
*
|
|
361
|
-
* Formula:
|
|
362
|
-
* - At 10% remaining: reduce to 60% of current
|
|
363
|
-
* - At 5% remaining: reduce to 40% of current
|
|
364
|
-
* - At 1% remaining: reduce to 20% of current
|
|
365
|
-
*
|
|
366
|
-
* Linear scaling: reductionFactor = 0.2 + (ratio / WARNING_THRESHOLD) * 0.4
|
|
367
|
-
*/
|
|
368
|
-
recordApproachingLimit(ratio) {
|
|
369
|
-
const clampedRatio = Math.max(0, Math.min(1, ratio));
|
|
370
|
-
if (clampedRatio >= .1 || this.current <= this.min) return concurrencyChange(this.current, this.current, "proactive", false);
|
|
371
|
-
const previous = this.current;
|
|
372
|
-
const reductionFactor = .2 + clampedRatio / WARNING_THRESHOLD * .4;
|
|
373
|
-
this.current = Math.max(this.min, Math.floor(this.current * reductionFactor));
|
|
374
|
-
return concurrencyChange(previous, this.current, "proactive");
|
|
375
|
-
}
|
|
376
|
-
getCurrent() {
|
|
377
|
-
return this.current;
|
|
378
|
-
}
|
|
379
|
-
getMin() {
|
|
380
|
-
return this.min;
|
|
381
|
-
}
|
|
382
|
-
getInitial() {
|
|
383
|
-
return this.initial;
|
|
384
|
-
}
|
|
385
|
-
};
|
|
386
|
-
//#endregion
|
|
387
|
-
//#region src/scheduler/cancellation.ts
|
|
388
|
-
function throwIfAborted(signal) {
|
|
389
|
-
if (signal?.aborted) throw signal.reason;
|
|
390
|
-
}
|
|
391
|
-
function sleepWithAbort(ms, signal) {
|
|
392
|
-
return new Promise((resolve, reject) => {
|
|
393
|
-
throwIfAborted(signal);
|
|
394
|
-
const cleanup = () => {
|
|
395
|
-
clearTimeout(timer);
|
|
396
|
-
signal?.removeEventListener("abort", onAbort);
|
|
397
|
-
};
|
|
398
|
-
const onAbort = () => {
|
|
399
|
-
cleanup();
|
|
400
|
-
reject(signal?.reason);
|
|
401
|
-
};
|
|
402
|
-
const timer = setTimeout(() => {
|
|
403
|
-
cleanup();
|
|
404
|
-
resolve();
|
|
405
|
-
}, ms);
|
|
406
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
//#endregion
|
|
410
|
-
//#region src/scheduler/retryPolicy.ts
|
|
411
|
-
const DEFAULT_RETRY_POLICY = {
|
|
412
|
-
maxRetries: 3,
|
|
413
|
-
baseDelayMs: 1e3,
|
|
414
|
-
maxDelayMs: 6e4,
|
|
415
|
-
jitterFactor: .2
|
|
416
|
-
};
|
|
417
|
-
/**
|
|
418
|
-
* Calculate delay for retry attempt.
|
|
419
|
-
* Prefers server-specified Retry-After when available.
|
|
420
|
-
*/
|
|
421
|
-
function getRetryDelay(attempt, policy, serverRetryAfterMs) {
|
|
422
|
-
if (serverRetryAfterMs !== void 0 && serverRetryAfterMs >= 0) {
|
|
423
|
-
if (serverRetryAfterMs === 0) return 0;
|
|
424
|
-
const jitter = serverRetryAfterMs * policy.jitterFactor * Math.random();
|
|
425
|
-
return Math.min(serverRetryAfterMs + jitter, policy.maxDelayMs);
|
|
426
|
-
}
|
|
427
|
-
const exponentialDelay = policy.baseDelayMs * Math.pow(2, attempt);
|
|
428
|
-
const jitter = exponentialDelay * policy.jitterFactor * Math.random();
|
|
429
|
-
return Math.min(exponentialDelay + jitter, policy.maxDelayMs);
|
|
430
|
-
}
|
|
431
|
-
/**
|
|
432
|
-
* Determine if we should retry a failed request.
|
|
433
|
-
*/
|
|
434
|
-
function shouldRetry(attempt, error, isRateLimited, policy) {
|
|
435
|
-
if (attempt >= policy.maxRetries) return false;
|
|
436
|
-
if (isHttpRateLimitError(error) && error.kind === "quota") return false;
|
|
437
|
-
if (isRateLimited) return true;
|
|
438
|
-
if (error) {
|
|
439
|
-
const message = (error.message ?? "").toLowerCase();
|
|
440
|
-
return isTransientConnectionError(error) || message.includes("timeout") || message.startsWith("websocket request timed out after ") || message.includes("econnrefused") || message.includes("network") || message.includes("503") || message.includes("502") || message.includes("504");
|
|
441
|
-
}
|
|
442
|
-
return false;
|
|
443
|
-
}
|
|
444
|
-
//#endregion
|
|
445
|
-
//#region src/scheduler/slotQueue.ts
|
|
446
|
-
const DEFAULT_QUEUE_TIMEOUT_MS = 3e5;
|
|
447
|
-
/**
|
|
448
|
-
* Manages concurrency slots with FIFO queue for waiting requests.
|
|
449
|
-
*
|
|
450
|
-
* Race condition prevention:
|
|
451
|
-
* - All slot allocation goes through the queue
|
|
452
|
-
* - processQueue() is synchronous and runs atomically
|
|
453
|
-
* - No await between capacity check and increment
|
|
454
|
-
*/
|
|
455
|
-
var SlotQueue = class {
|
|
456
|
-
activeCount = 0;
|
|
457
|
-
maxConcurrency;
|
|
458
|
-
minConcurrency;
|
|
459
|
-
waiting = [];
|
|
460
|
-
resetTimer = null;
|
|
461
|
-
queueTimeoutMs;
|
|
462
|
-
resetAt = null;
|
|
463
|
-
remainingRequests = null;
|
|
464
|
-
remainingTokens = null;
|
|
465
|
-
requestLimit = null;
|
|
466
|
-
tokenLimit = null;
|
|
467
|
-
onSlotAcquired;
|
|
468
|
-
onSlotReleased;
|
|
469
|
-
constructor(options) {
|
|
470
|
-
this.maxConcurrency = options.maxConcurrency;
|
|
471
|
-
this.minConcurrency = options.minConcurrency;
|
|
472
|
-
this.queueTimeoutMs = options.queueTimeoutMs ?? DEFAULT_QUEUE_TIMEOUT_MS;
|
|
473
|
-
this.onSlotAcquired = options.onSlotAcquired;
|
|
474
|
-
this.onSlotReleased = options.onSlotReleased;
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* Acquire a slot. All requests go through the queue to prevent race conditions.
|
|
478
|
-
* Returns when a slot is available and quota is not exhausted. An aborted signal stops
|
|
479
|
-
* the request from waiting, but a slot that is free immediately is still granted.
|
|
480
|
-
*/
|
|
481
|
-
async acquire(requestId, abortSignal) {
|
|
482
|
-
return new Promise((resolve, reject) => {
|
|
483
|
-
let timeoutId;
|
|
484
|
-
const cleanup = () => {
|
|
485
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
486
|
-
abortSignal?.removeEventListener("abort", onAbort);
|
|
487
|
-
};
|
|
488
|
-
const removeAndReject = (error) => {
|
|
489
|
-
const index = this.waiting.indexOf(request);
|
|
490
|
-
if (index !== -1) {
|
|
491
|
-
this.waiting.splice(index, 1);
|
|
492
|
-
request.reject(error);
|
|
493
|
-
this.processQueue();
|
|
494
|
-
}
|
|
495
|
-
};
|
|
496
|
-
const onAbort = () => removeAndReject(abortSignal?.reason);
|
|
497
|
-
const request = {
|
|
498
|
-
id: requestId,
|
|
499
|
-
resolve: () => {
|
|
500
|
-
cleanup();
|
|
501
|
-
this.activeCount++;
|
|
502
|
-
this.onSlotAcquired?.(this.waiting.length);
|
|
503
|
-
resolve();
|
|
504
|
-
},
|
|
505
|
-
reject: (error) => {
|
|
506
|
-
cleanup();
|
|
507
|
-
reject(error);
|
|
508
|
-
}
|
|
509
|
-
};
|
|
510
|
-
if (this.queueTimeoutMs > 0) timeoutId = setTimeout(() => removeAndReject(/* @__PURE__ */ new Error(`Request ${requestId} timed out after ${this.queueTimeoutMs}ms in queue`)), this.queueTimeoutMs);
|
|
511
|
-
this.waiting.push(request);
|
|
512
|
-
abortSignal?.addEventListener("abort", onAbort, { once: true });
|
|
513
|
-
this.processQueue();
|
|
514
|
-
if (abortSignal?.aborted) onAbort();
|
|
515
|
-
});
|
|
516
|
-
}
|
|
517
|
-
/**
|
|
518
|
-
* Release a slot and process next queued request.
|
|
519
|
-
*/
|
|
520
|
-
release() {
|
|
521
|
-
if (this.activeCount <= 0) return;
|
|
522
|
-
this.activeCount--;
|
|
523
|
-
this.onSlotReleased?.(this.waiting.length);
|
|
524
|
-
this.processQueue();
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Update rate limit state from parsed headers.
|
|
528
|
-
*/
|
|
529
|
-
updateRateLimitState(parsed) {
|
|
530
|
-
if (parsed.remainingRequests !== void 0) this.remainingRequests = parsed.remainingRequests;
|
|
531
|
-
if (parsed.limitRequests !== void 0) this.requestLimit = parsed.limitRequests;
|
|
532
|
-
if (parsed.remainingTokens !== void 0) this.remainingTokens = parsed.remainingTokens;
|
|
533
|
-
if (parsed.limitTokens !== void 0) this.tokenLimit = parsed.limitTokens;
|
|
534
|
-
if (parsed.resetAt !== void 0) {
|
|
535
|
-
this.resetAt = parsed.resetAt;
|
|
536
|
-
this.scheduleResetProcessing();
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Mark that a rate limit was hit.
|
|
541
|
-
* Only updates resetAt if we don't already have a later reset time.
|
|
542
|
-
* A selected absolute deadline takes precedence over a relative retry delay.
|
|
543
|
-
*/
|
|
544
|
-
markRateLimited(retryAfterMs, selectedResetAt) {
|
|
545
|
-
this.remainingRequests = 0;
|
|
546
|
-
this.remainingTokens = 0;
|
|
547
|
-
let newResetAt = selectedResetAt;
|
|
548
|
-
if (newResetAt === void 0 && retryAfterMs !== void 0 && retryAfterMs >= 0) newResetAt = Date.now() + retryAfterMs;
|
|
549
|
-
if (newResetAt !== void 0) this.resetAt = Math.max(this.resetAt ?? newResetAt, newResetAt);
|
|
550
|
-
else if (this.resetAt === null) this.resetAt = Date.now() + 6e4;
|
|
551
|
-
this.scheduleResetProcessing();
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Adjust max concurrency (called by adaptive algorithm).
|
|
555
|
-
*/
|
|
556
|
-
setMaxConcurrency(value) {
|
|
557
|
-
this.maxConcurrency = Math.max(this.minConcurrency, value);
|
|
558
|
-
this.processQueue();
|
|
559
|
-
}
|
|
560
|
-
getMaxConcurrency() {
|
|
561
|
-
return this.maxConcurrency;
|
|
562
|
-
}
|
|
563
|
-
getActiveCount() {
|
|
564
|
-
return this.activeCount;
|
|
565
|
-
}
|
|
566
|
-
getQueueDepth() {
|
|
567
|
-
return this.waiting.length;
|
|
568
|
-
}
|
|
569
|
-
getResetAt() {
|
|
570
|
-
return this.resetAt;
|
|
571
|
-
}
|
|
572
|
-
/**
|
|
573
|
-
* Check if quota is exhausted (should wait for reset).
|
|
574
|
-
* Checks BOTH request AND token quotas.
|
|
575
|
-
*
|
|
576
|
-
* NOTE: This method has intentional side effects - it clears stale quota state
|
|
577
|
-
* when the reset time has passed. This ensures we don't block indefinitely on
|
|
578
|
-
* outdated rate limit info.
|
|
579
|
-
*/
|
|
580
|
-
isQuotaExhausted() {
|
|
581
|
-
const now = Date.now();
|
|
582
|
-
if (this.resetAt && now >= this.resetAt) {
|
|
583
|
-
this.remainingRequests = null;
|
|
584
|
-
this.remainingTokens = null;
|
|
585
|
-
this.resetAt = null;
|
|
586
|
-
return false;
|
|
587
|
-
}
|
|
588
|
-
const quotaExhausted = (remaining) => remaining !== null && remaining <= 0 && this.resetAt && now < this.resetAt;
|
|
589
|
-
return !!(quotaExhausted(this.remainingRequests) || quotaExhausted(this.remainingTokens));
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* Schedule queue processing when rate limit window resets.
|
|
593
|
-
*/
|
|
594
|
-
scheduleResetProcessing() {
|
|
595
|
-
clearTimeout(this.resetTimer ?? void 0);
|
|
596
|
-
this.resetTimer = null;
|
|
597
|
-
if (this.resetAt && this.waiting.length > 0) {
|
|
598
|
-
const delay = Math.max(0, this.resetAt - Date.now());
|
|
599
|
-
this.resetTimer = setTimeout(() => {
|
|
600
|
-
this.resetTimer = null;
|
|
601
|
-
this.remainingRequests = null;
|
|
602
|
-
this.remainingTokens = null;
|
|
603
|
-
this.resetAt = null;
|
|
604
|
-
this.processQueue();
|
|
605
|
-
}, delay);
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
/**
|
|
609
|
-
* Process queued requests up to available capacity.
|
|
610
|
-
* SYNCHRONOUS - no awaits, prevents race conditions.
|
|
611
|
-
*/
|
|
612
|
-
processQueue() {
|
|
613
|
-
while (this.waiting.length > 0 && this.activeCount < this.maxConcurrency && !this.isQuotaExhausted()) this.waiting.shift().resolve();
|
|
614
|
-
if (this.waiting.length > 0 && this.isQuotaExhausted()) this.scheduleResetProcessing();
|
|
615
|
-
else if (this.resetTimer) {
|
|
616
|
-
clearTimeout(this.resetTimer);
|
|
617
|
-
this.resetTimer = null;
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
/**
|
|
621
|
-
* Check if approaching rate limit (for proactive throttling).
|
|
622
|
-
* Returns ratio of remaining/limit, or null if unknown.
|
|
623
|
-
*/
|
|
624
|
-
getRemainingRatio() {
|
|
625
|
-
let requestRatio = null;
|
|
626
|
-
let tokenRatio = null;
|
|
627
|
-
if (this.remainingRequests !== null && this.requestLimit !== null && this.requestLimit > 0) requestRatio = this.remainingRequests / this.requestLimit;
|
|
628
|
-
if (this.remainingTokens !== null && this.tokenLimit !== null && this.tokenLimit > 0) tokenRatio = this.remainingTokens / this.tokenLimit;
|
|
629
|
-
return {
|
|
630
|
-
requests: requestRatio,
|
|
631
|
-
tokens: tokenRatio
|
|
632
|
-
};
|
|
633
|
-
}
|
|
634
|
-
/**
|
|
635
|
-
* Cleanup resources.
|
|
636
|
-
*
|
|
637
|
-
* Rejects any pending acquire() promises with 'Queue disposed' error.
|
|
638
|
-
* Callers should handle these rejections (e.g., via .catch() on acquire promises).
|
|
639
|
-
*/
|
|
640
|
-
dispose() {
|
|
641
|
-
clearTimeout(this.resetTimer ?? void 0);
|
|
642
|
-
this.resetTimer = null;
|
|
643
|
-
const waiting = this.waiting;
|
|
644
|
-
this.waiting = [];
|
|
645
|
-
for (const request of waiting) request.reject(/* @__PURE__ */ new Error("Queue disposed"));
|
|
646
|
-
}
|
|
647
|
-
};
|
|
648
|
-
//#endregion
|
|
649
|
-
//#region src/scheduler/providerRateLimitState.ts
|
|
650
|
-
var RateLimitExhaustedError = class extends Error {
|
|
651
|
-
result;
|
|
652
|
-
constructor(message, result) {
|
|
653
|
-
super(message);
|
|
654
|
-
this.result = result;
|
|
655
|
-
this.name = "RateLimitExhaustedError";
|
|
656
|
-
}
|
|
657
|
-
};
|
|
658
|
-
/**
|
|
659
|
-
* Wraps a finalizeResult throw so the retry classifier below skips it: a
|
|
660
|
-
* finalizer failure is not provider work and must never trigger another call.
|
|
661
|
-
*/
|
|
662
|
-
var ResultFinalizationError = class extends Error {
|
|
663
|
-
original;
|
|
664
|
-
constructor(original) {
|
|
665
|
-
super("finalizeResult failed");
|
|
666
|
-
this.original = original;
|
|
667
|
-
this.name = "ResultFinalizationError";
|
|
668
|
-
}
|
|
669
|
-
};
|
|
670
|
-
/**
|
|
671
|
-
* Manages rate limit state and retry logic for a single rate limit key.
|
|
672
|
-
*/
|
|
673
|
-
var ProviderRateLimitState = class extends EventEmitter {
|
|
674
|
-
rateLimitKey;
|
|
675
|
-
slotQueue;
|
|
676
|
-
adaptiveConcurrency;
|
|
677
|
-
retryPolicy;
|
|
678
|
-
totalRequests = 0;
|
|
679
|
-
completedRequests = 0;
|
|
680
|
-
failedRequests = 0;
|
|
681
|
-
rateLimitHits = 0;
|
|
682
|
-
retriedRequests = 0;
|
|
683
|
-
/** Keep the latest 100 latency measurements for bounded metric sorting and storage. */
|
|
684
|
-
latencies = [];
|
|
685
|
-
hasLearnedLimits = false;
|
|
686
|
-
constructor(options) {
|
|
687
|
-
super();
|
|
688
|
-
this.rateLimitKey = options.rateLimitKey;
|
|
689
|
-
this.retryPolicy = options.retryPolicy ?? DEFAULT_RETRY_POLICY;
|
|
690
|
-
this.adaptiveConcurrency = new AdaptiveConcurrency(options.maxConcurrency, options.minConcurrency);
|
|
691
|
-
this.slotQueue = new SlotQueue({
|
|
692
|
-
maxConcurrency: options.maxConcurrency,
|
|
693
|
-
minConcurrency: options.minConcurrency,
|
|
694
|
-
queueTimeoutMs: options.queueTimeoutMs,
|
|
695
|
-
onSlotAcquired: (queueDepth) => {
|
|
696
|
-
this.emit("slot:acquired", {
|
|
697
|
-
rateLimitKey: this.rateLimitKey,
|
|
698
|
-
queueDepth
|
|
699
|
-
});
|
|
700
|
-
},
|
|
701
|
-
onSlotReleased: (queueDepth) => {
|
|
702
|
-
this.emit("slot:released", {
|
|
703
|
-
rateLimitKey: this.rateLimitKey,
|
|
704
|
-
queueDepth
|
|
705
|
-
});
|
|
706
|
-
}
|
|
707
|
-
});
|
|
708
|
-
}
|
|
709
|
-
/**
|
|
710
|
-
* Execute a call with rate limiting and retry logic.
|
|
711
|
-
*/
|
|
712
|
-
async executeWithRetry(requestId, callFn, options) {
|
|
713
|
-
this.totalRequests++;
|
|
714
|
-
let attempt = 0;
|
|
715
|
-
const retryResults = [];
|
|
716
|
-
const retryPolicy = options.maxRetriesOverride === void 0 ? this.retryPolicy : {
|
|
717
|
-
...this.retryPolicy,
|
|
718
|
-
maxRetries: options.maxRetriesOverride
|
|
719
|
-
};
|
|
720
|
-
try {
|
|
721
|
-
while (true) {
|
|
722
|
-
try {
|
|
723
|
-
await this.slotQueue.acquire(`${requestId}-${attempt}`, options.abortSignal);
|
|
724
|
-
} catch (acquireError) {
|
|
725
|
-
this.emit(options.abortSignal?.aborted ? "queue:cancelled" : "queue:timeout", {
|
|
726
|
-
rateLimitKey: this.rateLimitKey,
|
|
727
|
-
requestId,
|
|
728
|
-
error: String(acquireError)
|
|
729
|
-
});
|
|
730
|
-
throw acquireError;
|
|
731
|
-
}
|
|
732
|
-
let ownsSlot = true;
|
|
733
|
-
let observedHeaders;
|
|
734
|
-
const onResponseHeaders = createResponseHeadersObserver(this, ([headers, backoff], alreadyObserved) => {
|
|
735
|
-
if (ownsSlot) {
|
|
736
|
-
if (backoff) {
|
|
737
|
-
if (!alreadyObserved) {
|
|
738
|
-
this.updateFromHeaders(headers, false, backoff.resetAt);
|
|
739
|
-
this.handleRateLimit(void 0, backoff.resetAt);
|
|
740
|
-
}
|
|
741
|
-
} else {
|
|
742
|
-
observedHeaders = headers;
|
|
743
|
-
if (!alreadyObserved) this.updateFromHeaders(headers, false);
|
|
744
|
-
}
|
|
745
|
-
return true;
|
|
746
|
-
}
|
|
747
|
-
return alreadyObserved;
|
|
748
|
-
});
|
|
749
|
-
const releaseSlot = () => {
|
|
750
|
-
if (ownsSlot) {
|
|
751
|
-
ownsSlot = false;
|
|
752
|
-
this.slotQueue.release();
|
|
753
|
-
}
|
|
754
|
-
};
|
|
755
|
-
const startTime = Date.now();
|
|
756
|
-
let retryError;
|
|
757
|
-
let retryResult;
|
|
758
|
-
let isRateLimited;
|
|
759
|
-
let isRetryableResult = false;
|
|
760
|
-
let retryAfterMs;
|
|
761
|
-
try {
|
|
762
|
-
throwIfAborted(options.abortSignal);
|
|
763
|
-
const result = await callFn(onResponseHeaders);
|
|
764
|
-
retryResult = result;
|
|
765
|
-
const hasErrorResponse = result !== null && typeof result === "object" && "error" in result && typeof result.error === "string" && result.error.length > 0;
|
|
766
|
-
const hasRefusalResponse = result !== null && typeof result === "object" && "isRefusal" in result && result.isRefusal === true;
|
|
767
|
-
const headers = options.getHeaders?.(result);
|
|
768
|
-
const isObserverError = isResponseHeadersObserverErrorResponse(result);
|
|
769
|
-
isRateLimited = options.canRetry?.() !== false && !isObserverError && (options.isRateLimited?.(result, void 0) ?? false);
|
|
770
|
-
isRetryableResult = options.canRetry?.() !== false && !isObserverError && (options.isRetryableResult?.(result) ?? false);
|
|
771
|
-
retryAfterMs = options.getRetryAfter?.(result, void 0);
|
|
772
|
-
if (!isObserverError && headers && (headers !== observedHeaders || isRateLimited)) this.updateFromHeaders(headers, isRateLimited);
|
|
773
|
-
if (isRateLimited) this.handleRateLimit(retryAfterMs);
|
|
774
|
-
if (this.latencies.push(Date.now() - startTime) > 100) this.latencies.shift();
|
|
775
|
-
releaseSlot();
|
|
776
|
-
if (options.abortSignal?.aborted && hasErrorResponse) {
|
|
777
|
-
this.failedRequests++;
|
|
778
|
-
return result;
|
|
779
|
-
}
|
|
780
|
-
if (!isRateLimited && !isRetryableResult || options.abortSignal?.aborted && hasRefusalResponse) {
|
|
781
|
-
let finalizedResult;
|
|
782
|
-
try {
|
|
783
|
-
finalizedResult = options.finalizeResult?.(result, retryResults) ?? result;
|
|
784
|
-
} catch (finalizerError) {
|
|
785
|
-
throw new ResultFinalizationError(finalizerError);
|
|
786
|
-
}
|
|
787
|
-
this.applyConcurrencyChange(this.adaptiveConcurrency.recordSuccess());
|
|
788
|
-
this.completedRequests++;
|
|
789
|
-
return finalizedResult;
|
|
790
|
-
}
|
|
791
|
-
} catch (error) {
|
|
792
|
-
if (ownsSlot) {
|
|
793
|
-
if (this.latencies.push(Date.now() - startTime) > 100) this.latencies.shift();
|
|
794
|
-
}
|
|
795
|
-
if (isResponseHeadersObserverError(onResponseHeaders, error)) throw error;
|
|
796
|
-
if (error instanceof ResultFinalizationError) throw error.original;
|
|
797
|
-
if (options.abortSignal?.aborted && (error === options.abortSignal.reason || !(error instanceof Error)) || error instanceof Error && (error.name === "AbortError" || error.name === "AbortException")) throw error;
|
|
798
|
-
retryError = error;
|
|
799
|
-
isRateLimited = options.canRetry?.() !== false && (options.isRateLimited?.(void 0, retryError) ?? this.isRateLimitError(retryError));
|
|
800
|
-
retryAfterMs = options.getRetryAfter?.(void 0, retryError);
|
|
801
|
-
if (isRateLimited) this.handleRateLimit(retryAfterMs);
|
|
802
|
-
if (options.abortSignal?.aborted) throw error;
|
|
803
|
-
} finally {
|
|
804
|
-
releaseSlot();
|
|
805
|
-
}
|
|
806
|
-
if (options.canRetry?.() === false || !shouldRetry(attempt, retryError, isRateLimited || isRetryableResult, retryPolicy)) {
|
|
807
|
-
if (retryError) throw retryError;
|
|
808
|
-
if (isRetryableResult) {
|
|
809
|
-
const finalizedResult = options.finalizeResult?.(retryResult, retryResults) ?? retryResult;
|
|
810
|
-
this.failedRequests++;
|
|
811
|
-
return finalizedResult;
|
|
812
|
-
}
|
|
813
|
-
if (!options.onRateLimitExhausted && options.finalizeResult) {
|
|
814
|
-
const finalizedResult = options.finalizeResult(retryResult, retryResults);
|
|
815
|
-
this.failedRequests++;
|
|
816
|
-
return finalizedResult;
|
|
817
|
-
}
|
|
818
|
-
throw new RateLimitExhaustedError(`Rate limit exceeded for ${this.rateLimitKey} after ${attempt + 1} attempts`, retryResult);
|
|
819
|
-
}
|
|
820
|
-
if (isRetryableResult && retryResult !== void 0) retryResults.push(retryResult);
|
|
821
|
-
attempt++;
|
|
822
|
-
await sleepWithAbort(this.recordRetry(attempt, retryPolicy, retryAfterMs, isRateLimited ? "ratelimit" : "error"), options.abortSignal);
|
|
823
|
-
}
|
|
824
|
-
} catch (error) {
|
|
825
|
-
this.failedRequests++;
|
|
826
|
-
throw error;
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
recordRetry(attempt, retryPolicy, retryAfterMs, reason) {
|
|
830
|
-
this.retriedRequests++;
|
|
831
|
-
const delayMs = getRetryDelay(attempt, retryPolicy, retryAfterMs);
|
|
832
|
-
this.emit("request:retrying", {
|
|
833
|
-
rateLimitKey: this.rateLimitKey,
|
|
834
|
-
attempt,
|
|
835
|
-
delayMs,
|
|
836
|
-
reason
|
|
837
|
-
});
|
|
838
|
-
return delayMs;
|
|
839
|
-
}
|
|
840
|
-
/**
|
|
841
|
-
* Update state from response headers.
|
|
842
|
-
* @param headers - Response headers
|
|
843
|
-
* @param isRateLimited - Whether the response indicates a rate limit (e.g., HTTP 429).
|
|
844
|
-
* When false, retry-after headers are ignored to prevent incorrectly blocking the
|
|
845
|
-
* queue on successful responses from providers/proxies that include these headers.
|
|
846
|
-
*/
|
|
847
|
-
updateFromHeaders(headers, isRateLimited, selectedResetAt) {
|
|
848
|
-
const parsed = parseRateLimitHeaders(headers);
|
|
849
|
-
if (selectedResetAt !== void 0) {
|
|
850
|
-
const existingResetAt = this.slotQueue.getResetAt();
|
|
851
|
-
parsed.resetAt = existingResetAt !== null && existingResetAt > Date.now() ? Math.max(existingResetAt, selectedResetAt) : selectedResetAt;
|
|
852
|
-
}
|
|
853
|
-
if (!this.hasLearnedLimits && (parsed.limitRequests !== void 0 || parsed.limitTokens !== void 0)) {
|
|
854
|
-
this.hasLearnedLimits = true;
|
|
855
|
-
this.emit("ratelimit:learned", {
|
|
856
|
-
rateLimitKey: this.rateLimitKey,
|
|
857
|
-
requestLimit: parsed.limitRequests,
|
|
858
|
-
tokenLimit: parsed.limitTokens
|
|
859
|
-
});
|
|
860
|
-
}
|
|
861
|
-
this.slotQueue.updateRateLimitState(parsed);
|
|
862
|
-
if (isRateLimited && parsed.retryAfterMs !== void 0) this.slotQueue.markRateLimited(parsed.retryAfterMs);
|
|
863
|
-
const ratios = this.slotQueue.getRemainingRatio();
|
|
864
|
-
const minRatio = Math.min(ratios.requests ?? 1, ratios.tokens ?? 1);
|
|
865
|
-
if (minRatio < .1) {
|
|
866
|
-
this.emit("ratelimit:warning", {
|
|
867
|
-
rateLimitKey: this.rateLimitKey,
|
|
868
|
-
requestRatio: ratios.requests,
|
|
869
|
-
tokenRatio: ratios.tokens
|
|
870
|
-
});
|
|
871
|
-
this.applyConcurrencyChange(this.adaptiveConcurrency.recordApproachingLimit(minRatio));
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
/**
|
|
875
|
-
* Handle rate limit hit.
|
|
876
|
-
* Delegates to SlotQueue which preserves existing resetAt from headers.
|
|
877
|
-
*/
|
|
878
|
-
handleRateLimit(retryAfterMs, selectedResetAt) {
|
|
879
|
-
this.rateLimitHits++;
|
|
880
|
-
this.slotQueue.markRateLimited(retryAfterMs, selectedResetAt);
|
|
881
|
-
const change = this.adaptiveConcurrency.recordRateLimit();
|
|
882
|
-
this.applyConcurrencyChange(change);
|
|
883
|
-
this.emit("ratelimit:hit", {
|
|
884
|
-
rateLimitKey: this.rateLimitKey,
|
|
885
|
-
retryAfterMs,
|
|
886
|
-
resetAt: this.slotQueue.getResetAt(),
|
|
887
|
-
concurrencyChange: change
|
|
888
|
-
});
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* Apply concurrency change and emit appropriate event.
|
|
892
|
-
*/
|
|
893
|
-
applyConcurrencyChange(change) {
|
|
894
|
-
if (change.changed) {
|
|
895
|
-
this.slotQueue.setMaxConcurrency(change.current);
|
|
896
|
-
this.emit(change.reason === "recovery" ? "concurrency:increased" : "concurrency:decreased", {
|
|
897
|
-
rateLimitKey: this.rateLimitKey,
|
|
898
|
-
...change
|
|
899
|
-
});
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
/**
|
|
903
|
-
* Check if error is a rate limit error.
|
|
904
|
-
*/
|
|
905
|
-
isRateLimitError(error) {
|
|
906
|
-
const message = (error.message ?? "").toLowerCase();
|
|
907
|
-
return message.includes("429") || message.includes("rate limit") || message.includes("too many requests");
|
|
908
|
-
}
|
|
909
|
-
/**
|
|
910
|
-
* Get current queue depth without sorting latencies.
|
|
911
|
-
* Use this for frequent checks instead of getMetrics().
|
|
912
|
-
*/
|
|
913
|
-
getQueueDepth() {
|
|
914
|
-
return this.slotQueue.getQueueDepth();
|
|
915
|
-
}
|
|
916
|
-
getMetrics() {
|
|
917
|
-
const sorted = [...this.latencies].sort((a, b) => a - b);
|
|
918
|
-
return {
|
|
919
|
-
rateLimitKey: this.rateLimitKey,
|
|
920
|
-
activeRequests: this.slotQueue.getActiveCount(),
|
|
921
|
-
maxConcurrency: this.slotQueue.getMaxConcurrency(),
|
|
922
|
-
queueDepth: this.slotQueue.getQueueDepth(),
|
|
923
|
-
totalRequests: this.totalRequests,
|
|
924
|
-
completedRequests: this.completedRequests,
|
|
925
|
-
failedRequests: this.failedRequests,
|
|
926
|
-
rateLimitHits: this.rateLimitHits,
|
|
927
|
-
retriedRequests: this.retriedRequests,
|
|
928
|
-
avgLatencyMs: sorted.length > 0 ? sorted.reduce((a, b) => a + b, 0) / sorted.length : 0,
|
|
929
|
-
p50LatencyMs: sorted[Math.floor((sorted.length - 1) * .5)] ?? 0,
|
|
930
|
-
p99LatencyMs: sorted[Math.floor((sorted.length - 1) * .99)] ?? 0
|
|
931
|
-
};
|
|
932
|
-
}
|
|
933
|
-
dispose() {
|
|
934
|
-
this.slotQueue.dispose();
|
|
935
|
-
this.removeAllListeners();
|
|
936
|
-
}
|
|
937
|
-
};
|
|
938
|
-
//#endregion
|
|
939
|
-
//#region src/scheduler/rateLimitKey.ts
|
|
940
|
-
/**
|
|
941
|
-
* Generate a rate limit key that identifies a unique rate limit pool.
|
|
942
|
-
* Same provider with different API keys/regions get different keys.
|
|
943
|
-
*/
|
|
944
|
-
function getRateLimitKey(provider) {
|
|
945
|
-
const providerId = provider.id();
|
|
946
|
-
const config = provider.config || {};
|
|
947
|
-
const relevantConfig = {};
|
|
948
|
-
if (config.apiKey && config.apiKey.length > 4) relevantConfig.apiKeyTail = config.apiKey.slice(-4);
|
|
949
|
-
if (config.apiBaseUrl) relevantConfig.apiBaseUrl = config.apiBaseUrl;
|
|
950
|
-
if (config.region) relevantConfig.region = config.region;
|
|
951
|
-
if (config.organization) relevantConfig.organization = config.organization;
|
|
952
|
-
const configParts = Object.entries(relevantConfig).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|");
|
|
953
|
-
if (configParts)
|
|
954
|
-
/**
|
|
955
|
-
* Hash a string using SHA-256.
|
|
956
|
-
* Returns first 12 chars of hex digest (48 bits).
|
|
957
|
-
*/
|
|
958
|
-
return `${providerId}[${createHash("sha256").update(configParts).digest("hex").slice(0, 12)}]`;
|
|
959
|
-
return providerId;
|
|
960
|
-
}
|
|
961
|
-
//#endregion
|
|
962
|
-
//#region src/scheduler/rateLimitRegistry.ts
|
|
963
|
-
/**
|
|
964
|
-
* Per-eval registry that manages rate limit state for all providers.
|
|
965
|
-
* NOT a singleton - create one per evaluation context.
|
|
966
|
-
*/
|
|
967
|
-
var RateLimitRegistry = class extends EventEmitter {
|
|
968
|
-
states = /* @__PURE__ */ new Map();
|
|
969
|
-
maxConcurrency;
|
|
970
|
-
minConcurrency;
|
|
971
|
-
queueTimeoutMs;
|
|
972
|
-
enabled;
|
|
973
|
-
constructor(options) {
|
|
974
|
-
super();
|
|
975
|
-
this.maxConcurrency = options.maxConcurrency;
|
|
976
|
-
this.minConcurrency = options.minConcurrency ?? getEnvInt("PROMPTFOO_MIN_CONCURRENCY", 1);
|
|
977
|
-
this.queueTimeoutMs = options.queueTimeoutMs ?? getEnvInt("PROMPTFOO_SCHEDULER_QUEUE_TIMEOUT_MS", 3e5);
|
|
978
|
-
this.enabled = !getEnvBool("PROMPTFOO_DISABLE_ADAPTIVE_SCHEDULER", false);
|
|
979
|
-
}
|
|
980
|
-
/**
|
|
981
|
-
* Execute a provider call with rate limiting and retries.
|
|
982
|
-
*
|
|
983
|
-
* Note: No idempotency tracking. Each call is independent.
|
|
984
|
-
* The single integration point (evaluator) ensures no double-wrapping.
|
|
985
|
-
*/
|
|
986
|
-
async execute(provider, callFn, options) {
|
|
987
|
-
const providerMaxRetries = getProviderMaxRetries(provider);
|
|
988
|
-
if (!this.enabled) return withFetchRetryContext(providerMaxRetries, () => runProviderCallWithAbort(callFn, options?.abortSignal));
|
|
989
|
-
const rateLimitKey = getRateLimitKey(provider);
|
|
990
|
-
const parentContext = getProviderCallExecutionContext();
|
|
991
|
-
if (parentContext?.rateLimitProvider && getRateLimitKey(parentContext.rateLimitProvider) !== rateLimitKey) parentContext.onNestedScheduledCall?.();
|
|
992
|
-
let nestedCallStarted = false;
|
|
993
|
-
if (!this.states.has(rateLimitKey)) {
|
|
994
|
-
const state = new ProviderRateLimitState({
|
|
995
|
-
rateLimitKey,
|
|
996
|
-
maxConcurrency: this.maxConcurrency,
|
|
997
|
-
minConcurrency: this.minConcurrency,
|
|
998
|
-
queueTimeoutMs: this.queueTimeoutMs
|
|
999
|
-
});
|
|
1000
|
-
state.on("ratelimit:hit", (data) => this.emit("ratelimit:hit", data));
|
|
1001
|
-
state.on("ratelimit:warning", (data) => this.emit("ratelimit:warning", data));
|
|
1002
|
-
state.on("ratelimit:learned", (data) => this.emit("ratelimit:learned", data));
|
|
1003
|
-
state.on("concurrency:increased", (data) => this.emit("concurrency:increased", data));
|
|
1004
|
-
state.on("concurrency:decreased", (data) => this.emit("concurrency:decreased", data));
|
|
1005
|
-
state.on("request:retrying", (data) => this.emit("request:retrying", data));
|
|
1006
|
-
this.states.set(rateLimitKey, state);
|
|
1007
|
-
}
|
|
1008
|
-
const state = this.states.get(rateLimitKey);
|
|
1009
|
-
const requestId = `${rateLimitKey}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
1010
|
-
this.emit("request:started", {
|
|
1011
|
-
rateLimitKey,
|
|
1012
|
-
requestId,
|
|
1013
|
-
queueDepth: state.getQueueDepth()
|
|
1014
|
-
});
|
|
1015
|
-
const run = () => state.executeWithRetry(requestId, (onResponseHeaders) => {
|
|
1016
|
-
const executionContext = getProviderCallExecutionContext();
|
|
1017
|
-
return executionContext ? withProviderCallExecutionContext({
|
|
1018
|
-
...executionContext,
|
|
1019
|
-
rateLimitRegistry: this,
|
|
1020
|
-
rateLimitProvider: provider,
|
|
1021
|
-
onNestedScheduledCall: () => {
|
|
1022
|
-
nestedCallStarted = true;
|
|
1023
|
-
}
|
|
1024
|
-
}, () => callFn(onResponseHeaders)) : callFn(onResponseHeaders);
|
|
1025
|
-
}, {
|
|
1026
|
-
abortSignal: options?.abortSignal,
|
|
1027
|
-
getHeaders: (result) => nestedCallStarted ? void 0 : options?.getHeaders?.(result),
|
|
1028
|
-
isRateLimited: options?.isRateLimited,
|
|
1029
|
-
isRetryableResult: options?.isRetryableResult,
|
|
1030
|
-
finalizeResult: options?.finalizeResult,
|
|
1031
|
-
onRateLimitExhausted: options?.onRateLimitExhausted,
|
|
1032
|
-
canRetry: () => !nestedCallStarted,
|
|
1033
|
-
getRetryAfter: options?.getRetryAfter,
|
|
1034
|
-
maxRetriesOverride: provider.handlesOwnRetries ? 0 : providerMaxRetries
|
|
1035
|
-
});
|
|
1036
|
-
try {
|
|
1037
|
-
const result = await withFetchRetryContext(providerMaxRetries, () => runProviderCallWithAbort(run, options?.abortSignal));
|
|
1038
|
-
this.emit("request:completed", {
|
|
1039
|
-
rateLimitKey,
|
|
1040
|
-
requestId
|
|
1041
|
-
});
|
|
1042
|
-
return result;
|
|
1043
|
-
} catch (error) {
|
|
1044
|
-
this.emit("request:failed", {
|
|
1045
|
-
rateLimitKey,
|
|
1046
|
-
requestId,
|
|
1047
|
-
error: String(error)
|
|
1048
|
-
});
|
|
1049
|
-
if (error instanceof RateLimitExhaustedError && options?.onRateLimitExhausted) return options.onRateLimitExhausted(error.result, error);
|
|
1050
|
-
throw error;
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
/**
|
|
1054
|
-
* Get metrics for all tracked providers.
|
|
1055
|
-
*/
|
|
1056
|
-
getMetrics() {
|
|
1057
|
-
const metrics = {};
|
|
1058
|
-
for (const [key, state] of this.states) metrics[key] = state.getMetrics();
|
|
1059
|
-
return metrics;
|
|
1060
|
-
}
|
|
1061
|
-
/**
|
|
1062
|
-
* Cleanup all resources.
|
|
1063
|
-
*/
|
|
1064
|
-
dispose() {
|
|
1065
|
-
for (const state of this.states.values()) state.dispose();
|
|
1066
|
-
this.states.clear();
|
|
1067
|
-
this.removeAllListeners();
|
|
1068
|
-
}
|
|
1069
|
-
};
|
|
1070
|
-
/**
|
|
1071
|
-
* Read the provider's configured maxRetries value, tolerating numeric strings
|
|
1072
|
-
* (e.g. from environment overrides) and rejecting invalid values.
|
|
1073
|
-
*
|
|
1074
|
-
* Returning `undefined` means "fall back to defaults" — distinct from `0`, which
|
|
1075
|
-
* means "disable retries". Invalid user-supplied values (negatives, floats,
|
|
1076
|
-
* non-numeric strings) are logged so config typos aren't silently ignored.
|
|
1077
|
-
*/
|
|
1078
|
-
function getProviderMaxRetries(provider) {
|
|
1079
|
-
const raw = provider.config && typeof provider.config === "object" ? provider.config.maxRetries : void 0;
|
|
1080
|
-
if (raw === void 0) return;
|
|
1081
|
-
if (typeof raw === "number" && Number.isInteger(raw) && raw >= 0) return raw;
|
|
1082
|
-
if (typeof raw === "string") {
|
|
1083
|
-
const trimmed = raw.trim();
|
|
1084
|
-
if (/^\d+$/.test(trimmed)) {
|
|
1085
|
-
const parsed = Number(trimmed);
|
|
1086
|
-
if (Number.isSafeInteger(parsed)) return parsed;
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
logger.warn("[RateLimit] Ignoring invalid provider.config.maxRetries; expected a non-negative integer.", {
|
|
1090
|
-
maxRetries: raw,
|
|
1091
|
-
providerId: sanitizeProviderIdForLog(provider.id())
|
|
1092
|
-
});
|
|
1093
|
-
}
|
|
1094
|
-
//#endregion
|
|
1095
|
-
//#region src/util/tokenUsage.ts
|
|
1096
|
-
/**
|
|
1097
|
-
* A utility class for tracking token usage across an evaluation.
|
|
1098
|
-
*
|
|
1099
|
-
* @deprecated Use OpenTelemetry tracing instead for per-call token tracking.
|
|
1100
|
-
* This class provides only cumulative totals and will be removed in a future version.
|
|
1101
|
-
*
|
|
1102
|
-
* For new implementations, use the OTEL-based tracing infrastructure:
|
|
1103
|
-
* - Enable tracing with `PROMPTFOO_OTEL_ENABLED=true`
|
|
1104
|
-
* - Token usage is automatically captured as GenAI semantic convention span attributes
|
|
1105
|
-
*
|
|
1106
|
-
* @see src/tracing/genaiTracer.ts for the new tracing implementation
|
|
1107
|
-
*/
|
|
1108
|
-
var TokenUsageTracker = class TokenUsageTracker {
|
|
1109
|
-
static instance;
|
|
1110
|
-
providersMap = /* @__PURE__ */ new Map();
|
|
1111
|
-
constructor() {}
|
|
1112
|
-
/**
|
|
1113
|
-
* Get the singleton instance of TokenUsageTracker
|
|
1114
|
-
*/
|
|
1115
|
-
static getInstance() {
|
|
1116
|
-
if (!TokenUsageTracker.instance) TokenUsageTracker.instance = new TokenUsageTracker();
|
|
1117
|
-
return TokenUsageTracker.instance;
|
|
1118
|
-
}
|
|
1119
|
-
/**
|
|
1120
|
-
* Track token usage for a provider
|
|
1121
|
-
* @param provider The provider to track usage for
|
|
1122
|
-
* @param usage The token usage to track
|
|
1123
|
-
*/
|
|
1124
|
-
trackUsage(providerId, usage = { numRequests: 1 }) {
|
|
1125
|
-
const updated = { ...this.providersMap.get(providerId) ?? createEmptyTokenUsage() };
|
|
1126
|
-
accumulateTokenUsage(updated, usage);
|
|
1127
|
-
this.providersMap.set(providerId, updated);
|
|
1128
|
-
logger.debug(`Tracked token usage for ${sanitizeProviderIdForLog(providerId)}: total=${usage.total ?? 0}, cached=${usage.cached ?? 0}`);
|
|
1129
|
-
}
|
|
1130
|
-
/**
|
|
1131
|
-
* Track token usage from one provider response while preserving the shared
|
|
1132
|
-
* response-aware request-counting contract.
|
|
1133
|
-
*/
|
|
1134
|
-
trackResponseUsage(providerId, response) {
|
|
1135
|
-
if (!response) return;
|
|
1136
|
-
let tokenUsage;
|
|
1137
|
-
try {
|
|
1138
|
-
const rawTokenUsage = response.tokenUsage;
|
|
1139
|
-
if (rawTokenUsage) {
|
|
1140
|
-
const parsedTokenUsage = BaseTokenUsageSchema.safeParse(rawTokenUsage);
|
|
1141
|
-
if (parsedTokenUsage.success) tokenUsage = parsedTokenUsage.data;
|
|
1142
|
-
}
|
|
1143
|
-
} catch {
|
|
1144
|
-
tokenUsage = void 0;
|
|
1145
|
-
}
|
|
1146
|
-
const updated = { ...this.providersMap.get(providerId) ?? createEmptyTokenUsage() };
|
|
1147
|
-
const accounting = createEmptyTokenUsage();
|
|
1148
|
-
accumulateResponseTokenUsage(accounting, {
|
|
1149
|
-
cached: response.cached,
|
|
1150
|
-
tokenUsage
|
|
1151
|
-
});
|
|
1152
|
-
accumulateTokenUsage(updated, {
|
|
1153
|
-
...accounting.incurredTokenUsage ?? accounting,
|
|
1154
|
-
cached: accounting.cached
|
|
1155
|
-
});
|
|
1156
|
-
this.providersMap.set(providerId, updated);
|
|
1157
|
-
logger.debug(`Tracked response usage for ${sanitizeProviderIdForLog(providerId)}: total=${tokenUsage?.total ?? 0}, cached=${tokenUsage?.cached ?? 0}`);
|
|
1158
|
-
}
|
|
1159
|
-
/**
|
|
1160
|
-
* Get the cumulative token usage for a specific provider
|
|
1161
|
-
* @param providerId The ID of the provider to get usage for
|
|
1162
|
-
* @returns A detached snapshot of the token usage for the provider
|
|
1163
|
-
*/
|
|
1164
|
-
getProviderUsage(providerId) {
|
|
1165
|
-
return structuredClone(this.providersMap.get(providerId));
|
|
1166
|
-
}
|
|
1167
|
-
/**
|
|
1168
|
-
* Get all provider IDs that have token usage tracked
|
|
1169
|
-
* @returns Array of provider IDs
|
|
1170
|
-
*/
|
|
1171
|
-
getProviderIds() {
|
|
1172
|
-
return Array.from(this.providersMap.keys());
|
|
1173
|
-
}
|
|
1174
|
-
/**
|
|
1175
|
-
* Get aggregated token usage across all providers
|
|
1176
|
-
* @returns Aggregated token usage
|
|
1177
|
-
*/
|
|
1178
|
-
getTotalUsage() {
|
|
1179
|
-
const result = createEmptyTokenUsage();
|
|
1180
|
-
for (const usage of this.providersMap.values()) accumulateTokenUsage(result, usage);
|
|
1181
|
-
return result;
|
|
1182
|
-
}
|
|
1183
|
-
/**
|
|
1184
|
-
* Reset token usage for a specific provider
|
|
1185
|
-
* @param providerId The ID of the provider to reset
|
|
1186
|
-
*/
|
|
1187
|
-
resetProviderUsage(providerId) {
|
|
1188
|
-
this.providersMap.delete(providerId);
|
|
1189
|
-
}
|
|
1190
|
-
/**
|
|
1191
|
-
* Reset token usage for all providers
|
|
1192
|
-
*/
|
|
1193
|
-
resetAllUsage() {
|
|
1194
|
-
this.providersMap.clear();
|
|
1195
|
-
}
|
|
1196
|
-
/**
|
|
1197
|
-
* Cleanup method to prevent memory leaks
|
|
1198
|
-
*/
|
|
1199
|
-
cleanup() {
|
|
1200
|
-
this.providersMap.clear();
|
|
1201
|
-
}
|
|
1202
|
-
};
|
|
1203
|
-
//#endregion
|
|
1204
|
-
//#region src/redteam/grading/storedResult.ts
|
|
1205
|
-
/** Opaque runtime values cannot safely identify a reusable assertion configuration. */
|
|
1206
|
-
function getGradingAssertionHash(assertion) {
|
|
1207
|
-
if (!assertion) return;
|
|
1208
|
-
try {
|
|
1209
|
-
const serialized = JSON.stringify(assertion, function(key, value) {
|
|
1210
|
-
const original = this[key];
|
|
1211
|
-
if (typeof original === "function" || typeof original === "symbol") throw new Error("Assertion contains a runtime value");
|
|
1212
|
-
if (original && typeof original === "object") {
|
|
1213
|
-
const prototype = Object.getPrototypeOf(original);
|
|
1214
|
-
if (prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null || typeof original.toJSON === "function") throw new Error("Assertion contains a runtime object");
|
|
1215
|
-
}
|
|
1216
|
-
return value;
|
|
1217
|
-
});
|
|
1218
|
-
return createHash("sha256").update(serialized).digest("hex");
|
|
1219
|
-
} catch {
|
|
1220
|
-
return;
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
/** Bind a verdict to its target turn without persisting another copy of the conversation. */
|
|
1224
|
-
function getGradingInputHash(prompt, output, messages, pluginId) {
|
|
1225
|
-
const conversation = Array.isArray(messages) ? messages.filter((message) => (message?.role === "user" || message?.role === "assistant") && typeof message.content === "string").map(({ role, content }) => ({
|
|
1226
|
-
role,
|
|
1227
|
-
content
|
|
1228
|
-
})) : [];
|
|
1229
|
-
return createHash("sha256").update(JSON.stringify([
|
|
1230
|
-
pluginId,
|
|
1231
|
-
prompt,
|
|
1232
|
-
output,
|
|
1233
|
-
conversation
|
|
1234
|
-
])).digest("hex");
|
|
1235
|
-
}
|
|
1236
|
-
function getTargetConversation(messages) {
|
|
1237
|
-
if (!Array.isArray(messages)) return {};
|
|
1238
|
-
let lastUserIndex = -1;
|
|
1239
|
-
for (let index = messages.length - 1; index >= 0; index--) if (messages[index]?.role === "user" && typeof messages[index].content === "string") {
|
|
1240
|
-
lastUserIndex = index;
|
|
1241
|
-
break;
|
|
1242
|
-
}
|
|
1243
|
-
if (lastUserIndex < 0 || !messages[lastUserIndex].content.trim()) return {};
|
|
1244
|
-
const conversationTranscript = messages.slice(0, lastUserIndex).filter((message) => (message?.role === "user" || message?.role === "assistant") && typeof message.content === "string").map((message) => `${message.role === "user" ? "User" : "Assistant"}: ${message.content}`).join("\n\n");
|
|
1245
|
-
return {
|
|
1246
|
-
lastUserPrompt: messages[lastUserIndex].content,
|
|
1247
|
-
conversationTranscript
|
|
1248
|
-
};
|
|
1249
|
-
}
|
|
1250
|
-
/** Attach cumulative usage without marking fresh work as a cached response. */
|
|
1251
|
-
function withGradingUsage(result, tokensUsed) {
|
|
1252
|
-
if (result.metadata?.cachedResponse === true && (tokensUsed?.numRequests ?? 0) > 0) {
|
|
1253
|
-
const { cachedResponse: _cachedResponse, ...metadata } = result.metadata;
|
|
1254
|
-
return {
|
|
1255
|
-
...result,
|
|
1256
|
-
metadata,
|
|
1257
|
-
tokensUsed
|
|
1258
|
-
};
|
|
1259
|
-
}
|
|
1260
|
-
return {
|
|
1261
|
-
...result,
|
|
1262
|
-
tokensUsed
|
|
1263
|
-
};
|
|
1264
|
-
}
|
|
1265
|
-
//#endregion
|
|
1266
|
-
//#region src/redteam/shared/promptLength.ts
|
|
1267
|
-
const MAX_CHARS_PER_MESSAGE_MODIFIER_KEY = "maxCharsPerMessage";
|
|
1268
|
-
function isRecord(value) {
|
|
1269
|
-
return typeof value === "object" && value !== null;
|
|
1270
|
-
}
|
|
1271
|
-
function getMaxCharsPerMessage(limit) {
|
|
1272
|
-
const maxCharsPerMessage = limit ?? state.config?.redteam?.maxCharsPerMessage;
|
|
1273
|
-
if (typeof maxCharsPerMessage !== "number" || !Number.isInteger(maxCharsPerMessage) || maxCharsPerMessage <= 0) return;
|
|
1274
|
-
return maxCharsPerMessage;
|
|
1275
|
-
}
|
|
1276
|
-
function parseChatMessages(prompt) {
|
|
1277
|
-
try {
|
|
1278
|
-
const parsed = JSON.parse(prompt);
|
|
1279
|
-
if (Array.isArray(parsed) && parsed.every((item) => isRecord(item) && typeof item.role === "string" && typeof item.content === "string")) return parsed.map((message, index) => ({
|
|
1280
|
-
content: message.content,
|
|
1281
|
-
path: `[${index}].content`,
|
|
1282
|
-
role: message.role
|
|
1283
|
-
}));
|
|
1284
|
-
if (isRecord(parsed) && parsed._promptfoo_audio_hybrid === true && (parsed.history === void 0 || Array.isArray(parsed.history)) && isRecord(parsed.currentTurn) && typeof parsed.currentTurn.role === "string" && typeof parsed.currentTurn.transcript === "string" && (parsed.history === void 0 || parsed.history.every((item) => isRecord(item) && typeof item.role === "string" && typeof item.content === "string"))) return [...(parsed.history ?? []).map((message, index) => ({
|
|
1285
|
-
content: message.content,
|
|
1286
|
-
path: `history[${index}].content`,
|
|
1287
|
-
role: message.role
|
|
1288
|
-
})), {
|
|
1289
|
-
content: parsed.currentTurn.transcript,
|
|
1290
|
-
path: "currentTurn.transcript",
|
|
1291
|
-
role: parsed.currentTurn.role
|
|
1292
|
-
}];
|
|
1293
|
-
} catch {}
|
|
1294
|
-
}
|
|
1295
|
-
function getPromptLengthViolation(prompt, limit) {
|
|
1296
|
-
const maxCharsPerMessage = getMaxCharsPerMessage(limit);
|
|
1297
|
-
if (!maxCharsPerMessage) return;
|
|
1298
|
-
const messages = parseChatMessages(prompt);
|
|
1299
|
-
if (messages) {
|
|
1300
|
-
const oversizedMessage = messages.find((message) => message.role === "user" && message.content.length > maxCharsPerMessage);
|
|
1301
|
-
return oversizedMessage ? {
|
|
1302
|
-
length: oversizedMessage.content.length,
|
|
1303
|
-
limit: maxCharsPerMessage,
|
|
1304
|
-
path: oversizedMessage.path
|
|
1305
|
-
} : void 0;
|
|
1306
|
-
}
|
|
1307
|
-
if (prompt.length <= maxCharsPerMessage) return;
|
|
1308
|
-
return {
|
|
1309
|
-
length: prompt.length,
|
|
1310
|
-
limit: maxCharsPerMessage,
|
|
1311
|
-
path: "prompt"
|
|
1312
|
-
};
|
|
1313
|
-
}
|
|
1314
|
-
function getMaxCharsPerMessageModifierValue(limit) {
|
|
1315
|
-
const maxCharsPerMessage = getMaxCharsPerMessage(limit);
|
|
1316
|
-
if (!maxCharsPerMessage) return;
|
|
1317
|
-
return `Each generated user message must be ${maxCharsPerMessage} characters or fewer.`;
|
|
1318
|
-
}
|
|
1319
|
-
function getGeneratedPromptOverLimit(prompt, limit) {
|
|
1320
|
-
const violation = getPromptLengthViolation(prompt, limit);
|
|
1321
|
-
if (!violation) return;
|
|
1322
|
-
return {
|
|
1323
|
-
length: violation.length,
|
|
1324
|
-
limit: violation.limit
|
|
1325
|
-
};
|
|
1326
|
-
}
|
|
1327
|
-
function throwIfTargetPromptExceedsMaxChars(prompt, limit) {
|
|
1328
|
-
const violation = getPromptLengthViolation(prompt, limit);
|
|
1329
|
-
if (!violation) return;
|
|
1330
|
-
throw new Error(`Target prompt message at ${violation.path} exceeds maxCharsPerMessage=${violation.limit}: ${violation.length} characters.`);
|
|
1331
|
-
}
|
|
1332
|
-
//#endregion
|
|
1333
|
-
//#region src/redteam/providers/constants.ts
|
|
1334
|
-
const ATTACKER_MODEL = "gpt-5.5-2026-04-23";
|
|
1335
|
-
const ATTACKER_MODEL_SMALL = "gpt-5.4-mini-2026-03-17";
|
|
1336
|
-
const TEMPERATURE = getEnvFloat("PROMPTFOO_JAILBREAK_TEMPERATURE") ? getEnvFloat("PROMPTFOO_JAILBREAK_TEMPERATURE") : .7;
|
|
1337
|
-
/** Count a blocking-analysis task as grading without treating it as a target or attacker call. */
|
|
1338
|
-
function accumulateUnblockingTokenUsage(totalTokenUsage, result) {
|
|
1339
|
-
if (!result.attempted && !result.tokenUsage) return;
|
|
1340
|
-
accumulateGradingResponseTokenUsage(totalTokenUsage, {
|
|
1341
|
-
cached: result.cached,
|
|
1342
|
-
tokenUsage: result.tokenUsage?.assertions ?? result.tokenUsage
|
|
1343
|
-
});
|
|
1344
|
-
}
|
|
1345
|
-
const defaultRedteamProviderLoader = async (providers) => {
|
|
1346
|
-
const { loadApiProviders } = await import("./server/index.js").then((n) => n.s);
|
|
1347
|
-
return loadApiProviders(providers);
|
|
1348
|
-
};
|
|
1349
|
-
let redteamProviderLoader = defaultRedteamProviderLoader;
|
|
1350
|
-
async function loadRedteamProvider({ provider, jsonOnly = false, preferSmallModel = false, purpose = "redteam" } = {}) {
|
|
1351
|
-
let ret;
|
|
1352
|
-
const redteamProvider = provider;
|
|
1353
|
-
if (isApiProvider(redteamProvider)) {
|
|
1354
|
-
logger.debug(`Using ${purpose} provider: ${redteamProvider}`);
|
|
1355
|
-
ret = redteamProvider;
|
|
1356
|
-
} else if (typeof redteamProvider === "string" || isProviderOptions(redteamProvider)) {
|
|
1357
|
-
logger.debug(`Loading ${purpose} provider`, { provider: redteamProvider });
|
|
1358
|
-
ret = (await redteamProviderLoader([redteamProvider]))[0];
|
|
1359
|
-
} else {
|
|
1360
|
-
const defaultModel = preferSmallModel ? ATTACKER_MODEL_SMALL : ATTACKER_MODEL;
|
|
1361
|
-
logger.debug(`Using default ${purpose} provider: ${defaultModel}`);
|
|
1362
|
-
ret = new OpenAiChatCompletionProvider(defaultModel, { config: {
|
|
1363
|
-
temperature: TEMPERATURE,
|
|
1364
|
-
response_format: jsonOnly ? { type: "json_object" } : void 0
|
|
1365
|
-
} });
|
|
1366
|
-
}
|
|
1367
|
-
return ret;
|
|
1368
|
-
}
|
|
1369
|
-
var RedteamProviderManager = class {
|
|
1370
|
-
provider;
|
|
1371
|
-
providerSpec;
|
|
1372
|
-
jsonOnlyProvider;
|
|
1373
|
-
multilingualProvider;
|
|
1374
|
-
gradingProvider;
|
|
1375
|
-
gradingJsonOnlyProvider;
|
|
1376
|
-
rateLimitRegistry;
|
|
1377
|
-
/**
|
|
1378
|
-
* Set the rate limit registry to use for wrapping providers.
|
|
1379
|
-
* When set, all providers returned by this manager will be wrapped
|
|
1380
|
-
* with rate limiting.
|
|
1381
|
-
*/
|
|
1382
|
-
setRateLimitRegistry(registry) {
|
|
1383
|
-
this.rateLimitRegistry = registry;
|
|
1384
|
-
}
|
|
1385
|
-
/**
|
|
1386
|
-
* Wrap a provider with rate limiting if a registry is configured.
|
|
1387
|
-
*/
|
|
1388
|
-
wrapProvider(provider) {
|
|
1389
|
-
if (this.rateLimitRegistry) return wrapProviderWithRateLimiting(provider, this.rateLimitRegistry);
|
|
1390
|
-
return provider;
|
|
1391
|
-
}
|
|
1392
|
-
clearProvider() {
|
|
1393
|
-
this.provider = void 0;
|
|
1394
|
-
this.providerSpec = void 0;
|
|
1395
|
-
this.jsonOnlyProvider = void 0;
|
|
1396
|
-
this.multilingualProvider = void 0;
|
|
1397
|
-
this.gradingProvider = void 0;
|
|
1398
|
-
this.gradingJsonOnlyProvider = void 0;
|
|
1399
|
-
}
|
|
1400
|
-
async setProvider(provider) {
|
|
1401
|
-
const loadedProvider = await loadRedteamProvider({ provider });
|
|
1402
|
-
const loadedJsonOnlyProvider = await loadRedteamProvider({
|
|
1403
|
-
provider,
|
|
1404
|
-
jsonOnly: true
|
|
1405
|
-
});
|
|
1406
|
-
this.providerSpec = typeof provider === "string" || isProviderOptions(provider) ? provider : void 0;
|
|
1407
|
-
this.provider = loadedProvider;
|
|
1408
|
-
this.jsonOnlyProvider = loadedJsonOnlyProvider;
|
|
1409
|
-
}
|
|
1410
|
-
getDefaultTestProvider() {
|
|
1411
|
-
if (typeof state.config?.defaultTest !== "object") return;
|
|
1412
|
-
return state.config.defaultTest?.provider || state.config.defaultTest?.options?.provider?.text || state.config.defaultTest?.options?.provider || void 0;
|
|
1413
|
-
}
|
|
1414
|
-
resolveProviderCandidate({ provider, fallbackProvider, ignoreCliState = false } = {}) {
|
|
1415
|
-
const toSpec = (value) => typeof value === "string" || isProviderOptions(value) ? value : void 0;
|
|
1416
|
-
if (provider) return {
|
|
1417
|
-
source: "explicit",
|
|
1418
|
-
provider,
|
|
1419
|
-
spec: toSpec(provider)
|
|
1420
|
-
};
|
|
1421
|
-
if (this.provider && this.jsonOnlyProvider) return {
|
|
1422
|
-
source: "cache",
|
|
1423
|
-
cachedProvider: this.provider,
|
|
1424
|
-
cachedJsonOnlyProvider: this.jsonOnlyProvider,
|
|
1425
|
-
spec: this.providerSpec
|
|
1426
|
-
};
|
|
1427
|
-
if (fallbackProvider) return {
|
|
1428
|
-
source: "fallback",
|
|
1429
|
-
provider: fallbackProvider,
|
|
1430
|
-
spec: toSpec(fallbackProvider)
|
|
1431
|
-
};
|
|
1432
|
-
if (ignoreCliState) return { source: "default" };
|
|
1433
|
-
const configuredProvider = state.config?.redteam?.provider;
|
|
1434
|
-
if (configuredProvider) return {
|
|
1435
|
-
source: "explicit",
|
|
1436
|
-
provider: configuredProvider,
|
|
1437
|
-
spec: toSpec(configuredProvider)
|
|
1438
|
-
};
|
|
1439
|
-
const defaultTestProvider = this.getDefaultTestProvider();
|
|
1440
|
-
if (defaultTestProvider) return {
|
|
1441
|
-
source: "explicit",
|
|
1442
|
-
provider: defaultTestProvider,
|
|
1443
|
-
spec: toSpec(defaultTestProvider)
|
|
1444
|
-
};
|
|
1445
|
-
return { source: "default" };
|
|
1446
|
-
}
|
|
1447
|
-
async loadProviderCandidate(candidate, { jsonOnly = false, preferSmallModel = false } = {}) {
|
|
1448
|
-
if (candidate.source === "cache") {
|
|
1449
|
-
const cachedProvider = jsonOnly ? candidate.cachedJsonOnlyProvider : candidate.cachedProvider;
|
|
1450
|
-
invariant(cachedProvider, "Expected cached redteam provider variant to be set");
|
|
1451
|
-
logger.debug("[RedteamProviderManager] Using cached redteam provider: " + cachedProvider.id());
|
|
1452
|
-
return this.wrapProvider(cachedProvider);
|
|
1453
|
-
}
|
|
1454
|
-
const loaded = await loadRedteamProvider({
|
|
1455
|
-
provider: candidate.provider,
|
|
1456
|
-
jsonOnly,
|
|
1457
|
-
preferSmallModel
|
|
1458
|
-
});
|
|
1459
|
-
logger.debug("[RedteamProviderManager] Loaded " + candidate.source + " redteam provider: " + loaded.id());
|
|
1460
|
-
return this.wrapProvider(loaded);
|
|
1461
|
-
}
|
|
1462
|
-
/**
|
|
1463
|
-
* Resolves runtime provider, provenance, local-only spec, and safe persisted ID
|
|
1464
|
-
* through one precedence walk.
|
|
1465
|
-
*/
|
|
1466
|
-
async getProviderSelection({ provider, fallbackProvider, ignoreCliState = false, jsonOnly = false, preferSmallModel = false } = {}) {
|
|
1467
|
-
const candidate = this.resolveProviderCandidate({
|
|
1468
|
-
provider,
|
|
1469
|
-
fallbackProvider,
|
|
1470
|
-
ignoreCliState
|
|
1471
|
-
});
|
|
1472
|
-
return {
|
|
1473
|
-
provider: await this.loadProviderCandidate(candidate, {
|
|
1474
|
-
jsonOnly,
|
|
1475
|
-
preferSmallModel
|
|
1476
|
-
}),
|
|
1477
|
-
source: candidate.source,
|
|
1478
|
-
localProviderSpec: candidate.spec,
|
|
1479
|
-
persistableId: typeof candidate.spec === "string" ? candidate.spec : void 0
|
|
1480
|
-
};
|
|
1481
|
-
}
|
|
1482
|
-
/**
|
|
1483
|
-
* Loads the built-in attacker model without consulting cache or CLI state.
|
|
1484
|
-
*/
|
|
1485
|
-
async getDefaultProvider({ jsonOnly = false, preferSmallModel = false } = {}) {
|
|
1486
|
-
const provider = await loadRedteamProvider({
|
|
1487
|
-
jsonOnly,
|
|
1488
|
-
preferSmallModel
|
|
1489
|
-
});
|
|
1490
|
-
return this.wrapProvider(provider);
|
|
1491
|
-
}
|
|
1492
|
-
async setMultilingualProvider(provider) {
|
|
1493
|
-
this.multilingualProvider = await loadRedteamProvider({
|
|
1494
|
-
provider,
|
|
1495
|
-
jsonOnly: true
|
|
1496
|
-
});
|
|
1497
|
-
}
|
|
1498
|
-
async setGradingProvider(provider) {
|
|
1499
|
-
this.gradingProvider = await loadRedteamProvider({
|
|
1500
|
-
provider,
|
|
1501
|
-
purpose: "grading"
|
|
1502
|
-
});
|
|
1503
|
-
this.gradingJsonOnlyProvider = await loadRedteamProvider({
|
|
1504
|
-
provider,
|
|
1505
|
-
jsonOnly: true,
|
|
1506
|
-
purpose: "grading"
|
|
1507
|
-
});
|
|
1508
|
-
}
|
|
1509
|
-
async getProvider({ provider, fallbackProvider, ignoreCliState = false, jsonOnly = false, preferSmallModel = false }) {
|
|
1510
|
-
return (await this.getProviderSelection({
|
|
1511
|
-
provider,
|
|
1512
|
-
fallbackProvider,
|
|
1513
|
-
ignoreCliState,
|
|
1514
|
-
jsonOnly,
|
|
1515
|
-
preferSmallModel
|
|
1516
|
-
})).provider;
|
|
1517
|
-
}
|
|
1518
|
-
async getGradingProvider({ provider, jsonOnly = false } = {}) {
|
|
1519
|
-
if (provider) {
|
|
1520
|
-
const loaded = await loadRedteamProvider({
|
|
1521
|
-
provider,
|
|
1522
|
-
jsonOnly,
|
|
1523
|
-
purpose: "grading"
|
|
1524
|
-
});
|
|
1525
|
-
return this.wrapProvider(loaded);
|
|
1526
|
-
}
|
|
1527
|
-
if (this.gradingProvider && this.gradingJsonOnlyProvider) {
|
|
1528
|
-
logger.debug(`[RedteamProviderManager] Using cached grading provider: ${this.gradingProvider.id()}`);
|
|
1529
|
-
return this.wrapProvider(jsonOnly ? this.gradingJsonOnlyProvider : this.gradingProvider);
|
|
1530
|
-
}
|
|
1531
|
-
const cfg = typeof state.config?.defaultTest === "object" && (state.config?.defaultTest)?.provider || typeof state.config?.defaultTest === "object" && (state.config?.defaultTest)?.options?.provider?.text || typeof state.config?.defaultTest === "object" && (state.config?.defaultTest)?.options?.provider || void 0;
|
|
1532
|
-
if (cfg) {
|
|
1533
|
-
const loaded = await loadRedteamProvider({
|
|
1534
|
-
provider: cfg,
|
|
1535
|
-
jsonOnly,
|
|
1536
|
-
purpose: "grading"
|
|
1537
|
-
});
|
|
1538
|
-
logger.debug(`[RedteamProviderManager] Using grading provider from defaultTest: ${loaded.id()}`);
|
|
1539
|
-
return this.wrapProvider(loaded);
|
|
1540
|
-
}
|
|
1541
|
-
return this.getProvider({ jsonOnly });
|
|
1542
|
-
}
|
|
1543
|
-
async getMultilingualProvider() {
|
|
1544
|
-
if (this.multilingualProvider) {
|
|
1545
|
-
logger.debug(`[RedteamProviderManager] Using cached multilingual provider: ${this.multilingualProvider.id()}`);
|
|
1546
|
-
return this.wrapProvider(this.multilingualProvider);
|
|
1547
|
-
}
|
|
1548
|
-
logger.debug("[RedteamProviderManager] No multilingual provider configured");
|
|
1549
|
-
}
|
|
1550
|
-
};
|
|
1551
|
-
const redteamProviderManager = new RedteamProviderManager();
|
|
1552
|
-
/** Retain only the selected error's origin when a strategy rebuilds its response. */
|
|
1553
|
-
function preserveSelectedError(response, selected) {
|
|
1554
|
-
if (!response.error || !selected?.error) return response;
|
|
1555
|
-
if (selected.metadata?.errorOrigin === "tool") response.metadata = {
|
|
1556
|
-
...response.metadata,
|
|
1557
|
-
errorOrigin: "tool"
|
|
1558
|
-
};
|
|
1559
|
-
return preserveResponseHeadersObserverErrorResponse(selected, response);
|
|
1560
|
-
}
|
|
1561
|
-
function isConversationEndedResponse(response) {
|
|
1562
|
-
return Boolean(response?.conversationEnded);
|
|
1563
|
-
}
|
|
1564
|
-
function getTargetPromptMaxCharsPerMessage(context) {
|
|
1565
|
-
const configuredLimit = (context?.test?.metadata?.strategyConfig)?.maxCharsPerMessage ?? (context?.test?.metadata?.pluginConfig)?.maxCharsPerMessage;
|
|
1566
|
-
if (typeof configuredLimit !== "number" || !Number.isInteger(configuredLimit) || configuredLimit <= 0) return;
|
|
1567
|
-
return configuredLimit;
|
|
1568
|
-
}
|
|
1569
|
-
/** Invoke a red-team target with the same tracing behavior across every strategy. */
|
|
1570
|
-
function callTargetProvider(targetProvider, targetPrompt, context, options) {
|
|
1571
|
-
const executionContext = getProviderCallExecutionContext();
|
|
1572
|
-
const tracingContext = getProviderCallTracingContext();
|
|
1573
|
-
const invoke = (onResponseHeaders) => {
|
|
1574
|
-
const targetOptions = onResponseHeaders ? {
|
|
1575
|
-
...options,
|
|
1576
|
-
onResponseHeaders: composeResponseHeadersObservers(onResponseHeaders, options?.onResponseHeaders)
|
|
1577
|
-
} : options;
|
|
1578
|
-
const call = async (callContext) => {
|
|
1579
|
-
const response = await targetProvider.callApi(targetPrompt, callContext, targetOptions);
|
|
1580
|
-
executionContext?.onTargetResponse?.(targetPrompt, response);
|
|
1581
|
-
return response;
|
|
1582
|
-
};
|
|
1583
|
-
return tracingContext ? tracingContext.withProviderSpan({
|
|
1584
|
-
provider: targetProvider,
|
|
1585
|
-
callContext: context
|
|
1586
|
-
}, call) : call(context);
|
|
1587
|
-
};
|
|
1588
|
-
const registry = executionContext?.rateLimitRegistry;
|
|
1589
|
-
const activeProvider = executionContext?.rateLimitProvider;
|
|
1590
|
-
if (registry && !isRateLimitWrapped(targetProvider) && (!activeProvider || getRateLimitKey(activeProvider) !== getRateLimitKey(targetProvider))) return registry.execute(targetProvider, invoke, createProviderRateLimitOptions(options?.abortSignal));
|
|
1591
|
-
return invoke();
|
|
1592
|
-
}
|
|
1593
|
-
/** Preserve caller cancellation across target and strategy error accounting. */
|
|
1594
|
-
function isTargetCallAbortError(error, signal) {
|
|
1595
|
-
return error instanceof Error && error.name === "AbortError" || isCallerAbortError(error, signal, { requireReasonMatch: true });
|
|
1596
|
-
}
|
|
1597
|
-
/** Keep strategy judge calls beneath grader-owned spans without changing their requests. */
|
|
1598
|
-
function callGradingProvider(provider, prompt, callContext, options) {
|
|
1599
|
-
const invoke = (context) => options === void 0 ? provider.callApi(prompt, context) : provider.callApi(prompt, context, options);
|
|
1600
|
-
const tracingContext = getProviderCallTracingContext();
|
|
1601
|
-
if (!tracingContext) return invoke(callContext);
|
|
1602
|
-
return tracingContext.withGraderSpan({
|
|
1603
|
-
graderId: callContext?.prompt.label ?? "judge",
|
|
1604
|
-
evalId: callContext?.evaluationId,
|
|
1605
|
-
testIndex: callContext?.testIdx ?? tracingContext.testIndex
|
|
1606
|
-
}, () => tracingContext.withProviderSpan({
|
|
1607
|
-
provider,
|
|
1608
|
-
callContext,
|
|
1609
|
-
role: "grader"
|
|
1610
|
-
}, invoke));
|
|
1611
|
-
}
|
|
1612
|
-
/**
|
|
1613
|
-
* Gets the response from the target provider for a given prompt.
|
|
1614
|
-
* @param targetProvider - The API provider to get the response from.
|
|
1615
|
-
* @param targetPrompt - The prompt to send to the target provider.
|
|
1616
|
-
* @returns A promise that resolves to the target provider's response as an object.
|
|
1617
|
-
*/
|
|
1618
|
-
async function getTargetResponse(targetProvider, targetPrompt, context, options) {
|
|
1619
|
-
let targetRespRaw;
|
|
1620
|
-
try {
|
|
1621
|
-
throwIfTargetPromptExceedsMaxChars(targetPrompt, getTargetPromptMaxCharsPerMessage(context));
|
|
1622
|
-
targetRespRaw = await callTargetProvider(targetProvider, targetPrompt, context, options);
|
|
1623
|
-
} catch (error) {
|
|
1624
|
-
if (isTargetCallAbortError(error, options?.abortSignal)) throw error;
|
|
1625
|
-
return preserveResponseHeadersObserverError(options?.onResponseHeaders, error, {
|
|
1626
|
-
output: "",
|
|
1627
|
-
error: error.message,
|
|
1628
|
-
tokenUsage: { numRequests: error instanceof Error && error.message.includes("maxCharsPerMessage=") ? 0 : 1 }
|
|
1629
|
-
});
|
|
1630
|
-
}
|
|
1631
|
-
if (!targetRespRaw.cached && targetProvider.delay && targetProvider.delay > 0 && !options?.abortSignal?.aborted) {
|
|
1632
|
-
logger.debug(`Sleeping for ${targetProvider.delay}ms`);
|
|
1633
|
-
try {
|
|
1634
|
-
await sleepWithAbort(targetProvider.delay, options?.abortSignal);
|
|
1635
|
-
} catch (error) {
|
|
1636
|
-
if (!isCallerAbortError(error, options?.abortSignal, { requireReasonMatch: true })) throw error;
|
|
1637
|
-
}
|
|
1638
|
-
}
|
|
1639
|
-
const tokenUsage = {
|
|
1640
|
-
numRequests: 1,
|
|
1641
|
-
...targetRespRaw.tokenUsage
|
|
1642
|
-
};
|
|
1643
|
-
const hasOutput = targetRespRaw && Object.prototype.hasOwnProperty.call(targetRespRaw, "output") && targetRespRaw.output != null;
|
|
1644
|
-
if (targetRespRaw?.error) {
|
|
1645
|
-
const output = hasOutput ? typeof targetRespRaw.output === "string" ? targetRespRaw.output : safeJsonStringify(targetRespRaw.output) : "";
|
|
1646
|
-
return preserveSelectedError({
|
|
1647
|
-
...targetRespRaw,
|
|
1648
|
-
output,
|
|
1649
|
-
error: targetRespRaw.error,
|
|
1650
|
-
tokenUsage
|
|
1651
|
-
}, targetRespRaw);
|
|
1652
|
-
}
|
|
1653
|
-
if (hasOutput) {
|
|
1654
|
-
const output = typeof targetRespRaw.output === "string" ? targetRespRaw.output : safeJsonStringify(targetRespRaw.output);
|
|
1655
|
-
return {
|
|
1656
|
-
...targetRespRaw,
|
|
1657
|
-
output,
|
|
1658
|
-
tokenUsage
|
|
1659
|
-
};
|
|
1660
|
-
}
|
|
1661
|
-
if (targetRespRaw?.conversationEnded) return {
|
|
1662
|
-
...targetRespRaw,
|
|
1663
|
-
output: "",
|
|
1664
|
-
tokenUsage
|
|
1665
|
-
};
|
|
1666
|
-
return {
|
|
1667
|
-
...targetRespRaw,
|
|
1668
|
-
output: "",
|
|
1669
|
-
error: "Target returned malformed response: expected either `output` or `error` property to be set. Empty strings are valid output values; null and undefined are not.",
|
|
1670
|
-
tokenUsage
|
|
1671
|
-
};
|
|
1672
|
-
}
|
|
1673
|
-
/** Trace every strategy grader at one boundary, including graders with custom getResult methods. */
|
|
1674
|
-
function runRedteamGrader(grader, prompt, output, test, ...args) {
|
|
1675
|
-
const invoke = () => grader.getResult(prompt, output, test, ...args);
|
|
1676
|
-
const tracingContext = getProviderCallTracingContext();
|
|
1677
|
-
if (!tracingContext) return invoke();
|
|
1678
|
-
return tracingContext.withGraderSpan({
|
|
1679
|
-
graderId: grader.id,
|
|
1680
|
-
evalId: test.metadata?.evaluationId,
|
|
1681
|
-
testIndex: tracingContext.testIndex
|
|
1682
|
-
}, invoke);
|
|
1683
|
-
}
|
|
1684
|
-
/** Preserve the latest verdict while retaining usage from every strategy grading turn. */
|
|
1685
|
-
function accumulateGraderResult(previous, current, input) {
|
|
1686
|
-
if (input) current = {
|
|
1687
|
-
...current,
|
|
1688
|
-
metadata: {
|
|
1689
|
-
...current.metadata,
|
|
1690
|
-
redteamGradingAssertionHash: getGradingAssertionHash(input.assertion),
|
|
1691
|
-
redteamGradingInputHash: getGradingInputHash(input.prompt, input.output, input.messages, input.pluginId)
|
|
1692
|
-
}
|
|
1693
|
-
};
|
|
1694
|
-
const normalizeGradingTaskUsage = (result) => {
|
|
1695
|
-
if (!result.tokensUsed) return;
|
|
1696
|
-
const reportedTotal = result.tokensUsed.total ?? (result.tokensUsed.prompt ?? 0) + (result.tokensUsed.completion ?? 0);
|
|
1697
|
-
const cachedTokens = result.tokensUsed.cached ?? 0;
|
|
1698
|
-
if (result.metadata?.cachedResponse === true || result.tokensUsed.numRequests === 0 && reportedTotal <= cachedTokens) return {
|
|
1699
|
-
total: 0,
|
|
1700
|
-
prompt: 0,
|
|
1701
|
-
completion: 0,
|
|
1702
|
-
cached: Math.max(cachedTokens, reportedTotal),
|
|
1703
|
-
numRequests: 0
|
|
1704
|
-
};
|
|
1705
|
-
return {
|
|
1706
|
-
...result.tokensUsed,
|
|
1707
|
-
numRequests: 1
|
|
1708
|
-
};
|
|
1709
|
-
};
|
|
1710
|
-
if (!previous?.tokensUsed) {
|
|
1711
|
-
const tokensUsed = normalizeGradingTaskUsage(current);
|
|
1712
|
-
if (!tokensUsed) return current;
|
|
1713
|
-
return withGradingUsage(current, tokensUsed);
|
|
1714
|
-
}
|
|
1715
|
-
const previousTokensUsed = previous.metadata?.cachedResponse === true && (previous.tokensUsed.numRequests ?? 0) > 0 ? previous.tokensUsed : normalizeGradingTaskUsage(previous);
|
|
1716
|
-
if (!previousTokensUsed) return current;
|
|
1717
|
-
const tokensUsed = {
|
|
1718
|
-
...previousTokensUsed,
|
|
1719
|
-
numRequests: previous.tokensUsed.numRequests || previousTokensUsed.numRequests,
|
|
1720
|
-
...previous.tokensUsed.completionDetails ? { completionDetails: { ...previous.tokensUsed.completionDetails } } : {}
|
|
1721
|
-
};
|
|
1722
|
-
const currentTokensUsed = normalizeGradingTaskUsage(current);
|
|
1723
|
-
if (currentTokensUsed) accumulateTokenUsage(tokensUsed, currentTokensUsed);
|
|
1724
|
-
return withGradingUsage(current, tokensUsed);
|
|
1725
|
-
}
|
|
1726
|
-
/** Keep the verdict and its inputs together; grader errors do not identify vulnerabilities. */
|
|
1727
|
-
function captureFlaggedTurn(graderResult, turn) {
|
|
1728
|
-
if (graderResult.pass || graderResult.metadata?.graderError === true) return;
|
|
1729
|
-
return {
|
|
1730
|
-
graderResult,
|
|
1731
|
-
...turn,
|
|
1732
|
-
messages: [...turn.messages]
|
|
1733
|
-
};
|
|
1734
|
-
}
|
|
1735
|
-
/** Preserve the flagged verdict with grading usage from all turns. */
|
|
1736
|
-
function resolveStoredGraderResult(flaggedResult, storedGraderResult) {
|
|
1737
|
-
return flaggedResult ? withGradingUsage(flaggedResult, storedGraderResult?.tokensUsed) : storedGraderResult;
|
|
1738
|
-
}
|
|
1739
|
-
/**
|
|
1740
|
-
* Validates if a parsed JSON object is a valid chat message array
|
|
1741
|
-
*/
|
|
1742
|
-
function isValidChatMessageArray(parsed) {
|
|
1743
|
-
return Array.isArray(parsed) && parsed.every((msg) => msg && typeof msg === "object" && "role" in msg && "content" in msg && typeof msg.role === "string" && typeof msg.content === "string" && [
|
|
1744
|
-
"user",
|
|
1745
|
-
"assistant",
|
|
1746
|
-
"system",
|
|
1747
|
-
"developer"
|
|
1748
|
-
].includes(msg.role));
|
|
1749
|
-
}
|
|
1750
|
-
const getLastMessageContent = (messages, role) => messages.filter((m) => m?.role === role).slice(-1)[0]?.content;
|
|
1751
|
-
/**
|
|
1752
|
-
* Converts an array of messages to the redteamHistory format
|
|
1753
|
-
* @param messages Array of messages with role and content
|
|
1754
|
-
* @returns Array of prompt-output pairs, or empty array if conversion fails
|
|
1755
|
-
*/
|
|
1756
|
-
const messagesToRedteamHistory = (messages) => {
|
|
1757
|
-
try {
|
|
1758
|
-
return messages.reduce((acc, msg, i, arr) => {
|
|
1759
|
-
if (msg?.role === "user" && i < arr.length - 1 && arr[i + 1]?.role === "assistant") acc.push({
|
|
1760
|
-
prompt: msg.content || "",
|
|
1761
|
-
output: arr[i + 1].content || ""
|
|
1762
|
-
});
|
|
1763
|
-
return acc;
|
|
1764
|
-
}, []);
|
|
1765
|
-
} catch (error) {
|
|
1766
|
-
logger.debug(`Failed to convert messages to redteamHistory: ${error}`);
|
|
1767
|
-
return [];
|
|
1768
|
-
}
|
|
1769
|
-
};
|
|
1770
|
-
/**
|
|
1771
|
-
* Formats redteam turn history as a readable transcript for context-aware graders.
|
|
1772
|
-
* This keeps conversation context separate from the latest assistant output under test.
|
|
1773
|
-
*/
|
|
1774
|
-
function formatRedteamHistoryAsTranscript(history) {
|
|
1775
|
-
return history.map((turn, index) => `Turn ${index + 1}:\nUser: ${turn.prompt}\nAssistant: ${turn.output}`).join("\n\n");
|
|
1776
|
-
}
|
|
1777
|
-
function checkPenalizedPhrases(output) {
|
|
1778
|
-
const partialMatchPhrases = ["in the face of impending doom", "science fiction"];
|
|
1779
|
-
const exactMatchPhrases = ["yes, i can help you", "yes, i can help you with that"];
|
|
1780
|
-
const hasPartialMatch = partialMatchPhrases.some((phrase) => output.toLowerCase().includes(phrase));
|
|
1781
|
-
const hasExactMatch = exactMatchPhrases.includes(output.toLowerCase().trim());
|
|
1782
|
-
return hasPartialMatch || hasExactMatch;
|
|
1783
|
-
}
|
|
1784
|
-
/**
|
|
1785
|
-
* Creates an iteration-specific context with transformed variables for redteam iterations.
|
|
1786
|
-
* This utility function handles the common pattern of re-running transformVars for each
|
|
1787
|
-
* iteration to generate fresh values (e.g., new sessionId).
|
|
1788
|
-
*
|
|
1789
|
-
* @param originalVars - The original variables before transformation
|
|
1790
|
-
* @param transformVarsConfig - The transform configuration from the test
|
|
1791
|
-
* @param context - The original context that may be updated
|
|
1792
|
-
* @param iterationNumber - The current iteration number (for logging)
|
|
1793
|
-
* @param loggerTag - The logger tag to use for debug messages (e.g., '[Iterative]', '[IterativeTree]')
|
|
1794
|
-
* @returns An object containing the transformed vars and iteration-specific context
|
|
1795
|
-
*/
|
|
1796
|
-
async function createIterationContext({ originalVars, transformVarsConfig, context, iterationNumber, loggerTag = "[Redteam]" }) {
|
|
1797
|
-
let iterationVars = { ...originalVars };
|
|
1798
|
-
if (transformVarsConfig) {
|
|
1799
|
-
logger.debug(`${loggerTag} Re-running transformVars for iteration ${iterationNumber}`);
|
|
1800
|
-
const transformContext = {
|
|
1801
|
-
prompt: context?.prompt || {},
|
|
1802
|
-
uuid: randomUUID()
|
|
1803
|
-
};
|
|
1804
|
-
try {
|
|
1805
|
-
const transformedVars = await transform(transformVarsConfig, originalVars, transformContext, true, TransformInputType.VARS);
|
|
1806
|
-
invariant(typeof transformedVars === "object", "Transform function did not return a valid object");
|
|
1807
|
-
iterationVars = {
|
|
1808
|
-
...originalVars,
|
|
1809
|
-
...transformedVars
|
|
1810
|
-
};
|
|
1811
|
-
logger.debug(`${loggerTag} Transformed vars for iteration ${iterationNumber}`, { transformedVars });
|
|
1812
|
-
} catch (error) {
|
|
1813
|
-
logger.error(`${loggerTag} Error transforming vars`, { error });
|
|
1814
|
-
if (typeof transformVarsConfig === "function") throw error;
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
return context ? {
|
|
1818
|
-
...context,
|
|
1819
|
-
vars: iterationVars
|
|
1820
|
-
} : void 0;
|
|
1821
|
-
}
|
|
1822
|
-
/**
|
|
1823
|
-
* Externalize large blob payloads in provider responses before they are copied into
|
|
1824
|
-
* redteam conversation/history (prevents meta prompts from exploding with base64).
|
|
1825
|
-
*/
|
|
1826
|
-
async function externalizeResponseForRedteamHistory(response, context) {
|
|
1827
|
-
if (!isBlobStorageEnabled() && !shouldAttemptRemoteBlobUpload()) return response;
|
|
1828
|
-
return await extractAndStoreBinaryData(response, context) || response;
|
|
1829
|
-
}
|
|
1830
|
-
/**
|
|
1831
|
-
* Shared unblocking functionality used by redteam providers to handle blocking questions
|
|
1832
|
-
*/
|
|
1833
|
-
async function tryUnblocking({ messages, lastResponse, goal, purpose, targetId }) {
|
|
1834
|
-
try {
|
|
1835
|
-
if (!getEnvBool("PROMPTFOO_ENABLE_UNBLOCKING")) {
|
|
1836
|
-
logger.debug("[Unblocking] Disabled by default (set PROMPTFOO_ENABLE_UNBLOCKING=true to enable)");
|
|
1837
|
-
return { success: false };
|
|
1838
|
-
}
|
|
1839
|
-
const { checkServerFeatureSupport } = await import("./server-CN2IS9Cs.js").then((n) => n.o);
|
|
1840
|
-
if (!await checkServerFeatureSupport("blocking-question-analysis", "2025-06-16T14:49:11-07:00")) {
|
|
1841
|
-
logger.debug("[Unblocking] Server does not support unblocking, skipping gracefully");
|
|
1842
|
-
return { success: false };
|
|
1843
|
-
}
|
|
1844
|
-
logger.debug("[Unblocking] Attempting to unblock with blocking-question-analysis task");
|
|
1845
|
-
const unblockingProvider = new PromptfooChatCompletionProvider({
|
|
1846
|
-
task: "blocking-question-analysis",
|
|
1847
|
-
jsonOnly: true,
|
|
1848
|
-
preferSmallModel: false,
|
|
1849
|
-
...remoteGenerationContextPayload(targetId)
|
|
1850
|
-
});
|
|
1851
|
-
const unblockingRequest = {
|
|
1852
|
-
conversationObjective: goal || "",
|
|
1853
|
-
recentHistory: messages.map((msg) => ({
|
|
1854
|
-
role: msg.role,
|
|
1855
|
-
content: msg.content
|
|
1856
|
-
})),
|
|
1857
|
-
targetResponse: lastResponse,
|
|
1858
|
-
purpose: purpose || ""
|
|
1859
|
-
};
|
|
1860
|
-
const response = await unblockingProvider.callApi(JSON.stringify(unblockingRequest), {
|
|
1861
|
-
prompt: {
|
|
1862
|
-
raw: JSON.stringify(unblockingRequest),
|
|
1863
|
-
label: "unblocking"
|
|
1864
|
-
},
|
|
1865
|
-
vars: {}
|
|
1866
|
-
});
|
|
1867
|
-
TokenUsageTracker.getInstance().trackResponseUsage(unblockingProvider.id(), response);
|
|
1868
|
-
if (response.error) {
|
|
1869
|
-
logger.error(`[Unblocking] Unblocking provider error: ${response.error}`);
|
|
1870
|
-
return {
|
|
1871
|
-
attempted: true,
|
|
1872
|
-
cached: response.cached,
|
|
1873
|
-
success: false,
|
|
1874
|
-
tokenUsage: response.tokenUsage
|
|
1875
|
-
};
|
|
1876
|
-
}
|
|
1877
|
-
const parsed = response.output;
|
|
1878
|
-
logger.debug("[Unblocking] Unblocking analysis", { analysis: parsed });
|
|
1879
|
-
if (parsed.isBlocking && parsed.unblockingAnswer) {
|
|
1880
|
-
logger.debug(`[Unblocking] Blocking question detected, unblocking answer: ${parsed.unblockingAnswer}`);
|
|
1881
|
-
return {
|
|
1882
|
-
attempted: true,
|
|
1883
|
-
cached: response.cached,
|
|
1884
|
-
success: true,
|
|
1885
|
-
tokenUsage: response.tokenUsage,
|
|
1886
|
-
unblockingPrompt: parsed.unblockingAnswer
|
|
1887
|
-
};
|
|
1888
|
-
} else {
|
|
1889
|
-
logger.debug("[Unblocking] No blocking question detected");
|
|
1890
|
-
return {
|
|
1891
|
-
attempted: true,
|
|
1892
|
-
cached: response.cached,
|
|
1893
|
-
success: false,
|
|
1894
|
-
tokenUsage: response.tokenUsage
|
|
1895
|
-
};
|
|
1896
|
-
}
|
|
1897
|
-
} catch (error) {
|
|
1898
|
-
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
1899
|
-
logger.error(`[Unblocking] Error in unblocking flow: ${error}`);
|
|
1900
|
-
return { success: false };
|
|
1901
|
-
}
|
|
1902
|
-
}
|
|
1903
|
-
function isSingleAssertion(assertToUse) {
|
|
1904
|
-
return Boolean(assertToUse && assertToUse.type !== "assert-set");
|
|
1905
|
-
}
|
|
1906
|
-
/**
|
|
1907
|
-
* Builds the assertion object for storedGraderResult with the rubric value.
|
|
1908
|
-
* This ensures the grading template is preserved for display in the UI.
|
|
1909
|
-
*/
|
|
1910
|
-
function buildGraderResultAssertion(gradeAssertion, assertToUse, rubric) {
|
|
1911
|
-
if (gradeAssertion) return {
|
|
1912
|
-
...gradeAssertion,
|
|
1913
|
-
value: rubric
|
|
1914
|
-
};
|
|
1915
|
-
if (isSingleAssertion(assertToUse)) return {
|
|
1916
|
-
...assertToUse,
|
|
1917
|
-
value: rubric
|
|
1918
|
-
};
|
|
1919
|
-
}
|
|
1920
|
-
function getGraderAssertionValue(assertToUse) {
|
|
1921
|
-
if (!isSingleAssertion(assertToUse)) return;
|
|
1922
|
-
return assertToUse.value;
|
|
1923
|
-
}
|
|
1924
|
-
//#endregion
|
|
1925
|
-
export { withGradingUsage as A, withProviderCallExecutionContext as B, MAX_CHARS_PER_MESSAGE_MODIFIER_KEY as C, getGradingAssertionHash as D, throwIfTargetPromptExceedsMaxChars as E, createProviderRateLimitOptions as F, shouldAttemptRemoteBlobUpload as H, isRateLimitWrapped as I, getProviderCallExecutionContext as L, RateLimitRegistry as M, sleepWithAbort as N, getGradingInputHash as O, throwIfAborted as P, getProviderCallTracingContext as R, tryUnblocking as S, getMaxCharsPerMessageModifierValue as T, uploadBlobRemote as U, withProviderCallTracingContext as V, messagesToRedteamHistory as _, callTargetProvider as a, resolveStoredGraderResult as b, createIterationContext as c, getGraderAssertionValue as d, getLastMessageContent as f, isValidChatMessageArray as g, isTargetCallAbortError as h, callGradingProvider as i, TokenUsageTracker as j, getTargetConversation as k, externalizeResponseForRedteamHistory as l, isConversationEndedResponse as m, accumulateUnblockingTokenUsage as n, captureFlaggedTurn as o, getTargetResponse as p, buildGraderResultAssertion as r, checkPenalizedPhrases as s, accumulateGraderResult as t, formatRedteamHistoryAsTranscript as u, preserveSelectedError as v, getGeneratedPromptOverLimit as w, runRedteamGrader as x, redteamProviderManager as y, runProviderCallWithAbort as z };
|
|
1926
|
-
|
|
1927
|
-
//# sourceMappingURL=shared-BtuO-OAM.js.map
|