@theokit/sdk 4.63.0 → 4.63.2
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/CHANGELOG.md +56 -0
- package/dist/a2a/index.cjs +2 -2
- package/dist/a2a/index.js +1 -1
- package/dist/agent-2COLCVOJ.js +57 -0
- package/dist/{agent-536OOESZ.js.map → agent-2COLCVOJ.js.map} +1 -1
- package/dist/agent-EXAN5EYJ.cjs +66 -0
- package/dist/{agent-5KYMG63I.cjs.map → agent-EXAN5EYJ.cjs.map} +1 -1
- package/dist/agent-session-store-6EL5NPA4.cjs +24 -0
- package/dist/{agent-session-store-WAKLOKWK.cjs.map → agent-session-store-6EL5NPA4.cjs.map} +1 -1
- package/dist/agent-session-store-OPGRB4XM.js +7 -0
- package/dist/{agent-session-store-G2BMUZQV.js.map → agent-session-store-OPGRB4XM.js.map} +1 -1
- package/dist/auth/index.cjs +18 -18
- package/dist/auth/index.js +6 -6
- package/dist/{batch-ND32UKZS.cjs → batch-BXYTW2DP.cjs} +27 -27
- package/dist/{batch-ND32UKZS.cjs.map → batch-BXYTW2DP.cjs.map} +1 -1
- package/dist/{batch-2TGJMNCJ.js → batch-L4ZXS46M.js} +10 -10
- package/dist/{batch-2TGJMNCJ.js.map → batch-L4ZXS46M.js.map} +1 -1
- package/dist/{chunk-VF7EWVDG.js → chunk-2GUYQR5P.js} +3 -3
- package/dist/{chunk-VF7EWVDG.js.map → chunk-2GUYQR5P.js.map} +1 -1
- package/dist/{chunk-J2UROOIG.cjs → chunk-2HVF2WJY.cjs} +8 -8
- package/dist/{chunk-J2UROOIG.cjs.map → chunk-2HVF2WJY.cjs.map} +1 -1
- package/dist/{chunk-44MBDIHG.js → chunk-2QDYBS2A.js} +3 -3
- package/dist/{chunk-44MBDIHG.js.map → chunk-2QDYBS2A.js.map} +1 -1
- package/dist/{chunk-NGESVVJN.cjs → chunk-3FFAEAUJ.cjs} +17 -17
- package/dist/{chunk-NGESVVJN.cjs.map → chunk-3FFAEAUJ.cjs.map} +1 -1
- package/dist/{chunk-GWC3HADL.cjs → chunk-3NSS2OIZ.cjs} +4 -4
- package/dist/{chunk-GWC3HADL.cjs.map → chunk-3NSS2OIZ.cjs.map} +1 -1
- package/dist/{chunk-CV7XMBHP.js → chunk-3O42QOMJ.js} +3 -3
- package/dist/{chunk-CV7XMBHP.js.map → chunk-3O42QOMJ.js.map} +1 -1
- package/dist/{chunk-IWBGCBR6.cjs → chunk-4CLOXP6H.cjs} +4 -4
- package/dist/{chunk-IWBGCBR6.cjs.map → chunk-4CLOXP6H.cjs.map} +1 -1
- package/dist/{chunk-YEXA3PGR.js → chunk-4FFBAUFS.js} +5 -5
- package/dist/{chunk-YEXA3PGR.js.map → chunk-4FFBAUFS.js.map} +1 -1
- package/dist/{chunk-HY57ULY2.cjs → chunk-4PYZ5AX3.cjs} +5 -5
- package/dist/{chunk-HY57ULY2.cjs.map → chunk-4PYZ5AX3.cjs.map} +1 -1
- package/dist/{chunk-OC4NTGMN.js → chunk-4QZSA2HJ.js} +3 -3
- package/dist/{chunk-OC4NTGMN.js.map → chunk-4QZSA2HJ.js.map} +1 -1
- package/dist/{chunk-K3FW2XZD.cjs → chunk-4ZHTIJNE.cjs} +9 -9
- package/dist/{chunk-K3FW2XZD.cjs.map → chunk-4ZHTIJNE.cjs.map} +1 -1
- package/dist/{chunk-BUIK7GUA.cjs → chunk-5HEG4CQH.cjs} +8 -8
- package/dist/{chunk-BUIK7GUA.cjs.map → chunk-5HEG4CQH.cjs.map} +1 -1
- package/dist/{chunk-NXH4GPAQ.cjs → chunk-5VB22SYX.cjs} +7 -7
- package/dist/{chunk-NXH4GPAQ.cjs.map → chunk-5VB22SYX.cjs.map} +1 -1
- package/dist/{chunk-5USCYPPI.cjs → chunk-6HKGLTJI.cjs} +8 -8
- package/dist/{chunk-5USCYPPI.cjs.map → chunk-6HKGLTJI.cjs.map} +1 -1
- package/dist/{chunk-EHJEZAOO.cjs → chunk-6RKUO7AW.cjs} +32 -32
- package/dist/{chunk-EHJEZAOO.cjs.map → chunk-6RKUO7AW.cjs.map} +1 -1
- package/dist/{chunk-5JLFFPCH.js → chunk-7YGCPMGB.js} +4 -4
- package/dist/{chunk-5JLFFPCH.js.map → chunk-7YGCPMGB.js.map} +1 -1
- package/dist/{chunk-SUKXXLWD.js → chunk-A46SWMIF.js} +6 -6
- package/dist/{chunk-SUKXXLWD.js.map → chunk-A46SWMIF.js.map} +1 -1
- package/dist/{chunk-F7AQV62G.js → chunk-A4JVILQU.js} +5 -5
- package/dist/{chunk-F7AQV62G.js.map → chunk-A4JVILQU.js.map} +1 -1
- package/dist/{chunk-44JAAH4X.js → chunk-B3IMEBOA.js} +3 -3
- package/dist/{chunk-44JAAH4X.js.map → chunk-B3IMEBOA.js.map} +1 -1
- package/dist/{chunk-QDED6YO6.cjs → chunk-B4EOJWOY.cjs} +5 -5
- package/dist/{chunk-QDED6YO6.cjs.map → chunk-B4EOJWOY.cjs.map} +1 -1
- package/dist/{chunk-YJDH3CKG.js → chunk-BP46RJ5X.js} +5 -5
- package/dist/{chunk-YJDH3CKG.js.map → chunk-BP46RJ5X.js.map} +1 -1
- package/dist/{chunk-QRSUA2CV.js → chunk-BU4KFWXF.js} +3 -3
- package/dist/{chunk-QRSUA2CV.js.map → chunk-BU4KFWXF.js.map} +1 -1
- package/dist/{chunk-AQLGBKNT.js → chunk-BZRFXJHA.js} +3 -3
- package/dist/{chunk-AQLGBKNT.js.map → chunk-BZRFXJHA.js.map} +1 -1
- package/dist/{chunk-UQGQFBRL.js → chunk-C3NT3PVE.js} +3 -3
- package/dist/{chunk-UQGQFBRL.js.map → chunk-C3NT3PVE.js.map} +1 -1
- package/dist/{chunk-UC3HT2S4.js → chunk-C72AZW7J.js} +3 -3
- package/dist/{chunk-UC3HT2S4.js.map → chunk-C72AZW7J.js.map} +1 -1
- package/dist/{chunk-WNTAPVU5.cjs → chunk-CQBXOJ6U.cjs} +13 -13
- package/dist/{chunk-WNTAPVU5.cjs.map → chunk-CQBXOJ6U.cjs.map} +1 -1
- package/dist/{chunk-T7XEKOVW.js → chunk-D4CUGAKZ.js} +3 -3
- package/dist/{chunk-T7XEKOVW.js.map → chunk-D4CUGAKZ.js.map} +1 -1
- package/dist/{chunk-R6TA2DRJ.js → chunk-DKD3MH6A.js} +6 -6
- package/dist/{chunk-R6TA2DRJ.js.map → chunk-DKD3MH6A.js.map} +1 -1
- package/dist/{chunk-NLXOGBRJ.cjs → chunk-DKK5QY4C.cjs} +358 -326
- package/dist/chunk-DKK5QY4C.cjs.map +1 -0
- package/dist/{chunk-YXGAW7BB.js → chunk-DN2PACRI.js} +10 -10
- package/dist/{chunk-YXGAW7BB.js.map → chunk-DN2PACRI.js.map} +1 -1
- package/dist/{chunk-XSX2UU6Y.cjs → chunk-DXGZ2NUG.cjs} +10 -10
- package/dist/{chunk-XSX2UU6Y.cjs.map → chunk-DXGZ2NUG.cjs.map} +1 -1
- package/dist/{chunk-NUKRL3I6.cjs → chunk-EG4QM7ZJ.cjs} +18 -2
- package/dist/chunk-EG4QM7ZJ.cjs.map +1 -0
- package/dist/{chunk-C7QPML3L.js → chunk-GEEXBYFL.js} +9 -9
- package/dist/{chunk-C7QPML3L.js.map → chunk-GEEXBYFL.js.map} +1 -1
- package/dist/{chunk-A4VHSE56.cjs → chunk-GKEFRLU7.cjs} +6 -6
- package/dist/{chunk-A4VHSE56.cjs.map → chunk-GKEFRLU7.cjs.map} +1 -1
- package/dist/{chunk-NIRE5CNO.cjs → chunk-HCZD23VS.cjs} +13 -13
- package/dist/{chunk-NIRE5CNO.cjs.map → chunk-HCZD23VS.cjs.map} +1 -1
- package/dist/{chunk-IRCJ7EHV.cjs → chunk-HOXVQ5FR.cjs} +14 -14
- package/dist/{chunk-IRCJ7EHV.cjs.map → chunk-HOXVQ5FR.cjs.map} +1 -1
- package/dist/{chunk-QARJGQSA.js → chunk-HS7AVXTF.js} +3 -3
- package/dist/{chunk-QARJGQSA.js.map → chunk-HS7AVXTF.js.map} +1 -1
- package/dist/{chunk-4I55V454.cjs → chunk-I6HGWHPU.cjs} +4 -4
- package/dist/{chunk-4I55V454.cjs.map → chunk-I6HGWHPU.cjs.map} +1 -1
- package/dist/{chunk-T73NA43R.js → chunk-IPYYKCRC.js} +3 -3
- package/dist/{chunk-T73NA43R.js.map → chunk-IPYYKCRC.js.map} +1 -1
- package/dist/{chunk-UUP3MUZ6.cjs → chunk-ITYQ6VBP.cjs} +18 -18
- package/dist/{chunk-UUP3MUZ6.cjs.map → chunk-ITYQ6VBP.cjs.map} +1 -1
- package/dist/chunk-JPBKYL3B.cjs +18 -0
- package/dist/{chunk-6HTXPPHK.cjs.map → chunk-JPBKYL3B.cjs.map} +1 -1
- package/dist/{chunk-MZ2FGBLZ.js → chunk-K5OJUYSZ.js} +4 -4
- package/dist/{chunk-MZ2FGBLZ.js.map → chunk-K5OJUYSZ.js.map} +1 -1
- package/dist/{chunk-EI2Q7SJ5.cjs → chunk-KQ7TS7WW.cjs} +10 -10
- package/dist/{chunk-EI2Q7SJ5.cjs.map → chunk-KQ7TS7WW.cjs.map} +1 -1
- package/dist/{chunk-RUDY2GTT.js → chunk-KQRW2GPZ.js} +5 -5
- package/dist/{chunk-RUDY2GTT.js.map → chunk-KQRW2GPZ.js.map} +1 -1
- package/dist/{chunk-P5LCASTC.cjs → chunk-KYAJINUI.cjs} +125 -125
- package/dist/{chunk-P5LCASTC.cjs.map → chunk-KYAJINUI.cjs.map} +1 -1
- package/dist/{chunk-AMFXSENK.js → chunk-LWGSI6M3.js} +4 -4
- package/dist/{chunk-AMFXSENK.js.map → chunk-LWGSI6M3.js.map} +1 -1
- package/dist/{chunk-ZHPWGIUX.js → chunk-LXI4XZEC.js} +5 -5
- package/dist/{chunk-ZHPWGIUX.js.map → chunk-LXI4XZEC.js.map} +1 -1
- package/dist/{chunk-AG5JPQIY.js → chunk-LXQ6HKPS.js} +3 -3
- package/dist/{chunk-AG5JPQIY.js.map → chunk-LXQ6HKPS.js.map} +1 -1
- package/dist/{chunk-ROYPRJH4.cjs → chunk-LYRDF5TQ.cjs} +9 -9
- package/dist/{chunk-ROYPRJH4.cjs.map → chunk-LYRDF5TQ.cjs.map} +1 -1
- package/dist/{chunk-G24KZRSA.js → chunk-N2U4AZGB.js} +3 -3
- package/dist/{chunk-G24KZRSA.js.map → chunk-N2U4AZGB.js.map} +1 -1
- package/dist/{chunk-4ERPXIVB.js → chunk-O73J46PV.js} +5 -5
- package/dist/{chunk-4ERPXIVB.js.map → chunk-O73J46PV.js.map} +1 -1
- package/dist/{chunk-F3YZMOAU.cjs → chunk-O7DK5PBJ.cjs} +4 -4
- package/dist/{chunk-F3YZMOAU.cjs.map → chunk-O7DK5PBJ.cjs.map} +1 -1
- package/dist/{chunk-Z4BCLVTI.cjs → chunk-O7LZFG6O.cjs} +5 -5
- package/dist/{chunk-Z4BCLVTI.cjs.map → chunk-O7LZFG6O.cjs.map} +1 -1
- package/dist/{chunk-3YJNUKYN.cjs → chunk-OHLDPWTA.cjs} +15 -15
- package/dist/{chunk-3YJNUKYN.cjs.map → chunk-OHLDPWTA.cjs.map} +1 -1
- package/dist/{chunk-FUL2I7G5.js → chunk-OSEG74VJ.js} +8 -8
- package/dist/{chunk-FUL2I7G5.js.map → chunk-OSEG74VJ.js.map} +1 -1
- package/dist/{chunk-UCBJBJ27.js → chunk-PUAEFLYK.js} +4 -4
- package/dist/{chunk-UCBJBJ27.js.map → chunk-PUAEFLYK.js.map} +1 -1
- package/dist/{chunk-2C72DXQF.cjs → chunk-RFMBZPOW.cjs} +9 -9
- package/dist/{chunk-2C72DXQF.cjs.map → chunk-RFMBZPOW.cjs.map} +1 -1
- package/dist/{chunk-NLTVXLGT.js → chunk-RFXWMRFC.js} +3 -3
- package/dist/{chunk-NLTVXLGT.js.map → chunk-RFXWMRFC.js.map} +1 -1
- package/dist/{chunk-MG3SOM3M.js → chunk-RMIWHYC7.js} +6 -6
- package/dist/{chunk-MG3SOM3M.js.map → chunk-RMIWHYC7.js.map} +1 -1
- package/dist/{chunk-2DG7KW4L.cjs → chunk-RMWTPV3M.cjs} +8 -8
- package/dist/{chunk-2DG7KW4L.cjs.map → chunk-RMWTPV3M.cjs.map} +1 -1
- package/dist/{chunk-P6A3M6VD.cjs → chunk-SZVR77EJ.cjs} +10 -10
- package/dist/{chunk-P6A3M6VD.cjs.map → chunk-SZVR77EJ.cjs.map} +1 -1
- package/dist/{chunk-3E77SX4H.js → chunk-TAZVKYWJ.js} +3 -3
- package/dist/{chunk-3E77SX4H.js.map → chunk-TAZVKYWJ.js.map} +1 -1
- package/dist/{chunk-WKRSH2VR.js → chunk-U6IFHFWK.js} +3 -3
- package/dist/{chunk-WKRSH2VR.js.map → chunk-U6IFHFWK.js.map} +1 -1
- package/dist/{chunk-I6TGFUCO.cjs → chunk-UALX2J2Q.cjs} +4 -4
- package/dist/{chunk-I6TGFUCO.cjs.map → chunk-UALX2J2Q.cjs.map} +1 -1
- package/dist/{chunk-XN7NOENA.js → chunk-UBDMVMBZ.js} +5 -5
- package/dist/{chunk-XN7NOENA.js.map → chunk-UBDMVMBZ.js.map} +1 -1
- package/dist/{chunk-YTR3RBUZ.js → chunk-UEXIJTLC.js} +4 -4
- package/dist/{chunk-YTR3RBUZ.js.map → chunk-UEXIJTLC.js.map} +1 -1
- package/dist/{chunk-DQKERTND.cjs → chunk-UGT7GK7I.cjs} +11 -11
- package/dist/{chunk-DQKERTND.cjs.map → chunk-UGT7GK7I.cjs.map} +1 -1
- package/dist/{chunk-FKMUFNQE.js → chunk-UMP6OJIM.js} +4 -4
- package/dist/{chunk-FKMUFNQE.js.map → chunk-UMP6OJIM.js.map} +1 -1
- package/dist/{chunk-AEOZTXVW.js → chunk-UNYXQ4M5.js} +3 -3
- package/dist/{chunk-AEOZTXVW.js.map → chunk-UNYXQ4M5.js.map} +1 -1
- package/dist/{chunk-2BDH744Z.js → chunk-UTSRIDKZ.js} +3 -3
- package/dist/{chunk-2BDH744Z.js.map → chunk-UTSRIDKZ.js.map} +1 -1
- package/dist/{chunk-2ADR2GSO.cjs → chunk-UU36SHFY.cjs} +5 -5
- package/dist/{chunk-2ADR2GSO.cjs.map → chunk-UU36SHFY.cjs.map} +1 -1
- package/dist/{chunk-R3UPQFKK.cjs → chunk-V2BOS4WF.cjs} +9 -9
- package/dist/{chunk-R3UPQFKK.cjs.map → chunk-V2BOS4WF.cjs.map} +1 -1
- package/dist/{chunk-CASUEY42.cjs → chunk-VX4SQ2LY.cjs} +24 -24
- package/dist/{chunk-CASUEY42.cjs.map → chunk-VX4SQ2LY.cjs.map} +1 -1
- package/dist/{chunk-CHKH5452.js → chunk-WHFUZMIC.js} +80 -48
- package/dist/chunk-WHFUZMIC.js.map +1 -0
- package/dist/{chunk-Q4CMI2LP.js → chunk-WLQNMXQE.js} +5 -5
- package/dist/{chunk-Q4CMI2LP.js.map → chunk-WLQNMXQE.js.map} +1 -1
- package/dist/{chunk-XWL6O3SW.cjs → chunk-WNO3C3N2.cjs} +4 -4
- package/dist/{chunk-XWL6O3SW.cjs.map → chunk-WNO3C3N2.cjs.map} +1 -1
- package/dist/{chunk-T7O6K6PX.js → chunk-XEQ3TM66.js} +18 -3
- package/dist/chunk-XEQ3TM66.js.map +1 -0
- package/dist/{chunk-BVZW2B5V.cjs → chunk-XJCXEKMD.cjs} +4 -4
- package/dist/{chunk-BVZW2B5V.cjs.map → chunk-XJCXEKMD.cjs.map} +1 -1
- package/dist/{chunk-JTB5Q42C.cjs → chunk-XL7Q7HB2.cjs} +4 -4
- package/dist/{chunk-JTB5Q42C.cjs.map → chunk-XL7Q7HB2.cjs.map} +1 -1
- package/dist/{chunk-LW7G5DYW.js → chunk-XO4SOZN6.js} +4 -4
- package/dist/{chunk-LW7G5DYW.js.map → chunk-XO4SOZN6.js.map} +1 -1
- package/dist/{chunk-CQGYNZ3K.cjs → chunk-XWTLIGO3.cjs} +4 -4
- package/dist/{chunk-CQGYNZ3K.cjs.map → chunk-XWTLIGO3.cjs.map} +1 -1
- package/dist/{chunk-6SBW4QR2.cjs → chunk-YML4ME27.cjs} +11 -11
- package/dist/{chunk-6SBW4QR2.cjs.map → chunk-YML4ME27.cjs.map} +1 -1
- package/dist/{chunk-P6H23T43.cjs → chunk-ZCIRZE37.cjs} +11 -11
- package/dist/{chunk-P6H23T43.cjs.map → chunk-ZCIRZE37.cjs.map} +1 -1
- package/dist/{chunk-QI7WE46I.cjs → chunk-ZLQSWSJ2.cjs} +11 -11
- package/dist/{chunk-QI7WE46I.cjs.map → chunk-ZLQSWSJ2.cjs.map} +1 -1
- package/dist/{chunk-ILCGLTSA.cjs → chunk-ZSWPZ23K.cjs} +4 -4
- package/dist/{chunk-ILCGLTSA.cjs.map → chunk-ZSWPZ23K.cjs.map} +1 -1
- package/dist/{chunk-IDCKSLYH.js → chunk-ZZMZWBR6.js} +3 -3
- package/dist/{chunk-IDCKSLYH.js.map → chunk-ZZMZWBR6.js.map} +1 -1
- package/dist/compact-session-QV57KR66.cjs +59 -0
- package/dist/{compact-session-GJXJD73F.cjs.map → compact-session-QV57KR66.cjs.map} +1 -1
- package/dist/compact-session-RIGOWC4Y.js +22 -0
- package/dist/{compact-session-TSMQOIHO.js.map → compact-session-RIGOWC4Y.js.map} +1 -1
- package/dist/compaction.cjs +17 -17
- package/dist/compaction.js +4 -4
- package/dist/concurrency.cjs +7 -7
- package/dist/concurrency.js +5 -5
- package/dist/context-AGQ3DIZU.cjs +24 -0
- package/dist/{context-LCKNH2XI.cjs.map → context-AGQ3DIZU.cjs.map} +1 -1
- package/dist/context-GQRFBCLP.js +7 -0
- package/dist/{context-MZSKGKYR.js.map → context-GQRFBCLP.js.map} +1 -1
- package/dist/cron.cjs +36 -36
- package/dist/cron.js +35 -35
- package/dist/errors.cjs +22 -22
- package/dist/errors.js +3 -3
- package/dist/eval.cjs +41 -41
- package/dist/eval.js +35 -35
- package/dist/{executor-ZERJ3DGN.cjs → executor-6CYCA7MI.cjs} +25 -25
- package/dist/{executor-ZERJ3DGN.cjs.map → executor-6CYCA7MI.cjs.map} +1 -1
- package/dist/{executor-BMEHFOXZ.js → executor-QSEC3MRH.js} +8 -8
- package/dist/{executor-BMEHFOXZ.js.map → executor-QSEC3MRH.js.map} +1 -1
- package/dist/filesystem/index.cjs +8 -8
- package/dist/filesystem/index.js +4 -4
- package/dist/fs-session-store-4PIHT5UX.cjs +20 -0
- package/dist/{fs-session-store-XZ7ZTB3A.cjs.map → fs-session-store-4PIHT5UX.cjs.map} +1 -1
- package/dist/fs-session-store-NM6YSTE2.js +11 -0
- package/dist/{fs-session-store-4BHGIWRE.js.map → fs-session-store-NM6YSTE2.js.map} +1 -1
- package/dist/generate-object-GUNAUVBX.js +8 -0
- package/dist/{generate-object-N5MDZUJI.js.map → generate-object-GUNAUVBX.js.map} +1 -1
- package/dist/generate-object-R7HTMW7F.cjs +21 -0
- package/dist/{generate-object-PGSP5U7N.cjs.map → generate-object-R7HTMW7F.cjs.map} +1 -1
- package/dist/index-manager-RBDHP3PM.js +17 -0
- package/dist/{index-manager-ACEQG3IJ.js.map → index-manager-RBDHP3PM.js.map} +1 -1
- package/dist/index-manager-UZBF22BJ.cjs +26 -0
- package/dist/{index-manager-6TEEIWM7.cjs.map → index-manager-UZBF22BJ.cjs.map} +1 -1
- package/dist/index.cjs +139 -139
- package/dist/index.js +50 -50
- package/dist/{inject-session-ZCQUB3IT.js → inject-session-DAR7OUCW.js} +8 -8
- package/dist/{inject-session-ZCQUB3IT.js.map → inject-session-DAR7OUCW.js.map} +1 -1
- package/dist/{inject-session-PPSO2IDD.cjs → inject-session-WQKMC3GR.cjs} +10 -10
- package/dist/{inject-session-PPSO2IDD.cjs.map → inject-session-WQKMC3GR.cjs.map} +1 -1
- package/dist/internal/memory/adapters/index.cjs +9 -9
- package/dist/internal/memory/adapters/index.js +8 -8
- package/dist/internal/memory/storage/index.cjs +39 -39
- package/dist/internal/memory/storage/index.js +10 -10
- package/dist/internal/persistence/index.cjs +21 -21
- package/dist/internal/persistence/index.js +7 -7
- package/dist/internal/security/index.cjs +14 -14
- package/dist/internal/security/index.js +4 -4
- package/dist/judge-call-LAHMBJ57.cjs +23 -0
- package/dist/{judge-call-EGYRC2RE.cjs.map → judge-call-LAHMBJ57.cjs.map} +1 -1
- package/dist/judge-call-LVXABPS3.js +6 -0
- package/dist/{judge-call-DWHAJATE.js.map → judge-call-LVXABPS3.js.map} +1 -1
- package/dist/mcp-auth.cjs +15 -15
- package/dist/mcp-auth.js +5 -5
- package/dist/models.cjs +22 -22
- package/dist/models.js +7 -7
- package/dist/path-safety.cjs +11 -11
- package/dist/path-safety.js +4 -4
- package/dist/persistence.cjs +28 -28
- package/dist/persistence.js +9 -9
- package/dist/project.cjs +6 -6
- package/dist/project.js +4 -4
- package/dist/providers.cjs +9 -9
- package/dist/providers.js +7 -7
- package/dist/registry-75W33OGL.js +10 -0
- package/dist/{registry-VFP3WWQP.js.map → registry-75W33OGL.js.map} +1 -1
- package/dist/registry-V7BDQ6QB.cjs +47 -0
- package/dist/{registry-VFKX7WOP.cjs.map → registry-V7BDQ6QB.cjs.map} +1 -1
- package/dist/retry.cjs +5 -5
- package/dist/retry.js +4 -4
- package/dist/sandbox/index.cjs +7 -7
- package/dist/sandbox/index.js +3 -3
- package/dist/server/errors-envelope.cjs +15 -15
- package/dist/server/errors-envelope.js +4 -4
- package/dist/session-transcript-6WNITKRE.cjs +63 -0
- package/dist/{session-transcript-HF5GEU5M.cjs.map → session-transcript-6WNITKRE.cjs.map} +1 -1
- package/dist/session-transcript-XAEKW6P7.js +6 -0
- package/dist/{session-transcript-P462ZRHX.js.map → session-transcript-XAEKW6P7.js.map} +1 -1
- package/dist/skills.cjs +8 -8
- package/dist/skills.js +6 -6
- package/dist/stream-object-UF4QRQRU.js +8 -0
- package/dist/{stream-object-L57K4OFS.js.map → stream-object-UF4QRQRU.js.map} +1 -1
- package/dist/stream-object-ZJTQNKY3.cjs +21 -0
- package/dist/{stream-object-BUCF5PHO.cjs.map → stream-object-ZJTQNKY3.cjs.map} +1 -1
- package/dist/subagents-loader-CRT5LLL3.js +8 -0
- package/dist/{subagents-loader-6ATCDEKN.js.map → subagents-loader-CRT5LLL3.js.map} +1 -1
- package/dist/subagents-loader-YEUFFPAL.cjs +17 -0
- package/dist/{subagents-loader-X5QKODCL.cjs.map → subagents-loader-YEUFFPAL.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +7 -7
- package/dist/subagents-loader.js +5 -5
- package/dist/subscription/index.cjs +4 -4
- package/dist/subscription/index.js +3 -3
- package/dist/task-store.cjs +8 -8
- package/dist/task-store.js +5 -5
- package/dist/workflow.cjs +28 -28
- package/dist/workflow.js +7 -7
- package/package.json +1 -1
- package/dist/agent-536OOESZ.js +0 -57
- package/dist/agent-5KYMG63I.cjs +0 -66
- package/dist/agent-session-store-G2BMUZQV.js +0 -7
- package/dist/agent-session-store-WAKLOKWK.cjs +0 -24
- package/dist/chunk-6HTXPPHK.cjs +0 -18
- package/dist/chunk-CHKH5452.js.map +0 -1
- package/dist/chunk-NLXOGBRJ.cjs.map +0 -1
- package/dist/chunk-NUKRL3I6.cjs.map +0 -1
- package/dist/chunk-T7O6K6PX.js.map +0 -1
- package/dist/compact-session-GJXJD73F.cjs +0 -59
- package/dist/compact-session-TSMQOIHO.js +0 -22
- package/dist/context-LCKNH2XI.cjs +0 -24
- package/dist/context-MZSKGKYR.js +0 -7
- package/dist/fs-session-store-4BHGIWRE.js +0 -11
- package/dist/fs-session-store-XZ7ZTB3A.cjs +0 -20
- package/dist/generate-object-N5MDZUJI.js +0 -8
- package/dist/generate-object-PGSP5U7N.cjs +0 -21
- package/dist/index-manager-6TEEIWM7.cjs +0 -26
- package/dist/index-manager-ACEQG3IJ.js +0 -17
- package/dist/judge-call-DWHAJATE.js +0 -6
- package/dist/judge-call-EGYRC2RE.cjs +0 -23
- package/dist/registry-VFKX7WOP.cjs +0 -47
- package/dist/registry-VFP3WWQP.js +0 -10
- package/dist/session-transcript-HF5GEU5M.cjs +0 -63
- package/dist/session-transcript-P462ZRHX.js +0 -6
- package/dist/stream-object-BUCF5PHO.cjs +0 -21
- package/dist/stream-object-L57K4OFS.js +0 -8
- package/dist/subagents-loader-6ATCDEKN.js +0 -8
- package/dist/subagents-loader-X5QKODCL.cjs +0 -17
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["picked"],"mappings":";;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,cAAA,GAAiB,IAAA;AAchB,SAAS,iBAAiB,IAAA,EAA8B;AAC7D,EAAA,MAAM,IAAA,GAAO,KAAK,MAAA,IAAU,eAAA;AAC5B,EAAA,MAAM,GAAA,GAAM,KAAK,KAAA,IAAS,cAAA;AAC1B,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,IAAA,CAAK,MAAA;AAC7B,EAAA,IAAI,IAAA,CAAK,YAAA,KAAiB,MAAA,IAAa,IAAA,CAAK,gBAAgB,CAAA,EAAG;AAC7D,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,EAAM,IAAA,CAAK,IAAI,GAAA,EAAK,IAAA,CAAK,YAAY,CAAC,CAAA;AAAA,EACxD;AACA,EAAA,MAAM,UAAU,IAAA,CAAK,GAAA,CAAI,KAAK,IAAA,GAAO,CAAA,IAAK,KAAK,OAAO,CAAA;AACtD,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,EAAI,GAAI,OAAO,CAAA;AACnC;AASO,SAAS,cAAA,CAA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CAAA;AACtB,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACvUA,IAAM,mBAAA,GAAsB,IAAI,iBAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-3E77SX4H.js","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/retry.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["picked"],"mappings":";;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC7D7C,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,cAAA,GAAiB,IAAA;AAchB,SAAS,iBAAiB,IAAA,EAA8B;AAC7D,EAAA,MAAM,IAAA,GAAO,KAAK,MAAA,IAAU,eAAA;AAC5B,EAAA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AAA,GAAa,IAAA;AACnB,QAAA,KAAA,CAAM,YAAA,GAAe,MAAA;AACrB,QAAA,KAAA,CAAM,aAAA,GAAgB,MAAA;AACtB,QAAA,KAAA,CAAM,gBAAA,GAAmB,MAAA;AACzB,QAAA,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;AAMA,SAAS,cAAc,OAAA,EAAiD;AACtE,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,MAAM,MAA0B,EAAC;AACjC,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AAC7B,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,WAAW,CAAA;AACtB,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACvUA,IAAM,mBAAA,GAAsB,IAAI,iBAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-TAZVKYWJ.js","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * T3.4 — exponential backoff with full jitter for credential-pool retry.\n *\n * Why we need this: pre-T3.4 `pool-aware-client.ts:79-83` retried the\n * SAME credential immediately on the first 429 without any wait. When\n * every credential in the pool returned 429 (thundering herd against a\n * shared quota), the client burned through all 5 retry attempts in <1ms,\n * tripped `CredentialPoolExhaustedError`, and surfaced to the agent loop\n * as a hard failure. The user-visible symptom was \"all my keys are\n * exhausted!\" when in reality a 1-2s wait would have cleared the rate\n * limit.\n *\n * AWS Architecture Blog \"Exponential Backoff And Jitter\" (Marc Brooker,\n * 2015) demonstrates full jitter as the canonical pattern: `sleep =\n * random_between(0, base * 2^attempt)`. We extend it with a hard cap\n * (so a 32s sleep never blocks an interactive agent) and honor the\n * provider's `Retry-After` hint when present — the hint always wins over\n * the computed value when it falls within `[base, cap]`.\n *\n * @internal\n */\n\nexport interface BackoffOptions {\n /** 0-indexed retry attempt number. */\n attempt: number;\n /** Base delay in ms (multiplier for 2^attempt). Default 500. */\n baseMs?: number;\n /** Hard cap in ms — backoff never sleeps longer than this. Default 32_000. */\n capMs?: number;\n /** Provider's Retry-After hint in ms (from header). Takes precedence when in-range. */\n retryAfterMs?: number;\n /** Random source — pass a deterministic mock from tests. Default `Math.random`. */\n rng?: () => number;\n}\n\nconst DEFAULT_BASE_MS = 500;\nconst DEFAULT_CAP_MS = 32_000;\n\n/**\n * Compute the next sleep duration (ms) before retrying a failed request.\n *\n * Algorithm:\n * 1. If `retryAfterMs` is set, prefer it — clamped to `[baseMs, capMs]`.\n * The provider's hint is the most accurate available signal.\n * 2. Otherwise: `sleep = random(0, min(cap, base * 2^attempt))` — full\n * jitter per Brooker 2015 ensures coordinated clients (each with\n * different RNG seeds) spread the retry storm.\n *\n * @internal\n */\nexport function computeBackoffMs(opts: BackoffOptions): number {\n const base = opts.baseMs ?? DEFAULT_BASE_MS;\n const cap = opts.capMs ?? DEFAULT_CAP_MS;\n const rng = opts.rng ?? Math.random;\n if (opts.retryAfterMs !== undefined && opts.retryAfterMs >= 0) {\n return Math.max(base, Math.min(cap, opts.retryAfterMs));\n }\n const ceiling = Math.min(cap, base * 2 ** opts.attempt);\n return Math.floor(rng() * ceiling);\n}\n\n/**\n * `setTimeout`-based sleep that resolves early when the abort signal fires.\n * Resolves cleanly (does not throw on abort) so callers decide how to\n * react to the abort downstream.\n *\n * @internal\n */\nexport function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {\n if (ms <= 0 || signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const sleeper = opts.sleeper ?? sleepWithAbort;\n const deadline = Date.now() + opts.maxWaitMs;\n while (Date.now() < deadline) {\n if (signal.aborted) return false;\n const jittered = this.computeJitteredSleepMs(deadline);\n await sleeper(jittered, signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - Date.now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - Date.now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { setupStructuredOutput, makeOutputTool, buildTransientAgentOptions, buildToolPrompt, extractUsage, disposeAndDeleteTransient } from './chunk-
|
|
1
|
+
import { setupStructuredOutput, makeOutputTool, buildTransientAgentOptions, buildToolPrompt, extractUsage, disposeAndDeleteTransient } from './chunk-UNYXQ4M5.js';
|
|
2
2
|
|
|
3
3
|
// src/stream-object.ts
|
|
4
4
|
var StreamObjectError = class extends Error {
|
|
@@ -141,5 +141,5 @@ function bestEffortPartialParse(text, schema) {
|
|
|
141
141
|
}
|
|
142
142
|
|
|
143
143
|
export { StreamObjectError, streamObjectImpl };
|
|
144
|
-
//# sourceMappingURL=chunk-
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
144
|
+
//# sourceMappingURL=chunk-U6IFHFWK.js.map
|
|
145
|
+
//# sourceMappingURL=chunk-U6IFHFWK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream-object.ts"],"names":[],"mappings":";;;AA+EO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA;AAAA,EAChB,IAAA;AAAA,EACS,KAAA;AAAA,EAClB,WAAA,CAAY,IAAA,EAAuC,OAAA,EAAiB,KAAA,EAAiB;AACnF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACxC;AACF;AA6BA,gBAAuB,gBAAA,CACrB,SACA,IAAA,EACsE;AACtE,EAAA,MAAM,EAAE,UAAA,EAAY,UAAA,EAAY,YAAA,EAAa,GAAI,qBAAA;AAAA,IAC/C,OAAA,CAAQ,MAAA;AAAA,IACR,OAAA,CAAQ;AAAA,GACV;AACA,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,SAAA,GAAY,YAAA;AAEhB,EAAA,MAAM,UAAA,GAAa,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AAW,CAAC,QAAA;AACZ,MAAA;AAAA,IACF;AACA,IAAA,IAAI,QAAA,EAAU;AACd,IAAA,IAAI,EAAA,KAAO,KAAK,KAAA,IAAS,CAAA;AAAA,SAAA,IAChB,OAAO,GAAA,EAAK;AACnB,MAAA,KAAA,IAAS,CAAA;AACT,MAAA,IAAI,KAAA,KAAU,GAAG,GAAA,GAAM,CAAA;AAAA,IACzB;AAAA,EACF;AACA,EAAA,IAAI,GAAA,GAAM,GAAG,OAAO,MAAA;AACpB,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,KAAA,EAAO,MAAM,CAAC,CAAA;AAC3C,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,MAAM,SAAS,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,MAAM,eAAgB,MAAA,CAAkD,OAAA;AACxE,EAAA,MAAM,cAAc,OAAO,YAAA,KAAiB,aAAa,YAAA,CAAa,IAAA,CAAK,MAAM,CAAA,GAAI,MAAA;AACrF,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAM,CAAA;AAC3C,EAAA,OAAO,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,IAAA,GAAO,MAAA;AACxC","file":"chunk-WKRSH2VR.js","sourcesContent":["import type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.streamObject}. Same shape as\n * `Agent.generateObject` with the addition that the result is an\n * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.\n *\n * @public\n */\nexport interface StreamObjectOptions<T extends ZodType> {\n schema: T;\n prompt: string;\n systemPrompt?: string;\n /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */\n model: string | ModelSelection;\n apiKey?: string;\n local: LocalOptions;\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n}\n\n/**\n * Recursive partial — `T` where every nested field becomes optional.\n *\n * @public\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? Array<DeepPartial<U>>\n : T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T;\n\n/**\n * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.\n *\n * - `partial` events fire zero or more times with monotonically increasing\n * `attempt`, carrying best-effort schema-parsed snapshots of the model's\n * accumulating output.\n * - `complete` fires exactly once at the end, carrying the fully Zod-parsed\n * object alongside usage and finishReason — semantically identical to a\n * successful `Agent.generateObject()` return.\n *\n * @public\n */\nexport type StreamObjectEvent<T> =\n | { type: \"partial\"; partial: DeepPartial<T>; attempt: number }\n | {\n type: \"complete\";\n object: T;\n raw: unknown;\n usage: { inputTokens: number; outputTokens: number };\n finishReason: \"tool_use\" | \"error\";\n };\n\n/**\n * Error thrown by {@link Agent.streamObject} when the model refuses to call\n * the synthetic `output` tool or when all retries fail to produce a\n * schema-valid object. Same code taxonomy as `GenerateObjectError`.\n *\n * @public\n */\nexport class StreamObjectError extends Error {\n override readonly name = \"StreamObjectError\";\n readonly code: \"no_tool_call\" | \"parse_failed\";\n override readonly cause?: unknown;\n constructor(code: \"no_tool_call\" | \"parse_failed\", message: string, cause?: unknown) {\n super(message);\n this.code = code;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\ninterface StreamObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * Implementation of `Agent.streamObject` as an async generator. Mirrors the\n * synthetic-forced-tool pattern from `generate-object.ts` (ADR D33) with the\n * addition of intermediate `partial` events emitted from incremental parsing\n * of accumulating text deltas during the agent loop.\n *\n * REACHED BY DYNAMIC IMPORT — do not delete on a dead-code report (B-140).\n * `agent.ts` loads this module lazily to keep it off the eager path:\n *\n * streamObjectImport ??= import(\"./stream-object.js\");\n * const { streamObjectImpl } = await streamObjectImport;\n *\n * `knip` resolves imports statically and does not follow a destructure off a\n * dynamic-import promise, so it reports this export as unused on every run. It\n * is not: removing it breaks `Agent.streamObject`. That is why this file is\n * named in `knip.json`'s ignore list rather than cleaned up — the entry is a\n * tool limitation, not a suppression of a real finding, and the difference is\n * the whole reason this comment exists.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: streaming loop interleaves text-delta accumulation, partial-parse attempts, retries, and final dispose — splitting harms locality of the iterator contract.\nexport async function* streamObjectImpl<T extends ZodType>(\n options: StreamObjectOptions<T>,\n deps: StreamObjectDeps,\n): AsyncGenerator<StreamObjectEvent<ZodNamespace.infer<T>>, void, void> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-6: first capture wins (parallel tool use in Claude 3.5+).\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n return JSON.stringify({ ok: true });\n });\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: options.model,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n const userMessage = buildToolPrompt(options.prompt);\n\n try {\n let lastParseError: unknown;\n let attemptCounter = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n\n // Buffer text deltas during streaming; try partial-parse on each.\n let textBuffer = \"\";\n for await (const msg of run.stream()) {\n if (msg.type === \"assistant\") {\n const newText = msg.message.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n if (newText.length > 0) {\n textBuffer += newText;\n const partial = bestEffortPartialParse(textBuffer, options.schema);\n if (partial !== undefined) {\n attemptCounter += 1;\n yield {\n type: \"partial\",\n partial: partial as DeepPartial<ZodNamespace.infer<T>>,\n attempt: attemptCounter,\n };\n }\n }\n }\n }\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new StreamObjectError(\n \"no_tool_call\",\n `Agent run failed before the model could reply: ${result.error.message ?? \"unknown error\"} [${result.error.code ?? \"?\"}]`,\n result.error,\n );\n }\n if (attempt === maxRetries) {\n throw new StreamObjectError(\n \"no_tool_call\",\n \"The model returned text instead of calling the `output` tool.\",\n );\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n yield {\n type: \"complete\",\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n return;\n }\n lastParseError = parsed.error;\n }\n\n throw new StreamObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-4: even if consumer calls iter.return() mid-stream, this finally\n // runs — transient agent is disposed AND removed from registry.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n\n/**\n * Try to extract a partial JSON object from a possibly-incomplete text\n * buffer and parse it via the schema in lenient mode. Returns `undefined`\n * if nothing parseable is found yet.\n *\n * Strategy: find the first `{`, find the LAST balanced `}` (greedy), parse\n * the substring as JSON, then `safeParse` against `schema.partial()` if the\n * schema supports it, else against the original schema.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stateful JSON-balancing scanner — string/brace/escape state must be co-located for the parser to remain correct.\nfunction bestEffortPartialParse<T extends ZodType>(text: string, schema: T): unknown | undefined {\n const start = text.indexOf(\"{\");\n if (start < 0) return undefined;\n // Find the longest balanced JSON object from `start`.\n let depth = 0;\n let inString = false;\n let isEscaped = false;\n let end = -1;\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\" && inString) {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (ch === \"{\") depth += 1;\n else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) end = i;\n }\n }\n if (end < 0) return undefined;\n const candidate = text.slice(start, end + 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n return undefined;\n }\n // Try schema.partial() if available (Zod objects support it); else fall\n // back to the original schema (loose match).\n const maybePartial = (schema as unknown as { partial?: () => ZodType }).partial;\n const looseSchema = typeof maybePartial === \"function\" ? maybePartial.call(schema) : schema;\n const result = looseSchema.safeParse(parsed);\n return result.success ? result.data : undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/stream-object.ts"],"names":[],"mappings":";;;AA+EO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAO,mBAAA;AAAA,EAChB,IAAA;AAAA,EACS,KAAA;AAAA,EAClB,WAAA,CAAY,IAAA,EAAuC,OAAA,EAAiB,KAAA,EAAiB;AACnF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,I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\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.streamObject}. Same shape as\n * `Agent.generateObject` with the addition that the result is an\n * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.\n *\n * @public\n */\nexport interface StreamObjectOptions<T extends ZodType> {\n schema: T;\n prompt: string;\n systemPrompt?: string;\n /** SE8 — accepts a bare-string id shorthand or a {@link ModelSelection}. */\n model: string | ModelSelection;\n apiKey?: string;\n local: LocalOptions;\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n}\n\n/**\n * Recursive partial — `T` where every nested field becomes optional.\n *\n * @public\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? Array<DeepPartial<U>>\n : T extends object\n ? { [K in keyof T]?: DeepPartial<T[K]> }\n : T;\n\n/**\n * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.\n *\n * - `partial` events fire zero or more times with monotonically increasing\n * `attempt`, carrying best-effort schema-parsed snapshots of the model's\n * accumulating output.\n * - `complete` fires exactly once at the end, carrying the fully Zod-parsed\n * object alongside usage and finishReason — semantically identical to a\n * successful `Agent.generateObject()` return.\n *\n * @public\n */\nexport type StreamObjectEvent<T> =\n | { type: \"partial\"; partial: DeepPartial<T>; attempt: number }\n | {\n type: \"complete\";\n object: T;\n raw: unknown;\n usage: { inputTokens: number; outputTokens: number };\n finishReason: \"tool_use\" | \"error\";\n };\n\n/**\n * Error thrown by {@link Agent.streamObject} when the model refuses to call\n * the synthetic `output` tool or when all retries fail to produce a\n * schema-valid object. Same code taxonomy as `GenerateObjectError`.\n *\n * @public\n */\nexport class StreamObjectError extends Error {\n override readonly name = \"StreamObjectError\";\n readonly code: \"no_tool_call\" | \"parse_failed\";\n override readonly cause?: unknown;\n constructor(code: \"no_tool_call\" | \"parse_failed\", message: string, cause?: unknown) {\n super(message);\n this.code = code;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\ninterface StreamObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * Implementation of `Agent.streamObject` as an async generator. Mirrors the\n * synthetic-forced-tool pattern from `generate-object.ts` (ADR D33) with the\n * addition of intermediate `partial` events emitted from incremental parsing\n * of accumulating text deltas during the agent loop.\n *\n * REACHED BY DYNAMIC IMPORT — do not delete on a dead-code report (B-140).\n * `agent.ts` loads this module lazily to keep it off the eager path:\n *\n * streamObjectImport ??= import(\"./stream-object.js\");\n * const { streamObjectImpl } = await streamObjectImport;\n *\n * `knip` resolves imports statically and does not follow a destructure off a\n * dynamic-import promise, so it reports this export as unused on every run. It\n * is not: removing it breaks `Agent.streamObject`. That is why this file is\n * named in `knip.json`'s ignore list rather than cleaned up — the entry is a\n * tool limitation, not a suppression of a real finding, and the difference is\n * the whole reason this comment exists.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: streaming loop interleaves text-delta accumulation, partial-parse attempts, retries, and final dispose — splitting harms locality of the iterator contract.\nexport async function* streamObjectImpl<T extends ZodType>(\n options: StreamObjectOptions<T>,\n deps: StreamObjectDeps,\n): AsyncGenerator<StreamObjectEvent<ZodNamespace.infer<T>>, void, void> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-6: first capture wins (parallel tool use in Claude 3.5+).\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n return JSON.stringify({ ok: true });\n });\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: options.model,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n const userMessage = buildToolPrompt(options.prompt);\n\n try {\n let lastParseError: unknown;\n let attemptCounter = 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n\n // Buffer text deltas during streaming; try partial-parse on each.\n let textBuffer = \"\";\n for await (const msg of run.stream()) {\n if (msg.type === \"assistant\") {\n const newText = msg.message.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\");\n if (newText.length > 0) {\n textBuffer += newText;\n const partial = bestEffortPartialParse(textBuffer, options.schema);\n if (partial !== undefined) {\n attemptCounter += 1;\n yield {\n type: \"partial\",\n partial: partial as DeepPartial<ZodNamespace.infer<T>>,\n attempt: attemptCounter,\n };\n }\n }\n }\n }\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new StreamObjectError(\n \"no_tool_call\",\n `Agent run failed before the model could reply: ${result.error.message ?? \"unknown error\"} [${result.error.code ?? \"?\"}]`,\n result.error,\n );\n }\n if (attempt === maxRetries) {\n throw new StreamObjectError(\n \"no_tool_call\",\n \"The model returned text instead of calling the `output` tool.\",\n );\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n yield {\n type: \"complete\",\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n return;\n }\n lastParseError = parsed.error;\n }\n\n throw new StreamObjectError(\n \"parse_failed\",\n \"Schema parse failed after all retries.\",\n lastParseError,\n );\n } finally {\n // EC-4: even if consumer calls iter.return() mid-stream, this finally\n // runs — transient agent is disposed AND removed from registry.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n\n/**\n * Try to extract a partial JSON object from a possibly-incomplete text\n * buffer and parse it via the schema in lenient mode. Returns `undefined`\n * if nothing parseable is found yet.\n *\n * Strategy: find the first `{`, find the LAST balanced `}` (greedy), parse\n * the substring as JSON, then `safeParse` against `schema.partial()` if the\n * schema supports it, else against the original schema.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: stateful JSON-balancing scanner — string/brace/escape state must be co-located for the parser to remain correct.\nfunction bestEffortPartialParse<T extends ZodType>(text: string, schema: T): unknown | undefined {\n const start = text.indexOf(\"{\");\n if (start < 0) return undefined;\n // Find the longest balanced JSON object from `start`.\n let depth = 0;\n let inString = false;\n let isEscaped = false;\n let end = -1;\n for (let i = start; i < text.length; i += 1) {\n const ch = text[i];\n if (isEscaped) {\n isEscaped = false;\n continue;\n }\n if (ch === \"\\\\\" && inString) {\n isEscaped = true;\n continue;\n }\n if (ch === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (ch === \"{\") depth += 1;\n else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) end = i;\n }\n }\n if (end < 0) return undefined;\n const candidate = text.slice(start, end + 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(candidate);\n } catch {\n return undefined;\n }\n // Try schema.partial() if available (Zod objects support it); else fall\n // back to the original schema (loose match).\n const maybePartial = (schema as unknown as { partial?: () => ZodType }).partial;\n const looseSchema = typeof maybePartial === \"function\" ? maybePartial.call(schema) : schema;\n const result = looseSchema.safeParse(parsed);\n return result.success ? result.data : undefined;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkEG4QM7ZJ_cjs = require('./chunk-EG4QM7ZJ.cjs');
|
|
4
4
|
var crypto = require('crypto');
|
|
5
5
|
var promises = require('fs/promises');
|
|
6
6
|
var path = require('path');
|
|
@@ -23,7 +23,7 @@ async function warnOnNetworkFsOnce(dirPath, label) {
|
|
|
23
23
|
const info = await promises.statfs(dirPath);
|
|
24
24
|
const fsName = detectNetworkFsName(info.type);
|
|
25
25
|
if (fsName === null) return;
|
|
26
|
-
|
|
26
|
+
chunkEG4QM7ZJ_cjs.diag(
|
|
27
27
|
`[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} \u2014 rename() atomicity guarantees may be weaker than expected.
|
|
28
28
|
`
|
|
29
29
|
);
|
|
@@ -77,5 +77,5 @@ exports.atomicWriteJson = atomicWriteJson;
|
|
|
77
77
|
exports.atomicWriteTempTarget = atomicWriteTempTarget;
|
|
78
78
|
exports.atomicWriteText = atomicWriteText;
|
|
79
79
|
exports.replaceFileAtomic = replaceFileAtomic;
|
|
80
|
-
//# sourceMappingURL=chunk-
|
|
81
|
-
//# sourceMappingURL=chunk-
|
|
80
|
+
//# sourceMappingURL=chunk-UALX2J2Q.cjs.map
|
|
81
|
+
//# sourceMappingURL=chunk-UALX2J2Q.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/atomic-write.ts"],"names":["statfs","diag","dirname","randomBytes","open","rename","unlink","mkdir"],"mappings":";;;;;;;AAUA,IAAM,gBAAA,uBAAoD,GAAA,CAAI;AAAA,EAC5D,CAAC,OAAQ,KAAK,CAAA;AAAA,EACd,CAAC,OAAQ,KAAK,CAAA;AAAA,EACd,CAAC,YAAY,MAAM,CAAA;AAAA,EACnB,CAAC,YAAY,MAAM;AACrB,CAAC,CAAA;AAUD,SAAS,oBAAoB,SAAA,EAAkC;AAC7D,EAAA,OAAO,gBAAA,CAAiB,GAAA,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AAClD,EAAA,MAAM,iBAAA,CAAkB,QAAA,EAAU,OAAA,EAAS,OAAO,CAAA;AACpD;AASA,eAAsB,eAAA,CAAgB,UAAkB,OAAA,EAAgC;AACtF,EAAA,MAAMK,eAAML,YAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,EAAA,MAAM,iBAAA,CAAkB,UAAU,OAAO,CAAA;AAC3C","file":"chunk-I6TGFUCO.cjs","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, rename, statfs, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { diag } from \"../diagnostics.js\";\n\n// T5.8 — Linux filesystem magic numbers (from `<linux/magic.h>`).\n// Used by `detectNetworkFsName` to identify the parent directory's\n// filesystem type from a `statfs()` return value. The four entries\n// below cover the network/FUSE cases where `rename()` is best-effort\n// rather than strictly atomic; everything else is treated as local.\nconst NETWORK_FS_MAGIC: ReadonlyMap<number, string> = new Map([\n [0x6969, \"nfs\"],\n [0x517b, \"smb\"],\n [0xff534d42, \"cifs\"],\n [0x65735546, \"fuse\"],\n]);\n\n/**\n * T5.8 — Map a `statfs().type` magic number to a network-FS label, or\n * `null` for local filesystems. Pure function — exported via the\n * `__TESTING__` seam so unit tests can drive the parse logic without\n * needing a network mount.\n *\n * @internal\n */\nfunction detectNetworkFsName(typeMagic: number): string | null {\n return NETWORK_FS_MAGIC.get(typeMagic) ?? null;\n}\n\nconst warnedNfsDirs = new Set<string>();\n\n/**\n * T5.8 — Best-effort one-shot stderr warning when `dirPath` lives on a\n * network/FUSE filesystem. Silent no-op on local filesystems, on\n * statfs failure (Windows / Node < 18.15 / EACCES), or after the\n * first warning per (dir + label) pair. Mirrors the `sqlite-wal.ts`\n * warn-once-per-label pattern (D63).\n *\n * @internal\n */\nasync function warnOnNetworkFsOnce(dirPath: string, label: string): Promise<void> {\n const key = `${dirPath}\\0${label}`;\n if (warnedNfsDirs.has(key)) return;\n warnedNfsDirs.add(key);\n try {\n const info = await statfs(dirPath);\n const fsName = detectNetworkFsName(info.type);\n if (fsName === null) return;\n diag(\n `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} — ` +\n \"rename() atomicity guarantees may be weaker than expected.\\n\",\n );\n } catch {\n // statfs unavailable (Windows / Node < 18.15) or unreadable —\n // silent fallback. The warning is purely informational.\n }\n}\n\n/**\n * T5.8 — Test seam exposing the pure detection function so unit tests\n * can assert magic-number coverage without spinning up a network FS.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__detectNetworkFsName(typeMagic: number): string | null {\n return detectNetworkFsName(typeMagic);\n}\n\n/**\n * T5.8 — Test seam: clear the per-directory warn-once registry between\n * tests so warning-emission tests stay deterministic.\n *\n * @internal\n */\nexport function __TESTING__resetNfsWarnings(): void {\n warnedNfsDirs.clear();\n}\n\n/**\n * M107 — temp-file creation control, shared by `replaceFileAtomic`,\n * `atomicWriteJson` e `atomicWriteText`.\n *\n * Both fields are OPTIONAL and the default is byte-identical to the behavior\n * before M107. See `replaceFileAtomic` for why the mode reassertion\n * is conditional.\n *\n */\nexport interface AtomicWriteFileOptions {\n /**\n * Permission bits of the created file. Default: `0o600`, the previous fixed\n * literal — filtered by the `umask`, as it always was. When provided, the mode is\n * reasserted on the descriptor, so the `umask` cannot silently\n * clearing bits the caller asked for.\n */\n mode?: number;\n /**\n * Create the temp file with `wx` (exclusive creation) instead of `w`. Default:\n * `false` — the previous flag. With `true`, a pre-existing temp file becomes\n * `EEXIST` instead of being truncated.\n */\n exclusive?: boolean;\n}\n\n/** The one place the temp-path format is written. `atomicWriteTempTarget` reverses it. */\nfunction atomicWriteTempPath(filePath: string, pid: number, suffix: string): string {\n return `${filePath}.${String(pid)}.${suffix}.tmp`;\n}\n\n/** Reverses {@link atomicWriteTempPath}: `<file>.<pid>.<hex>.tmp` → `<file>`. */\nconst TEMP_PATTERN = /^(.+)\\.\\d+\\.[0-9a-f]{16}\\.tmp$/;\n\n/**\n * U-9 — the file a leftover temp was replacing, or `undefined` if this is not one of ours.\n *\n * A crash between the open and the rename leaves `<file>.<pid>.<hex>.tmp` behind, and nothing here\n * collects it: this module creates temps and has no opinion about sweeping them. A consumer that\n * wants to has to know the format — which lived only in the implementation, so one copied it out of\n * a compiled chunk as a regex. That copy would have gone on reporting \"nothing to collect\" the day\n * the format changed, which is the quietest possible way for a cleanup to stop working.\n *\n * Deliberately strict: the pid must be digits and the suffix exactly 16 hex characters. Matching any\n * `.tmp` would claim editors' swap files and other tools' scratch, on a path whose purpose is\n * deleting them.\n */\nexport function atomicWriteTempTarget(name: string): string | undefined {\n return TEMP_PATTERN.exec(name)?.[1];\n}\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors peer-project's `replaceFileAtomic` from\n * `reference/peer-project/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * ## M107 — `options` is optional, and the default is byte-identical\n *\n * The third parameter is additive: every earlier caller still compiles and\n * writing exactly the same bytes, with the same mode, to the same path.\n *\n * The mode reassertion (`handle.chmod`) is **conditional on `mode !== undefined`**,\n * and that is not cosmetic. `open`'s mode argument is filtered by the `umask`,\n * which only CLEARS bits — measured in this codebase before the change:\n *\n * ```\n * umask 0o002 -> 0o600 umask 0o022 -> 0o600 umask 0o200 -> 0o400\n * ```\n *\n * An unconditional `chmod` would take the third case from `0o400` to `0o600` — a\n * an on-disk change for every caller that asked for nothing, including external\n * consumers. When the caller DOES ask for a mode, however, letting the `umask` decide\n * silently is the defect this parameter exists to close; hence the reassertion.\n *\n * It goes on the DESCRIPTOR, before the `rename`, never after: chmod-ing the final\n * final one would leave a window where it carries the `umask`'s mode — a known anti-pattern.\n * The chosen shape passes the mode as an `open` argument.\n *\n */\nexport async function replaceFileAtomic(\n filePath: string,\n content: string,\n options?: AtomicWriteFileOptions,\n): Promise<void> {\n // T5.8 — warn once per parent directory if it lives on a network /\n // FUSE filesystem where `rename()` atomicity is best-effort. The\n // write proceeds unchanged; the warning is purely informational so\n // operators can spot the case in stderr / log aggregators.\n await warnOnNetworkFsOnce(dirname(filePath), \"atomic-write\");\n // T5.7 — crypto-random tmp suffix (CSPRNG, 64 bits of entropy)\n // replaces the predictable `Math.random().toString(36)` source. An\n // attacker observing the process can no longer predict the next\n // tmp path and pre-stage a hostile file to be renamed into place.\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = atomicWriteTempPath(filePath, process.pid, suffix);\n // T5.7 — mode 0o600 on the tmp file (owner read+write only). The\n // tmp file holds the FULL in-flight content (credential snapshots,\n // OAuth tokens) before the rename. World-readable default would\n // expose secrets during the ms-window between open and rename\n // (TOCTOU). On modern Linux the post-rename target inherits the\n // tmp's permission bits, so the final file is also 0o600.\n const handle = await open(tmp, options?.exclusive === true ? \"wx\" : \"w\", options?.mode ?? 0o600);\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n // Conditional by measurement, not by taste — see this function's docblock.\n if (options?.mode !== undefined) await handle.chmod(options.mode);\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n */\nexport interface AtomicWriteJsonOptions extends AtomicWriteFileOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content, options);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/atomic-write.ts"],"names":["statfs","diag","dirname","randomBytes","open","rename","unlink","mkdir"],"mappings":";;;;;;;AAUA,IAAM,gBAAA,uBAAoD,GAAA,CAAI;AAAA,EAC5D,CAAC,OAAQ,KAAK,CAAA;AAAA,EACd,CAAC,OAAQ,KAAK,CAAA;AAAA,EACd,CAAC,YAAY,MAAM,CAAA;AAAA,EACnB,CAAC,YAAY,MAAM;AACrB,CAAC,CAAA;AAUD,SAAS,oBAAoB,SAAA,EAAkC;AAC7D,EAAA,OAAO,gBAAA,CAAiB,GAAA,CAAI,SAAS,CAAA,IAAK,IAAA;AAC5C;AAEA,IAAM,aAAA,uBAAoB,GAAA,EAAY;AAWtC,eAAe,mBAAA,CAAoB,SAAiB,KAAA,EAA8B;AAChF,EAAA,MAAM,GAAA,GAAM,CAAA,EAAG,OAAO,CAAA,EAAA,EAAK,KAAK,CAAA,CAAA;AAChC,EAAA,IAAI,aA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AAkB,UAAU,OAAO,CAAA;AAC3C","file":"chunk-UALX2J2Q.cjs","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, rename, statfs, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { diag } from \"../diagnostics.js\";\n\n// T5.8 — Linux filesystem magic numbers (from `<linux/magic.h>`).\n// Used by `detectNetworkFsName` to identify the parent directory's\n// filesystem type from a `statfs()` return value. The four entries\n// below cover the network/FUSE cases where `rename()` is best-effort\n// rather than strictly atomic; everything else is treated as local.\nconst NETWORK_FS_MAGIC: ReadonlyMap<number, string> = new Map([\n [0x6969, \"nfs\"],\n [0x517b, \"smb\"],\n [0xff534d42, \"cifs\"],\n [0x65735546, \"fuse\"],\n]);\n\n/**\n * T5.8 — Map a `statfs().type` magic number to a network-FS label, or\n * `null` for local filesystems. Pure function — exported via the\n * `__TESTING__` seam so unit tests can drive the parse logic without\n * needing a network mount.\n *\n * @internal\n */\nfunction detectNetworkFsName(typeMagic: number): string | null {\n return NETWORK_FS_MAGIC.get(typeMagic) ?? null;\n}\n\nconst warnedNfsDirs = new Set<string>();\n\n/**\n * T5.8 — Best-effort one-shot stderr warning when `dirPath` lives on a\n * network/FUSE filesystem. Silent no-op on local filesystems, on\n * statfs failure (Windows / Node < 18.15 / EACCES), or after the\n * first warning per (dir + label) pair. Mirrors the `sqlite-wal.ts`\n * warn-once-per-label pattern (D63).\n *\n * @internal\n */\nasync function warnOnNetworkFsOnce(dirPath: string, label: string): Promise<void> {\n const key = `${dirPath}\\0${label}`;\n if (warnedNfsDirs.has(key)) return;\n warnedNfsDirs.add(key);\n try {\n const info = await statfs(dirPath);\n const fsName = detectNetworkFsName(info.type);\n if (fsName === null) return;\n diag(\n `[theokit-sdk] ${label}: detected network fs (${fsName}) at ${dirPath} — ` +\n \"rename() atomicity guarantees may be weaker than expected.\\n\",\n );\n } catch {\n // statfs unavailable (Windows / Node < 18.15) or unreadable —\n // silent fallback. The warning is purely informational.\n }\n}\n\n/**\n * T5.8 — Test seam exposing the pure detection function so unit tests\n * can assert magic-number coverage without spinning up a network FS.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__detectNetworkFsName(typeMagic: number): string | null {\n return detectNetworkFsName(typeMagic);\n}\n\n/**\n * T5.8 — Test seam: clear the per-directory warn-once registry between\n * tests so warning-emission tests stay deterministic.\n *\n * @internal\n */\nexport function __TESTING__resetNfsWarnings(): void {\n warnedNfsDirs.clear();\n}\n\n/**\n * M107 — temp-file creation control, shared by `replaceFileAtomic`,\n * `atomicWriteJson` e `atomicWriteText`.\n *\n * Both fields are OPTIONAL and the default is byte-identical to the behavior\n * before M107. See `replaceFileAtomic` for why the mode reassertion\n * is conditional.\n *\n */\nexport interface AtomicWriteFileOptions {\n /**\n * Permission bits of the created file. Default: `0o600`, the previous fixed\n * literal — filtered by the `umask`, as it always was. When provided, the mode is\n * reasserted on the descriptor, so the `umask` cannot silently\n * clearing bits the caller asked for.\n */\n mode?: number;\n /**\n * Create the temp file with `wx` (exclusive creation) instead of `w`. Default:\n * `false` — the previous flag. With `true`, a pre-existing temp file becomes\n * `EEXIST` instead of being truncated.\n */\n exclusive?: boolean;\n}\n\n/** The one place the temp-path format is written. `atomicWriteTempTarget` reverses it. */\nfunction atomicWriteTempPath(filePath: string, pid: number, suffix: string): string {\n return `${filePath}.${String(pid)}.${suffix}.tmp`;\n}\n\n/** Reverses {@link atomicWriteTempPath}: `<file>.<pid>.<hex>.tmp` → `<file>`. */\nconst TEMP_PATTERN = /^(.+)\\.\\d+\\.[0-9a-f]{16}\\.tmp$/;\n\n/**\n * U-9 — the file a leftover temp was replacing, or `undefined` if this is not one of ours.\n *\n * A crash between the open and the rename leaves `<file>.<pid>.<hex>.tmp` behind, and nothing here\n * collects it: this module creates temps and has no opinion about sweeping them. A consumer that\n * wants to has to know the format — which lived only in the implementation, so one copied it out of\n * a compiled chunk as a regex. That copy would have gone on reporting \"nothing to collect\" the day\n * the format changed, which is the quietest possible way for a cleanup to stop working.\n *\n * Deliberately strict: the pid must be digits and the suffix exactly 16 hex characters. Matching any\n * `.tmp` would claim editors' swap files and other tools' scratch, on a path whose purpose is\n * deleting them.\n */\nexport function atomicWriteTempTarget(name: string): string | undefined {\n return TEMP_PATTERN.exec(name)?.[1];\n}\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors peer-project's `replaceFileAtomic` from\n * `reference/peer-project/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * ## M107 — `options` is optional, and the default is byte-identical\n *\n * The third parameter is additive: every earlier caller still compiles and\n * writing exactly the same bytes, with the same mode, to the same path.\n *\n * The mode reassertion (`handle.chmod`) is **conditional on `mode !== undefined`**,\n * and that is not cosmetic. `open`'s mode argument is filtered by the `umask`,\n * which only CLEARS bits — measured in this codebase before the change:\n *\n * ```\n * umask 0o002 -> 0o600 umask 0o022 -> 0o600 umask 0o200 -> 0o400\n * ```\n *\n * An unconditional `chmod` would take the third case from `0o400` to `0o600` — a\n * an on-disk change for every caller that asked for nothing, including external\n * consumers. When the caller DOES ask for a mode, however, letting the `umask` decide\n * silently is the defect this parameter exists to close; hence the reassertion.\n *\n * It goes on the DESCRIPTOR, before the `rename`, never after: chmod-ing the final\n * final one would leave a window where it carries the `umask`'s mode — a known anti-pattern.\n * The chosen shape passes the mode as an `open` argument.\n *\n */\nexport async function replaceFileAtomic(\n filePath: string,\n content: string,\n options?: AtomicWriteFileOptions,\n): Promise<void> {\n // T5.8 — warn once per parent directory if it lives on a network /\n // FUSE filesystem where `rename()` atomicity is best-effort. The\n // write proceeds unchanged; the warning is purely informational so\n // operators can spot the case in stderr / log aggregators.\n await warnOnNetworkFsOnce(dirname(filePath), \"atomic-write\");\n // T5.7 — crypto-random tmp suffix (CSPRNG, 64 bits of entropy)\n // replaces the predictable `Math.random().toString(36)` source. An\n // attacker observing the process can no longer predict the next\n // tmp path and pre-stage a hostile file to be renamed into place.\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = atomicWriteTempPath(filePath, process.pid, suffix);\n // T5.7 — mode 0o600 on the tmp file (owner read+write only). The\n // tmp file holds the FULL in-flight content (credential snapshots,\n // OAuth tokens) before the rename. World-readable default would\n // expose secrets during the ms-window between open and rename\n // (TOCTOU). On modern Linux the post-rename target inherits the\n // tmp's permission bits, so the final file is also 0o600.\n const handle = await open(tmp, options?.exclusive === true ? \"wx\" : \"w\", options?.mode ?? 0o600);\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n // Conditional by measurement, not by taste — see this function's docblock.\n if (options?.mode !== undefined) await handle.chmod(options.mode);\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n */\nexport interface AtomicWriteJsonOptions extends AtomicWriteFileOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content, options);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { globalEmbeddingCache } from './chunk-H73MEMQB.js';
|
|
2
|
-
import { mapOpenAICompatibleError } from './chunk-
|
|
3
|
-
import { mapWithConcurrency } from './chunk-
|
|
4
|
-
import { AuthenticationError, ConfigurationError, NetworkError } from './chunk-
|
|
2
|
+
import { mapOpenAICompatibleError } from './chunk-7YGCPMGB.js';
|
|
3
|
+
import { mapWithConcurrency } from './chunk-C72AZW7J.js';
|
|
4
|
+
import { AuthenticationError, ConfigurationError, NetworkError } from './chunk-ZZMZWBR6.js';
|
|
5
5
|
import { createHash } from 'crypto';
|
|
6
6
|
|
|
7
7
|
var MAX_BATCH = 100;
|
|
@@ -193,5 +193,5 @@ function sleep(ms) {
|
|
|
193
193
|
}
|
|
194
194
|
|
|
195
195
|
export { createOpenAiCompatibleRuntime };
|
|
196
|
-
//# sourceMappingURL=chunk-
|
|
197
|
-
//# sourceMappingURL=chunk-
|
|
196
|
+
//# sourceMappingURL=chunk-UBDMVMBZ.js.map
|
|
197
|
+
//# sourceMappingURL=chunk-UBDMVMBZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/memory/adapters/openai-compatible.ts"],"names":[],"mappings":";;;;;;AAsBA,IAAM,SAAA,GAAY,GAAA;AAClB,IAAM,WAAA,GAAc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AO,MAAA,KAAW,GAAA,IAAQ,MAAA,IAAU,GAAA,IAAO,MAAA,GAAS,GAAA;AACtD;AAEA,SAAS,OAAA,CAAQ,OAAe,IAAA,EAAsB;AACpD,EAAA,OAAO,UAAA,CAAW,QAAQ,CAAA,CAAE,MAAA,CAAO,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,IAAI,CAAA,CAAE,CAAA,CAAE,MAAA,CAAO,KAAK,CAAA;AACrE;AAEA,SAAS,gBAAgB,OAAA,EAAyB;AAChD,EAAA,OAAO,EAAA,GAAK,OAAA;AACd;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"chunk-XN7NOENA.js","sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { AuthenticationError, ConfigurationError, NetworkError } from \"../../../errors.js\";\nimport { mapOpenAICompatibleError } from \"../../error-mappers/openai-compatible.js\";\nimport { mapWithConcurrency } from \"../../runtime/concurrency/map-with-concurrency.js\";\nimport type {\n CreateAdapterOptions,\n EmbeddingRuntime,\n EmbeddingRuntimeStats,\n} from \"../embedding-adapter.js\";\nimport { globalEmbeddingCache } from \"../embedding-cache.js\";\n\n/**\n * Shared factory for OpenAI-compatible embedding providers (OpenAI, Mistral,\n * DeepInfra, and anything else exposing `POST /v1/embeddings` with the\n * `{ model, input }` request shape and `{ data: [{ embedding }] }` response).\n *\n * Mirrors the inner mechanics of peer-project's batch embedding runtime.\n *\n * @internal\n */\n\nconst MAX_BATCH = 100;\nconst MAX_RETRIES = 2;\n\n/**\n * What one provider adapter tells {@link createOpenAiCompatibleRuntime} about\n * its wire: where to POST, which environment variables carry the key and the\n * base URL, which model to use by default, and how wide each model's vectors\n * are.\n *\n * `id` is the provider id that ends up on errors and on\n * `EmbeddingRuntime.id`, and is also the identity the SQLite vector index stores\n * — changing it invalidates the vectors already on disk.\n *\n * `apiKeyEnv` is required, `baseUrlEnv` is not: a provider that declares no\n * base-URL variable can only be redirected by passing `baseUrl` explicitly.\n * Leave `dialect` unset for anything that speaks the OpenAI embedding wire.\n */\nexport interface OpenAiCompatibleConfig {\n id: string;\n defaultBaseUrl: string;\n apiKeyEnv: string;\n baseUrlEnv?: string;\n defaultModel: string;\n /**\n * Dimension hint by model id. The chosen model MUST be in this table —\n * unknown models throw `ConfigurationError(code: \"embedding_unknown_model\")`\n * (EC-4 fix). This prevents vec0 virtual-table dimension mismatches that\n * surface as cryptic errors downstream.\n */\n dimensionByModel: Record<string, number>;\n /**\n * Path component appended to `baseUrl` for the embeddings endpoint.\n * Default `\"/v1/embeddings\"` (OpenAI canonical). REPLACES the default —\n * does NOT concatenate. Used by DeepInfra (`\"/v1/openai/embeddings\"`),\n * etc. (EC-2 fix).\n */\n embeddingsPath?: string;\n /**\n * theokit#159 — per-provider deviations from the OpenAI wire.\n *\n * The runtime was rigidly OpenAI-shaped: one auth header, one body, one response shape. Three of\n * the ten catalog providers do not speak it, so every call they made was rejected — Azure\n * authenticates with an `api-key` header and puts the deployment in the path, Cohere's `/v2/embed`\n * takes `texts` and answers `{embeddings:{float}}`. Advertising a provider that cannot work is\n * worse than not advertising it.\n *\n * Every hook is optional and its default is exactly the previous behaviour, so the seven\n * providers that DO speak OpenAI are untouched.\n */\n dialect?: EmbeddingDialect;\n}\n\n/**\n * theokit#159 — the three points where a provider may deviate from the OpenAI embedding wire.\n *\n * Deliberately three narrow hooks rather than a general \"transform the request\" seam: these are the\n * only axes on which the supported providers actually differ, and a wider seam would invite\n * per-provider logic that belongs in the adapter.\n */\nexport interface EmbeddingDialect {\n /** Replaces `authorization: Bearer <key>`. */\n authHeaders?: (apiKey: string) => Record<string, string>;\n /** Replaces the `{ model, input }` request body. */\n body?: (model: string, inputs: ReadonlyArray<string>) => Record<string, unknown>;\n /** Replaces reading vectors from `json.data[].embedding`. Return `undefined` when unparseable. */\n vectors?: (json: unknown) => number[][] | undefined;\n}\n\n/**\n * Build an {@link EmbeddingRuntime} for a provider that speaks the OpenAI\n * embedding wire — or, through `cfg.dialect`, one that deviates from it in a\n * known way. Every adapter in the memory catalog is a thin call to this.\n *\n * Resolution order for each setting is explicit option, then environment\n * variable, then the config default. Two things are checked before any request\n * is sent, so a misconfiguration fails at creation rather than at first search:\n * a missing or empty key rejects with an `AuthenticationError` carrying\n * `embedding_missing_api_key`, and a model absent from `dimensionByModel`\n * rejects with a `ConfigurationError` carrying `embedding_unknown_model`. The\n * second check exists because the vector index is created at a fixed width — an\n * unknown dimension would surface much later as a vec0 mismatch.\n *\n * `{model}` in `embeddingsPath` is replaced with the URL-encoded model, which is\n * how Azure addresses a deployment in the path. `embeddingsPath` replaces the\n * default `/v1/embeddings` rather than being appended to it.\n *\n * The returned `embed` batches at 100 texts per request and runs at most 3\n * requests concurrently, preserving input order. Whitespace-only inputs never\n * reach the network and come back as an all-zero vector. Results are cached by\n * model and text; the cache defaults to a process-wide LRU of 5000 entries, so\n * pass `options.cache` when runtimes must not share entries.\n *\n * Failed requests retry up to twice on 429 and 5xx with a 50ms-per-attempt\n * linear backoff. Anything else, and a retry budget that runs out, throws the\n * typed error the OpenAI-compatible mapper builds from the status and body. A\n * response that parses but carries no vectors throws a `NetworkError` with\n * `embedding_invalid_response`. There is no request timeout here — cancellation\n * is the caller's to impose.\n */\nexport async function createOpenAiCompatibleRuntime(\n cfg: OpenAiCompatibleConfig,\n options: CreateAdapterOptions,\n): Promise<EmbeddingRuntime> {\n const model = options.model ?? cfg.defaultModel;\n const apiKey = options.apiKey ?? process.env[cfg.apiKeyEnv];\n if (apiKey === undefined || apiKey.length === 0) {\n throw new AuthenticationError(`${cfg.apiKeyEnv} missing`, {\n code: \"embedding_missing_api_key\",\n });\n }\n const envBaseUrl = cfg.baseUrlEnv !== undefined ? process.env[cfg.baseUrlEnv] : undefined;\n const baseUrl = options.baseUrl ?? envBaseUrl ?? cfg.defaultBaseUrl;\n const fetchImpl = options.fetch ?? fetch;\n // T4.4 — default to process-wide singleton (was per-adapter instance).\n const cache = options.cache ?? globalEmbeddingCache;\n // EC-4: refuse unknown models to prevent vec0 dimension mismatches downstream.\n const dimension = cfg.dimensionByModel[model];\n if (dimension === undefined) {\n throw new ConfigurationError(\n `${cfg.id} adapter: model \"${model}\" is not in the dimension table. Use one of: ${Object.keys(cfg.dimensionByModel).join(\", \")}. To add it, update dimensionByModel in the adapter source.`,\n { code: \"embedding_unknown_model\" },\n );\n }\n // theokit#128: `{model}` is substituted, because Azure OpenAI addresses the deployment IN THE\n // PATH (`/openai/deployments/{model}/embeddings`) rather than in the body. Without this the URL\n // carried the literal placeholder and every Azure request 404'd. A path with no placeholder —\n // every other provider — is passed through untouched.\n const embeddingsPath = (cfg.embeddingsPath ?? \"/v1/embeddings\").replace(\n \"{model}\",\n encodeURIComponent(model),\n );\n\n const stats: EmbeddingRuntimeStats = {\n cacheHits: 0,\n cacheMisses: 0,\n httpCalls: 0,\n retries: 0,\n };\n\n return {\n id: cfg.id,\n model,\n dimension,\n stats: () => ({ ...stats }),\n embed: (texts) =>\n embedTexts({\n texts,\n cache,\n stats,\n model,\n dimension,\n apiKey,\n baseUrl,\n embeddingsPath,\n fetchImpl,\n providerId: cfg.id,\n dialect: cfg.dialect ?? {},\n }),\n };\n}\n\ninterface EmbedTextsInput {\n texts: ReadonlyArray<string>;\n cache: NonNullable<CreateAdapterOptions[\"cache\"]>;\n stats: EmbeddingRuntimeStats;\n model: string;\n dimension: number;\n apiKey: string;\n baseUrl: string;\n embeddingsPath: string;\n fetchImpl: typeof fetch;\n providerId: string;\n dialect: EmbeddingDialect;\n}\n\nasync function embedTexts(input: EmbedTextsInput): Promise<number[][]> {\n const { texts, cache, stats, model, dimension } = input;\n const results = new Array<number[] | undefined>(texts.length);\n const pending: Array<{ index: number; text: string; key: string }> = [];\n for (let i = 0; i < texts.length; i++) {\n classifyEntry({\n index: i,\n text: texts[i] ?? \"\",\n model,\n dimension,\n cache,\n stats,\n results,\n pending,\n });\n }\n await embedInBoundedBatches(input, pending, results);\n return results.map((v) => v ?? new Array(dimension).fill(0));\n}\n\ninterface ClassifyEntryArgs {\n index: number;\n text: string;\n model: string;\n dimension: number;\n cache: NonNullable<CreateAdapterOptions[\"cache\"]>;\n stats: EmbeddingRuntimeStats;\n results: Array<number[] | undefined>;\n pending: Array<{ index: number; text: string; key: string }>;\n}\n\nfunction classifyEntry(args: ClassifyEntryArgs): void {\n if (args.text.trim().length === 0) {\n args.results[args.index] = new Array(args.dimension).fill(0);\n return;\n }\n const key = hashKey(args.model, args.text);\n const cached = args.cache.get(key);\n if (cached !== undefined) {\n args.stats.cacheHits += 1;\n args.results[args.index] = cached;\n return;\n }\n args.stats.cacheMisses += 1;\n args.pending.push({ index: args.index, text: args.text, key });\n}\n\n// T4.3 — max concurrent embedding API requests per embed() call.\n// 3 is enough to saturate most embedding APIs without triggering\n// rate limits (each batch is already up to MAX_BATCH=100 texts).\nconst MAX_CONCURRENT_BATCHES = 3;\n\n/**\n * T4.3 — parallel embed batches (DR4 finding #3).\n *\n * Pre-T4.3 this was a serial `for` loop — each batch of 100 texts\n * awaited before the next HTTP request started. With 500 texts the\n * serial path took 5 × RTT; parallel takes max(RTT) × ceil(5/3).\n *\n * Uses bounded-concurrency `Promise.all` capped at 3 concurrent\n * HTTP requests to avoid overwhelming the embedding API.\n */\nasync function embedInBoundedBatches(\n input: EmbedTextsInput,\n pending: ReadonlyArray<{ index: number; text: string; key: string }>,\n results: Array<number[] | undefined>,\n): Promise<void> {\n const batches: Array<ReadonlyArray<{ index: number; text: string; key: string }>> = [];\n for (let offset = 0; offset < pending.length; offset += MAX_BATCH) {\n batches.push(pending.slice(offset, offset + MAX_BATCH));\n }\n // M0-2: bounded parallel via the shared ordered pool (was an inline\n // acquire/release clone — see plan m0-foundation-expose-primitives).\n await mapWithConcurrency(batches, MAX_CONCURRENT_BATCHES, (batch) =>\n processBatch(input, batch, results),\n );\n}\n\nasync function processBatch(\n input: EmbedTextsInput,\n batch: ReadonlyArray<{ index: number; text: string; key: string }>,\n results: Array<number[] | undefined>,\n): Promise<void> {\n const vectors = await embedBatch({\n apiKey: input.apiKey,\n baseUrl: input.baseUrl,\n embeddingsPath: input.embeddingsPath,\n model: input.model,\n inputs: batch.map((b) => b.text),\n fetchImpl: input.fetchImpl,\n stats: input.stats,\n providerId: input.providerId,\n dialect: input.dialect,\n });\n for (let j = 0; j < batch.length; j++) {\n const slot = batch[j];\n const vector = vectors[j];\n if (slot === undefined || vector === undefined) continue;\n results[slot.index] = vector;\n input.cache.set(slot.key, vector);\n }\n}\n\ninterface BatchOptions {\n apiKey: string;\n baseUrl: string;\n embeddingsPath: string;\n model: string;\n inputs: ReadonlyArray<string>;\n fetchImpl: typeof fetch;\n stats: EmbeddingRuntimeStats;\n providerId: string;\n dialect: EmbeddingDialect;\n}\n\nasync function embedBatch(opts: BatchOptions): Promise<number[][]> {\n // EC-2: embeddingsPath REPLACES the suffix; never concatenates.\n const url = `${opts.baseUrl.replace(/\\/$/, \"\")}${opts.embeddingsPath}`;\n let attempt = 0;\n while (true) {\n opts.stats.httpCalls += 1;\n const response = await postEmbedRequest(opts, url);\n if (response.ok)\n return await parseEmbedResponse(response, opts.providerId, opts.embeddingsPath, opts.dialect);\n if (isRetryable(response.status) && attempt < MAX_RETRIES) {\n attempt += 1;\n opts.stats.retries += 1;\n await sleep(linearBackoffMs(attempt));\n continue;\n }\n // Read body (best-effort) so the mapper has access to provider error code.\n const text = await response.text().catch(() => \"\");\n let body: unknown = text;\n try {\n body = JSON.parse(text);\n } catch {\n // not JSON — keep as string\n }\n throw mapOpenAICompatibleError({\n providerId: opts.providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: opts.embeddingsPath,\n });\n }\n}\n\nasync function postEmbedRequest(opts: BatchOptions, url: string): Promise<Response> {\n return opts.fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(opts.dialect.authHeaders?.(opts.apiKey) ?? { authorization: `Bearer ${opts.apiKey}` }),\n },\n body: JSON.stringify(\n opts.dialect.body?.(opts.model, opts.inputs) ?? { model: opts.model, input: opts.inputs },\n ),\n });\n}\n\nasync function parseEmbedResponse(\n response: Response,\n providerId: string,\n endpoint: string,\n dialect?: EmbeddingDialect,\n): Promise<number[][]> {\n const json = (await response.json()) as { data?: Array<{ embedding: number[] }> };\n // theokit#159 — a provider whose response is not OpenAI-shaped supplies its own reader.\n const viaDialect = dialect?.vectors?.(json);\n if (viaDialect !== undefined) return viaDialect;\n if (!Array.isArray(json.data)) {\n throw new NetworkError(`${providerId} ${endpoint} returned no data`, {\n code: \"embedding_invalid_response\",\n metadata: {\n provider: providerId,\n endpoint,\n code: \"invalid_request\",\n raw: json,\n },\n });\n }\n return json.data.map((d) => d.embedding);\n}\n\nfunction isRetryable(status: number): boolean {\n return status === 429 || (status >= 500 && status < 600);\n}\n\nfunction hashKey(model: string, text: string): string {\n return createHash(\"sha256\").update(`${model} ${text}`).digest(\"hex\");\n}\n\nfunction linearBackoffMs(attempt: number): number {\n return 50 * attempt;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/memory/adapters/openai-compatible.ts"],"names":[],"mappings":";;;;;;AAsBA,IAAM,SAAA,GAAY,GAAA;AAClB,IAAM,WAAA,GAAc,CAAA;AAkGpB,eAAsB,6BAAA,CACpB,KACA,OAAA,EAC2B;AAC3B,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,KAAA,IAAS,GAAA,CAAI,YAAA;AACnC,EAAA,MAAM,SAAS,OAAA,CAAQ,MAAA,IAAU,OAAA,CAAQ,GAAA,CAAI,IAAI,SAAS,CAAA;AAC1D,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG;AAC/C,IAAA,MAAM,IAAI,mBAAA,CAAoB,CAAA,EAAG,GAAA,CAAI,SAAS,CAAA,QAA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2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"chunk-UBDMVMBZ.js","sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { AuthenticationError, ConfigurationError, NetworkError } from \"../../../errors.js\";\nimport { mapOpenAICompatibleError } from \"../../error-mappers/openai-compatible.js\";\nimport { mapWithConcurrency } from \"../../runtime/concurrency/map-with-concurrency.js\";\nimport type {\n CreateAdapterOptions,\n EmbeddingRuntime,\n EmbeddingRuntimeStats,\n} from \"../embedding-adapter.js\";\nimport { globalEmbeddingCache } from \"../embedding-cache.js\";\n\n/**\n * Shared factory for OpenAI-compatible embedding providers (OpenAI, Mistral,\n * DeepInfra, and anything else exposing `POST /v1/embeddings` with the\n * `{ model, input }` request shape and `{ data: [{ embedding }] }` response).\n *\n * Mirrors the inner mechanics of peer-project's batch embedding runtime.\n *\n * @internal\n */\n\nconst MAX_BATCH = 100;\nconst MAX_RETRIES = 2;\n\n/**\n * What one provider adapter tells {@link createOpenAiCompatibleRuntime} about\n * its wire: where to POST, which environment variables carry the key and the\n * base URL, which model to use by default, and how wide each model's vectors\n * are.\n *\n * `id` is the provider id that ends up on errors and on\n * `EmbeddingRuntime.id`, and is also the identity the SQLite vector index stores\n * — changing it invalidates the vectors already on disk.\n *\n * `apiKeyEnv` is required, `baseUrlEnv` is not: a provider that declares no\n * base-URL variable can only be redirected by passing `baseUrl` explicitly.\n * Leave `dialect` unset for anything that speaks the OpenAI embedding wire.\n */\nexport interface OpenAiCompatibleConfig {\n id: string;\n defaultBaseUrl: string;\n apiKeyEnv: string;\n baseUrlEnv?: string;\n defaultModel: string;\n /**\n * Dimension hint by model id. The chosen model MUST be in this table —\n * unknown models throw `ConfigurationError(code: \"embedding_unknown_model\")`\n * (EC-4 fix). This prevents vec0 virtual-table dimension mismatches that\n * surface as cryptic errors downstream.\n */\n dimensionByModel: Record<string, number>;\n /**\n * Path component appended to `baseUrl` for the embeddings endpoint.\n * Default `\"/v1/embeddings\"` (OpenAI canonical). REPLACES the default —\n * does NOT concatenate. Used by DeepInfra (`\"/v1/openai/embeddings\"`),\n * etc. (EC-2 fix).\n */\n embeddingsPath?: string;\n /**\n * theokit#159 — per-provider deviations from the OpenAI wire.\n *\n * The runtime was rigidly OpenAI-shaped: one auth header, one body, one response shape. Three of\n * the ten catalog providers do not speak it, so every call they made was rejected — Azure\n * authenticates with an `api-key` header and puts the deployment in the path, Cohere's `/v2/embed`\n * takes `texts` and answers `{embeddings:{float}}`. Advertising a provider that cannot work is\n * worse than not advertising it.\n *\n * Every hook is optional and its default is exactly the previous behaviour, so the seven\n * providers that DO speak OpenAI are untouched.\n */\n dialect?: EmbeddingDialect;\n}\n\n/**\n * theokit#159 — the three points where a provider may deviate from the OpenAI embedding wire.\n *\n * Deliberately three narrow hooks rather than a general \"transform the request\" seam: these are the\n * only axes on which the supported providers actually differ, and a wider seam would invite\n * per-provider logic that belongs in the adapter.\n */\nexport interface EmbeddingDialect {\n /** Replaces `authorization: Bearer <key>`. */\n authHeaders?: (apiKey: string) => Record<string, string>;\n /** Replaces the `{ model, input }` request body. */\n body?: (model: string, inputs: ReadonlyArray<string>) => Record<string, unknown>;\n /** Replaces reading vectors from `json.data[].embedding`. Return `undefined` when unparseable. */\n vectors?: (json: unknown) => number[][] | undefined;\n}\n\n/**\n * Build an {@link EmbeddingRuntime} for a provider that speaks the OpenAI\n * embedding wire — or, through `cfg.dialect`, one that deviates from it in a\n * known way. Every adapter in the memory catalog is a thin call to this.\n *\n * Resolution order for each setting is explicit option, then environment\n * variable, then the config default. Two things are checked before any request\n * is sent, so a misconfiguration fails at creation rather than at first search:\n * a missing or empty key rejects with an `AuthenticationError` carrying\n * `embedding_missing_api_key`, and a model absent from `dimensionByModel`\n * rejects with a `ConfigurationError` carrying `embedding_unknown_model`. The\n * second check exists because the vector index is created at a fixed width — an\n * unknown dimension would surface much later as a vec0 mismatch.\n *\n * `{model}` in `embeddingsPath` is replaced with the URL-encoded model, which is\n * how Azure addresses a deployment in the path. `embeddingsPath` replaces the\n * default `/v1/embeddings` rather than being appended to it.\n *\n * The returned `embed` batches at 100 texts per request and runs at most 3\n * requests concurrently, preserving input order. Whitespace-only inputs never\n * reach the network and come back as an all-zero vector. Results are cached by\n * model and text; the cache defaults to a process-wide LRU of 5000 entries, so\n * pass `options.cache` when runtimes must not share entries.\n *\n * Failed requests retry up to twice on 429 and 5xx with a 50ms-per-attempt\n * linear backoff. Anything else, and a retry budget that runs out, throws the\n * typed error the OpenAI-compatible mapper builds from the status and body. A\n * response that parses but carries no vectors throws a `NetworkError` with\n * `embedding_invalid_response`. There is no request timeout here — cancellation\n * is the caller's to impose.\n */\nexport async function createOpenAiCompatibleRuntime(\n cfg: OpenAiCompatibleConfig,\n options: CreateAdapterOptions,\n): Promise<EmbeddingRuntime> {\n const model = options.model ?? cfg.defaultModel;\n const apiKey = options.apiKey ?? process.env[cfg.apiKeyEnv];\n if (apiKey === undefined || apiKey.length === 0) {\n throw new AuthenticationError(`${cfg.apiKeyEnv} missing`, {\n code: \"embedding_missing_api_key\",\n });\n }\n const envBaseUrl = cfg.baseUrlEnv !== undefined ? process.env[cfg.baseUrlEnv] : undefined;\n const baseUrl = options.baseUrl ?? envBaseUrl ?? cfg.defaultBaseUrl;\n const fetchImpl = options.fetch ?? fetch;\n // T4.4 — default to process-wide singleton (was per-adapter instance).\n const cache = options.cache ?? globalEmbeddingCache;\n // EC-4: refuse unknown models to prevent vec0 dimension mismatches downstream.\n const dimension = cfg.dimensionByModel[model];\n if (dimension === undefined) {\n throw new ConfigurationError(\n `${cfg.id} adapter: model \"${model}\" is not in the dimension table. Use one of: ${Object.keys(cfg.dimensionByModel).join(\", \")}. To add it, update dimensionByModel in the adapter source.`,\n { code: \"embedding_unknown_model\" },\n );\n }\n // theokit#128: `{model}` is substituted, because Azure OpenAI addresses the deployment IN THE\n // PATH (`/openai/deployments/{model}/embeddings`) rather than in the body. Without this the URL\n // carried the literal placeholder and every Azure request 404'd. A path with no placeholder —\n // every other provider — is passed through untouched.\n const embeddingsPath = (cfg.embeddingsPath ?? \"/v1/embeddings\").replace(\n \"{model}\",\n encodeURIComponent(model),\n );\n\n const stats: EmbeddingRuntimeStats = {\n cacheHits: 0,\n cacheMisses: 0,\n httpCalls: 0,\n retries: 0,\n };\n\n return {\n id: cfg.id,\n model,\n dimension,\n stats: () => ({ ...stats }),\n embed: (texts) =>\n embedTexts({\n texts,\n cache,\n stats,\n model,\n dimension,\n apiKey,\n baseUrl,\n embeddingsPath,\n fetchImpl,\n providerId: cfg.id,\n dialect: cfg.dialect ?? {},\n }),\n };\n}\n\ninterface EmbedTextsInput {\n texts: ReadonlyArray<string>;\n cache: NonNullable<CreateAdapterOptions[\"cache\"]>;\n stats: EmbeddingRuntimeStats;\n model: string;\n dimension: number;\n apiKey: string;\n baseUrl: string;\n embeddingsPath: string;\n fetchImpl: typeof fetch;\n providerId: string;\n dialect: EmbeddingDialect;\n}\n\nasync function embedTexts(input: EmbedTextsInput): Promise<number[][]> {\n const { texts, cache, stats, model, dimension } = input;\n const results = new Array<number[] | undefined>(texts.length);\n const pending: Array<{ index: number; text: string; key: string }> = [];\n for (let i = 0; i < texts.length; i++) {\n classifyEntry({\n index: i,\n text: texts[i] ?? \"\",\n model,\n dimension,\n cache,\n stats,\n results,\n pending,\n });\n }\n await embedInBoundedBatches(input, pending, results);\n return results.map((v) => v ?? new Array(dimension).fill(0));\n}\n\ninterface ClassifyEntryArgs {\n index: number;\n text: string;\n model: string;\n dimension: number;\n cache: NonNullable<CreateAdapterOptions[\"cache\"]>;\n stats: EmbeddingRuntimeStats;\n results: Array<number[] | undefined>;\n pending: Array<{ index: number; text: string; key: string }>;\n}\n\nfunction classifyEntry(args: ClassifyEntryArgs): void {\n if (args.text.trim().length === 0) {\n args.results[args.index] = new Array(args.dimension).fill(0);\n return;\n }\n const key = hashKey(args.model, args.text);\n const cached = args.cache.get(key);\n if (cached !== undefined) {\n args.stats.cacheHits += 1;\n args.results[args.index] = cached;\n return;\n }\n args.stats.cacheMisses += 1;\n args.pending.push({ index: args.index, text: args.text, key });\n}\n\n// T4.3 — max concurrent embedding API requests per embed() call.\n// 3 is enough to saturate most embedding APIs without triggering\n// rate limits (each batch is already up to MAX_BATCH=100 texts).\nconst MAX_CONCURRENT_BATCHES = 3;\n\n/**\n * T4.3 — parallel embed batches (DR4 finding #3).\n *\n * Pre-T4.3 this was a serial `for` loop — each batch of 100 texts\n * awaited before the next HTTP request started. With 500 texts the\n * serial path took 5 × RTT; parallel takes max(RTT) × ceil(5/3).\n *\n * Uses bounded-concurrency `Promise.all` capped at 3 concurrent\n * HTTP requests to avoid overwhelming the embedding API.\n */\nasync function embedInBoundedBatches(\n input: EmbedTextsInput,\n pending: ReadonlyArray<{ index: number; text: string; key: string }>,\n results: Array<number[] | undefined>,\n): Promise<void> {\n const batches: Array<ReadonlyArray<{ index: number; text: string; key: string }>> = [];\n for (let offset = 0; offset < pending.length; offset += MAX_BATCH) {\n batches.push(pending.slice(offset, offset + MAX_BATCH));\n }\n // M0-2: bounded parallel via the shared ordered pool (was an inline\n // acquire/release clone — see plan m0-foundation-expose-primitives).\n await mapWithConcurrency(batches, MAX_CONCURRENT_BATCHES, (batch) =>\n processBatch(input, batch, results),\n );\n}\n\nasync function processBatch(\n input: EmbedTextsInput,\n batch: ReadonlyArray<{ index: number; text: string; key: string }>,\n results: Array<number[] | undefined>,\n): Promise<void> {\n const vectors = await embedBatch({\n apiKey: input.apiKey,\n baseUrl: input.baseUrl,\n embeddingsPath: input.embeddingsPath,\n model: input.model,\n inputs: batch.map((b) => b.text),\n fetchImpl: input.fetchImpl,\n stats: input.stats,\n providerId: input.providerId,\n dialect: input.dialect,\n });\n for (let j = 0; j < batch.length; j++) {\n const slot = batch[j];\n const vector = vectors[j];\n if (slot === undefined || vector === undefined) continue;\n results[slot.index] = vector;\n input.cache.set(slot.key, vector);\n }\n}\n\ninterface BatchOptions {\n apiKey: string;\n baseUrl: string;\n embeddingsPath: string;\n model: string;\n inputs: ReadonlyArray<string>;\n fetchImpl: typeof fetch;\n stats: EmbeddingRuntimeStats;\n providerId: string;\n dialect: EmbeddingDialect;\n}\n\nasync function embedBatch(opts: BatchOptions): Promise<number[][]> {\n // EC-2: embeddingsPath REPLACES the suffix; never concatenates.\n const url = `${opts.baseUrl.replace(/\\/$/, \"\")}${opts.embeddingsPath}`;\n let attempt = 0;\n while (true) {\n opts.stats.httpCalls += 1;\n const response = await postEmbedRequest(opts, url);\n if (response.ok)\n return await parseEmbedResponse(response, opts.providerId, opts.embeddingsPath, opts.dialect);\n if (isRetryable(response.status) && attempt < MAX_RETRIES) {\n attempt += 1;\n opts.stats.retries += 1;\n await sleep(linearBackoffMs(attempt));\n continue;\n }\n // Read body (best-effort) so the mapper has access to provider error code.\n const text = await response.text().catch(() => \"\");\n let body: unknown = text;\n try {\n body = JSON.parse(text);\n } catch {\n // not JSON — keep as string\n }\n throw mapOpenAICompatibleError({\n providerId: opts.providerId,\n status: response.status,\n body,\n headers: response.headers,\n endpoint: opts.embeddingsPath,\n });\n }\n}\n\nasync function postEmbedRequest(opts: BatchOptions, url: string): Promise<Response> {\n return opts.fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(opts.dialect.authHeaders?.(opts.apiKey) ?? { authorization: `Bearer ${opts.apiKey}` }),\n },\n body: JSON.stringify(\n opts.dialect.body?.(opts.model, opts.inputs) ?? { model: opts.model, input: opts.inputs },\n ),\n });\n}\n\nasync function parseEmbedResponse(\n response: Response,\n providerId: string,\n endpoint: string,\n dialect?: EmbeddingDialect,\n): Promise<number[][]> {\n const json = (await response.json()) as { data?: Array<{ embedding: number[] }> };\n // theokit#159 — a provider whose response is not OpenAI-shaped supplies its own reader.\n const viaDialect = dialect?.vectors?.(json);\n if (viaDialect !== undefined) return viaDialect;\n if (!Array.isArray(json.data)) {\n throw new NetworkError(`${providerId} ${endpoint} returned no data`, {\n code: \"embedding_invalid_response\",\n metadata: {\n provider: providerId,\n endpoint,\n code: \"invalid_request\",\n raw: json,\n },\n });\n }\n return json.data.map((d) => d.embedding);\n}\n\nfunction isRetryable(status: number): boolean {\n return status === 429 || (status >= 500 && status < 600);\n}\n\nfunction hashKey(model: string, text: string): string {\n return createHash(\"sha256\").update(`${model} ${text}`).digest(\"hex\");\n}\n\nfunction linearBackoffMs(attempt: number): number {\n return 50 * attempt;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { LruEmbeddingCache } from './chunk-H73MEMQB.js';
|
|
2
|
-
import { resolveMemoryRoot, defaultIndexPath, projectMemoryDir, openMemoryDb, collectMarkdownFiles, sha256, truncateSnippet, resolveWeights, blendScores, LanceIndex } from './chunk-
|
|
2
|
+
import { resolveMemoryRoot, defaultIndexPath, projectMemoryDir, openMemoryDb, collectMarkdownFiles, sha256, truncateSnippet, resolveWeights, blendScores, LanceIndex } from './chunk-GEEXBYFL.js';
|
|
3
3
|
import { sanitizeFts5Query } from './chunk-WE22OXQA.js';
|
|
4
|
-
import { ConfigurationError } from './chunk-
|
|
4
|
+
import { ConfigurationError } from './chunk-ZZMZWBR6.js';
|
|
5
5
|
import { createHash } from 'crypto';
|
|
6
6
|
import { readFile, stat } from 'fs/promises';
|
|
7
7
|
|
|
@@ -548,5 +548,5 @@ var IndexManager = class _IndexManager {
|
|
|
548
548
|
};
|
|
549
549
|
|
|
550
550
|
export { IndexManager };
|
|
551
|
-
//# sourceMappingURL=chunk-
|
|
552
|
-
//# sourceMappingURL=chunk-
|
|
551
|
+
//# sourceMappingURL=chunk-UEXIJTLC.js.map
|
|
552
|
+
//# sourceMappingURL=chunk-UEXIJTLC.js.map
|