@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,6 +1,6 @@
|
|
|
1
|
-
import { resolveCredential } from './chunk-
|
|
2
|
-
import { readStoredOAuth } from './chunk-
|
|
3
|
-
import { diag } from './chunk-
|
|
1
|
+
import { resolveCredential } from './chunk-2QDYBS2A.js';
|
|
2
|
+
import { readStoredOAuth } from './chunk-C3NT3PVE.js';
|
|
3
|
+
import { diag } from './chunk-XEQ3TM66.js';
|
|
4
4
|
import { readFileSync } from 'fs';
|
|
5
5
|
import { dirname, join } from 'path';
|
|
6
6
|
import { fileURLToPath } from 'url';
|
|
@@ -552,5 +552,5 @@ function registerBuiltins() {
|
|
|
552
552
|
}
|
|
553
553
|
|
|
554
554
|
export { catalogModelSchema, getCatalogCapabilities, getCatalogModelInfo, getProviderProfile, globalSingleton, inferModelDialect, inferRegionFromModelId, isPatchedModelKey, listProviders, loadProviderCatalog, patchModelInfo, registerBuiltins, registerProvider, resolveBedrockBaseUrl, resolveVertexBaseUrl, stripBedrockPrefix, stripVertexPrefix };
|
|
555
|
-
//# sourceMappingURL=chunk-
|
|
556
|
-
//# sourceMappingURL=chunk-
|
|
555
|
+
//# sourceMappingURL=chunk-WLQNMXQE.js.map
|
|
556
|
+
//# sourceMappingURL=chunk-WLQNMXQE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/global-singleton.ts","../src/internal/providers/registry.ts","../src/internal/providers/catalog-schema.ts","../src/internal/providers/catalog-loader.ts","../src/internal/providers/builtin/anthropic.ts","../src/internal/providers/builtin/bedrock.ts","../src/internal/providers/builtin/openai-compatible.ts","../src/internal/providers/builtin/cerebras.ts","../src/internal/providers/builtin/cohere.ts","../src/internal/providers/builtin/deepinfra.ts","../src/internal/providers/builtin/gemini.ts","../src/internal/providers/builtin/google.ts","../src/internal/providers/builtin/groq.ts","../src/internal/providers/builtin/llamacpp.ts","../src/internal/providers/builtin/lmstudio.ts","../src/internal/providers/builtin/mistral.ts","../src/internal/providers/builtin/ollama.ts","../src/internal/providers/builtin/openai.ts","../src/internal/providers/builtin/openai-chatgpt.ts","../src/internal/providers/builtin/openrouter.ts","../src/internal/providers/builtin/perplexity.ts","../src/internal/providers/builtin/together.ts","../src/internal/providers/builtin/vertex.ts","../src/internal/providers/builtin/xai.ts","../src/internal/providers/builtin/index.ts"],"names":[],"mappings":";;;;;;;;;;AAYO,SAAS,eAAA,CAAmB,KAAa,MAAA,EAAoB;AAClE,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AAC1B,EAAA,IAAI,EAAE,GAAG,CAAA,KAAM,QAAW,CAAA,CAAE,GAAG,IAAI,MAAA,EAAO;AAC1C,EAAA,OAAO,EAAE,GAAG,CAAA;AACd;;;ACIA,IAAM,QAAA,GAAW,eAAA;AAAA,EACf,gCAAA;AAAA,EACA,0BAAU,GAAA;AACZ,CAAA;AACA,IAAM,UAAU,eAAA,CAAgB,+BAAA,EAAiC,sBAAM,IAAI,KAAqB,CAAA;AAEzF,SAAS,iBAAiB,OAAA,EAAgC;AAC/D,EAAA,IAAI,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC9B,IAAA,IAAA,CAAK,CAAA,wBAAA,EAA2B,QAAQ,IAAI,CAAA;AAAA,CAAgC,CAAA;AAAA,EAC9E;AACA,EAAA,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAClC,EAAA,KAAA,MAAW,KAAA,IAAS,OAAA,CAAQ,OAAA,IAAW,EAAC,EAAG;AAEzC,IAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,KAAK,CAAA;AAClC,IAAA,IAAI,QAAA,KAAa,MA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AAA,gBAAA,CAAiB,IAAI,CAAA;AACrB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,SAAS,CAAA;AAC1B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,GAAG,CAAA;AACpB,EAAA,gBAAA,CAAiB,UAAU,CAAA;AAC3B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AAEzB,EAAA,wBAAA,EAAyB;AAC3B","file":"chunk-Q4CMI2LP.js","sourcesContent":["/**\n * One singleton per realm, keyed by `Symbol.for`.\n *\n * It exists because a package can be loaded more than once in the same process (two copies in\n * `node_modules`, ESM and CJS side by side, a monorepo with distinct versions) — and then a module-level\n * `const x = new Map()` produces TWO caches that cannot see each other. `Symbol.for` uses the global\n * symbol registry, which belongs to the realm and not the module, so every copy converges on one instance.\n *\n * It was copied verbatim into `providers/discovery.ts` and `providers/catalog-loader.ts`. That is\n * duplicated KNOWLEDGE, not a coincidence of shape: the two copies have to agree on the\n * mechanism, and one fixed without the other produces exactly the bug the function exists to avoid.\n */\nexport function globalSingleton<T>(key: string, create: () => T): T {\n const g = globalThis as unknown as Record<symbol, T>;\n const sym = Symbol.for(key);\n if (g[sym] === undefined) g[sym] = create();\n return g[sym];\n}\n","/**\n * Provider registry (T3.2, ADR D107).\n *\n * `registerProvider` is idempotent and surface-warning: re-registering\n * a `name` logs to stderr (D107 last-writer-wins with WARN). Alias\n * collisions also warn (EC-5).\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport type { ProviderProfile } from \"./types.js\";\n\n/**\n * M44 B1 fix — the registry state lives on `globalThis` keyed by `Symbol.for`, so EVERY bundle copy of this\n * module (tsup bundles each entry separately with `splitting: false` — `dist/index.js` and `dist/models.js`\n * each embed their own copy) shares the SAME maps. Without this, `@theokit/sdk/models`'s\n * `refreshModelCatalog` saw an eternally-empty registry and its patches were invisible to the core bundle's\n * capability/pricing lookups (state duplication made load-bearing by M44).\n */\nconst REGISTRY = globalSingleton(\n \"theokit-sdk.providers.registry\",\n () => new Map<string, ProviderProfile>(),\n);\nconst ALIASES = globalSingleton(\"theokit-sdk.providers.aliases\", () => new Map<string, string>());\n\nexport function registerProvider(profile: ProviderProfile): void {\n if (REGISTRY.has(profile.name)) {\n diag(`[theokit-sdk] Provider \"${profile.name}\" overridden by user plugin.\\n`);\n }\n REGISTRY.set(profile.name, profile);\n for (const alias of profile.aliases ?? []) {\n // EC-5: surface alias collision so operators notice mis-routing.\n const previous = ALIASES.get(alias);\n if (previous !== undefined && previous !== profile.name) {\n diag(`[theokit-sdk] Alias \"${alias}\" collision: was \"${previous}\", now \"${profile.name}\".\\n`);\n }\n ALIASES.set(alias, profile.name);\n }\n}\n\nexport function getProviderProfile(name: string): ProviderProfile | undefined {\n const canonical = ALIASES.get(name) ?? name;\n return REGISTRY.get(canonical);\n}\n\nexport function listProviders(): ProviderProfile[] {\n return Array.from(REGISTRY.values());\n}\n\n/** Test-only reset. @internal */\nexport function _resetProvidersForTests(): void {\n REGISTRY.clear();\n ALIASES.clear();\n}\n","import { z } from \"zod\";\n\n/**\n * M44 — the per-model catalog sub-schema. Field names mirror models.dev VERBATIM (snake_case) so\n * `scripts/refresh-catalog.mjs` regenerates the vendored data mechanically from `api.json` with zero\n * renaming (ADR D1).\n * TOLERANT by design: every field optional, unknown keys ignored — models.dev adds fields over time and\n * additive drift must never break the loader (Blueprint §6.4).\n *\n * theokit extensions beyond models.dev: `structured_output` / `cache_control` (both already exist on the\n * SDK's `ModelCapabilities`; models.dev has no such flags).\n *\n * Semver-exempt: nothing here is declared in `package.json` `exports`. `MODALITIES` is nonetheless\n * reachable from published declarations through the type graph, so it must be EMITTED.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows; the tag that\n * used to sit here deleted the `MODALITIES` declaration below from the emitted `.d.ts`.\n */\n\nexport const MODALITIES = [\"text\", \"audio\", \"image\", \"video\", \"pdf\"] as const;\n\n/**\n * One input or output medium a model accepts or produces.\n *\n * The union is derived from `MODALITIES`, so it is closed: a models.dev entry whose\n * `modalities.input` or `modalities.output` array contains a string outside this set fails\n * `catalogModelSchema.safeParse`, and `patchIndexFromApiJson` drops that single model rather\n * than the whole payload. Widening the catalog to a new medium means adding it to `MODALITIES`\n * first — nothing else in the schema enumerates media.\n */\nexport type Modality = (typeof MODALITIES)[number];\n\nconst costSchema = z\n .object({\n /** USD per 1M tokens (models.dev convention). */\n input: z.number().nonnegative(),\n output: z.number().nonnegative(),\n cache_read: z.number().nonnegative().optional(),\n cache_write: z.number().nonnegative().optional(),\n })\n .loose();\n\nconst limitSchema = z\n .object({\n context: z.number().positive(),\n input: z.number().positive().optional(),\n output: z.number().positive().optional(),\n })\n .loose();\n\nconst modalitiesSchema = z\n .object({\n input: z.array(z.enum(MODALITIES)).optional(),\n output: z.array(z.enum(MODALITIES)).optional(),\n })\n .loose();\n\nexport const catalogModelSchema = z\n .object({\n name: z.string().optional(),\n release_date: z.string().optional(),\n attachment: z.boolean().optional(),\n reasoning: z.boolean().optional(),\n temperature: z.boolean().optional(),\n tool_call: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsStructuredOutput. */\n structured_output: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsCacheControl. */\n cache_control: z.boolean().optional(),\n cost: costSchema.optional(),\n limit: limitSchema.optional(),\n modalities: modalitiesSchema.optional(),\n status: z.enum([\"alpha\", \"beta\", \"deprecated\"]).optional(),\n })\n .loose();\n\n/**\n * One model entry as it is stored in the vendored catalog and as models.dev publishes it.\n *\n * Every field is optional, so an entry that carries only `name` still parses. Reading a value\n * therefore means handling `undefined` at each level — `model.cost?.cache_read`, not\n * `model.cost.cache_read`. Field names are models.dev's own snake_case, kept verbatim so the\n * refresh script can copy `api.json` across without renaming.\n *\n * The schema is loose rather than strict: unknown keys survive parsing and stay on the returned\n * object instead of being rejected or dropped. That is what lets models.dev add a field without\n * breaking the loader — the cost is that a typo in a key name parses silently, so a caller\n * cannot use \"it parsed\" as evidence that a field it expected was present.\n *\n * `structured_output` and `cache_control` are theokit's own additions; models.dev publishes\n * neither.\n */\nexport type CatalogModel = z.infer<typeof catalogModelSchema>;\n\n/**\n * Per-token pricing for one model, in USD per 1M tokens (models.dev's unit — not per token, and\n * not per 1K).\n *\n * `input` and `output` are required and non-negative; the two cache buckets are optional and\n * absent for models that do not price caching separately. Absent is not zero: a missing\n * `cache_read` means the catalog says nothing about the cost of a cache hit, so a caller that\n * defaults it to 0 is asserting free cache reads on its own authority.\n *\n * Like `CatalogModel`, the shape is loose — unknown pricing keys published upstream are kept on\n * the parsed value.\n */\nexport type CatalogModelCost = z.infer<typeof costSchema>;\n","/**\n * Dynamic provider catalog loader (T10.1, ADR D447).\n *\n * Loads provider metadata from `provider-catalog.json` at runtime.\n * Malformed entries are skipped with WARN (EC-1) — never crash.\n *\n * @internal\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport { type CatalogModel, catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile, registerProvider } from \"./registry.js\";\nimport type { ApiMode, AuthType, ProviderProfile } from \"./types.js\";\n\nconst __dirname_resolved = dirname(fileURLToPath(import.meta.url));\n\nexport interface ProviderCapabilities {\n supportsToolUse: boolean;\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsStreaming: boolean;\n supportsCacheControl: boolean;\n maxContextTokens?: number;\n maxOutputTokens?: number;\n}\n\nexport interface CatalogEntry {\n id: string;\n displayName: string;\n apiMode: ApiMode;\n authType: AuthType;\n baseUrl: string;\n envVars: string[];\n fallbackModels: string[];\n capabilities: ProviderCapabilities;\n aliases?: string[];\n modelsUrl?: string;\n hostname?: string;\n extraHeaders?: Record<string, string>;\n /**\n * M44 — OPTIONAL per-model data (models.dev shape, snake_case — see `catalog-schema.ts`), keyed by the\n * BARE model id. Additive: entries without it behave byte-identically to before. The loader indexes this\n * into the model-info index (`getCatalogModelInfo`) rather than onto `ProviderProfile` (ADR D2 — the\n * builtins-first registration skip means profile-attached data would never reach builtin providers).\n */\n models?: Record<string, CatalogModel>;\n}\n\n/**\n * M44 — the model-info index: `provider/model` → per-model catalog data (the EXACT-map key convention).\n * Populated by the vendored catalog load AND patched by the optional models-dev source (cache entries win\n * per model). The single lookup surface for capability / cost / limit enrichment.\n */\n// M44 B1 fix — index state on globalThis (Symbol.for) so every bundle copy shares the SAME maps (see the\n// identical pattern + rationale in registry.ts).\nconst modelInfoIndex = globalSingleton(\n \"theokit-sdk.providers.model-info-index\",\n () => new Map<string, CatalogModel>(),\n);\n/** M44 M5 fix — keys patched by the live models-dev source (honest pricing provenance). */\nconst patchedModelKeys = globalSingleton(\n \"theokit-sdk.providers.model-info-patched\",\n () => new Set<string>(),\n);\nconst indexState = globalSingleton(\"theokit-sdk.providers.model-info-loaded\", () => ({\n loaded: false,\n}));\n\n/**\n * Look up per-model catalog data by `provider/model` key.\n *\n * Semver-exempt: not declared in `package.json` `exports`, but re-exported by\n * `catalog-source-models-dev.ts`, whose declaration is reachable from published entries — so it\n * must be EMITTED.\n */\nexport function getCatalogModelInfo(key: string): CatalogModel | undefined {\n ensureModelIndexLoaded();\n return modelInfoIndex.get(key);\n}\n\n/** Was this key patched by the LIVE models-dev source (vs the vendored catalog)? @internal */\nexport function isPatchedModelKey(key: string): boolean {\n return patchedModelKeys.has(key);\n}\n\n/**\n * Patch the index with fresher per-model data (the models-dev source). M44 H2 fix — a per-FIELD shallow\n * MERGE, not a wholesale replace: models.dev can never supply the theokit extension fields\n * (`cache_control`, `structured_output` overlays), so a replace would wipe them and silently flip\n * capability answers. Incoming fields win; existing fields survive when the patch omits them.\n * @internal\n */\nexport function patchModelInfo(key: string, model: CatalogModel): void {\n ensureModelIndexLoaded();\n const existing = modelInfoIndex.get(key);\n modelInfoIndex.set(key, existing === undefined ? model : { ...existing, ...model });\n patchedModelKeys.add(key);\n}\n\n/** All indexed `provider/model` keys (for maintenance/tests). @internal */\nexport function listModelInfoKeys(): string[] {\n ensureModelIndexLoaded();\n return [...modelInfoIndex.keys()];\n}\n\nfunction ensureModelIndexLoaded(): void {\n if (indexState.loaded) return;\n indexState.loaded = true;\n // M44 L9 fix — never throw from a capability/pricing lookup: a missing/corrupt vendored catalog degrades\n // to conservative defaults with a WARN (the deleted EXACT map could never throw; keep that property).\n try {\n const catalog = loadProviderCatalog();\n for (const entry of Object.values(catalog)) {\n indexEntryModels(entry);\n }\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: provider catalog unavailable (${(err as Error).message}) — per-model data disabled\\n`,\n );\n }\n}\n\n/**\n * Index an entry's `models` block. Runs for EVERY catalog entry — including those whose PROVIDER\n * registration is skipped builtins-first — so builtin providers still get their per-model data (ADR D2).\n * A malformed model sub-entry drops THAT MODEL with WARN and keeps the provider (EC-1 philosophy extended).\n */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction indexEntryModels(entry: CatalogEntry): void {\n if (entry.models === undefined || typeof entry.models !== \"object\") return;\n for (const [modelId, raw] of Object.entries(entry.models)) {\n const parsed = catalogModelSchema.safeParse(raw);\n if (!parsed.success) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog model \"${entry.id}/${modelId}\": ` +\n `${parsed.error.issues[0]?.message ?? \"invalid\"}\\n`,\n );\n continue;\n }\n // Index under the entry id AND every alias — capability lookups are VENDOR-keyed (e.g.\n // `google/gemini-2.5-pro` while the entry id is `google-gemini` with alias `google`), so alias keys are\n // what make the vendor-keyed convention resolve without a second mapping table.\n modelInfoIndex.set(`${entry.id}/${modelId}`, parsed.data);\n for (const alias of entry.aliases ?? []) {\n const key = `${alias}/${modelId}`;\n if (!modelInfoIndex.has(key)) modelInfoIndex.set(key, parsed.data);\n }\n }\n}\n\n/** Test-only reset for the model-info index. @internal */\nexport function _resetModelInfoIndexForTests(): void {\n modelInfoIndex.clear();\n patchedModelKeys.clear();\n indexState.loaded = false;\n}\n\ninterface LoadOptions {\n _testInjectMalformed?: boolean;\n}\n\nfunction validateEntry(raw: Record<string, unknown>): CatalogEntry | null {\n if (\n typeof raw.id !== \"string\" ||\n typeof raw.displayName !== \"string\" ||\n typeof raw.apiMode !== \"string\" ||\n typeof raw.authType !== \"string\" ||\n typeof raw.baseUrl !== \"string\" ||\n !Array.isArray(raw.envVars) ||\n !Array.isArray(raw.fallbackModels) ||\n raw.capabilities == null ||\n typeof raw.capabilities !== \"object\"\n ) {\n return null;\n }\n return raw as unknown as CatalogEntry;\n}\n\nexport function loadProviderCatalog(opts?: LoadOptions): Record<string, CatalogEntry> {\n const catalogPath = join(__dirname_resolved, \"provider-catalog.json\");\n const rawText = readFileSync(catalogPath, \"utf-8\");\n let entries: Record<string, unknown>[] = JSON.parse(rawText);\n\n if (opts?._testInjectMalformed) {\n entries = [\n ...entries,\n { id: \"malformed-provider\", displayName: \"Bad\" } as Record<string, unknown>,\n ];\n }\n\n const result: Record<string, CatalogEntry> = {};\n for (const raw of entries) {\n const validated = validateEntry(raw as Record<string, unknown>);\n if (validated === null) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog entry: ${JSON.stringify(raw).slice(0, 100)}\\n`,\n );\n continue;\n }\n result[validated.id] = validated;\n }\n return result;\n}\n\nlet _capabilitiesCache: Record<string, ProviderCapabilities> | null = null;\n\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nexport function getCatalogCapabilities(providerId: string): ProviderCapabilities | undefined {\n if (_capabilitiesCache === null) {\n const catalog = loadProviderCatalog();\n _capabilitiesCache = {};\n for (const entry of Object.values(catalog)) {\n _capabilitiesCache[entry.id] = entry.capabilities;\n // M45 review L4 — alias keys too (e.g. entry `google-gemini` alias `google`), consistent with the\n // model-info index's alias-keyed convention.\n for (const alias of entry.aliases ?? []) {\n if (_capabilitiesCache[alias] === undefined) _capabilitiesCache[alias] = entry.capabilities;\n }\n }\n }\n return _capabilitiesCache[providerId];\n}\n\nexport function registerCatalogProviders(opts?: LoadOptions): void {\n const catalog = loadProviderCatalog(opts);\n for (const entry of Object.values(catalog)) {\n // Skip catalog entries that would overwrite first-party builtins.\n // Builtins have richer env-var handling and are registered first.\n // Also skip if any alias collides with an existing provider name.\n if (getProviderProfile(entry.id) !== undefined) continue;\n if (entry.aliases?.some((a) => getProviderProfile(a) !== undefined)) continue;\n\n const profile: ProviderProfile = {\n name: entry.id,\n apiMode: entry.apiMode,\n authType: entry.authType,\n baseUrl: entry.baseUrl,\n envVars: entry.envVars,\n fallbackModels: entry.fallbackModels,\n displayName: entry.displayName,\n aliases: entry.aliases,\n modelsUrl: entry.modelsUrl,\n hostname: entry.hostname,\n extraHeaders: entry.extraHeaders,\n };\n registerProvider(profile);\n }\n}\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const ANTHROPIC: ProviderProfile = {\n name: \"anthropic\",\n apiMode: \"anthropic_messages\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.anthropic.com\",\n modelsUrl: \"https://api.anthropic.com/v1/models\",\n hostname: \"api.anthropic.com\",\n fallbackModels: [\"claude-opus-4-7\", \"claude-sonnet-4-6\", \"claude-haiku-4-5-20251001\"],\n // M45 — the Anthropic beta-features header (interleaved thinking + fine-grained tool streaming). An\n // Anthropic API constant. The\n // SANCTIONED behavior delta of M45 (ADR D4) — consumed by the anthropic transport's extraHeaders wiring.\n extraHeaders: {\n \"anthropic-beta\": \"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\",\n },\n};\n","/**\n * AWS Bedrock profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Bearer-only auth via `AWS_BEARER_TOKEN_BEDROCK` env (GA Sep 2025).\n * Optional `@aws/bedrock-token-generator` peer dep auto-refreshes short-term\n * tokens (D287). Transport via native `fetch`; no `@aws-sdk/*` dependency.\n *\n * Model IDs follow the `bedrock/{aws-id}` convention so the router can\n * infer the provider via prefix routing (D186). The client strips the\n * `bedrock/` prefix before building the URL.\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const BEDROCK: ProviderProfile = {\n name: \"bedrock\",\n apiMode: \"bedrock_anthropic\",\n envVars: [\"AWS_BEARER_TOKEN_BEDROCK\"],\n authType: \"aws_bearer\",\n baseUrl: \"https://bedrock-runtime.us-east-1.amazonaws.com\",\n modelsUrl: undefined,\n hostname: \"bedrock-runtime.amazonaws.com\",\n fallbackModels: [\n \"bedrock/us.anthropic.claude-sonnet-4-5-v1:0\",\n \"bedrock/us.anthropic.claude-opus-4-7-v1:0\",\n \"bedrock/global.anthropic.claude-haiku-4-5-v1:0\",\n ],\n};\n\n/** Strip `\"bedrock/\"` prefix so the raw AWS model id is used in the URL. */\nexport function stripBedrockPrefix(modelId: string): string {\n return modelId.replace(/^bedrock\\//, \"\");\n}\n\n/**\n * Infer AWS region from a Bedrock model id prefix (D290).\n *\n * `global.*` routes via `us-east-1` (AWS default entrypoint for global\n * inference profiles).\n */\nexport function inferRegionFromModelId(modelId: string): string | undefined {\n const id = stripBedrockPrefix(modelId);\n if (id.startsWith(\"global.\")) return \"us-east-1\";\n if (id.startsWith(\"us.\")) return process.env.AWS_REGION ?? \"us-east-1\";\n if (id.startsWith(\"eu.\")) return process.env.AWS_REGION ?? \"eu-west-1\";\n if (id.startsWith(\"apac.\")) return process.env.AWS_REGION ?? \"ap-southeast-1\";\n if (id.startsWith(\"jp.\")) return \"ap-northeast-1\";\n return undefined;\n}\n\n/** Resolve baseUrl from model id; falls back to `AWS_REGION` env or `us-east-1`. */\nexport function resolveBedrockBaseUrl(modelId: string): string {\n const region = inferRegionFromModelId(modelId) ?? process.env.AWS_REGION ?? \"us-east-1\";\n return `https://bedrock-runtime.${region}.amazonaws.com`;\n}\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * M45 — the data-only base for OpenAI-compatible chat_completions providers. A profile-map pattern\n * flattened to\n * theokit's data model: leaves declare name/baseUrl/envVars (+ overrides) in ~10 lines; the router's\n * URL-join rule (version-segment detection + `chatCompletionsPath` escape) derives the endpoint.\n *\n * @internal\n */\nexport function openAiCompatibleProfile(\n p: { name: string; baseUrl: string; envVars: readonly string[] } & Partial<ProviderProfile>,\n): ProviderProfile {\n return {\n apiMode: \"chat_completions\",\n authType: \"api_key\",\n fallbackModels: [],\n ...p,\n };\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cerebras. The integration header value is theokit's own: the header attributes TRAFFIC.\n * Models per models.dev (2026-07 snapshot).\n */\nexport const CEREBRAS = openAiCompatibleProfile({\n name: \"cerebras\",\n baseUrl: \"https://api.cerebras.ai/v1\",\n envVars: [\"CEREBRAS_API_KEY\"],\n fallbackModels: [\"gpt-oss-120b\", \"zai-glm-4.7\"],\n extraHeaders: { \"X-Cerebras-3rd-Party-Integration\": \"theokit\" },\n hostname: \"api.cerebras.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cohere via its OpenAI-compatibility surface (`api.cohere.ai/compatibility/v1` — the native v2 API\n * is NOT chat_completions; the discovery flagged the old catalog baseUrl as doubly wrong). Models per\n * models.dev `cohere` (2026-07 snapshot). SOURCE NOTE (review L2): the compatibility endpoint + `CO_API_KEY`\n * come from Cohere's own docs/python-SDK convention (not vendored in this repo's references) — verify with a\n * live smoke when a key is available.\n */\nexport const COHERE = openAiCompatibleProfile({\n name: \"cohere\",\n baseUrl: \"https://api.cohere.ai/compatibility/v1\",\n envVars: [\"COHERE_API_KEY\", \"CO_API_KEY\"],\n fallbackModels: [\"command-a-03-2025\"],\n hostname: \"api.cohere.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — DeepInfra. OpenAI-compat surface under /v1/openai (models.dev `deepinfra`). */\nexport const DEEPINFRA = openAiCompatibleProfile({\n name: \"deepinfra\",\n baseUrl: \"https://api.deepinfra.com/v1/openai\",\n envVars: [\"DEEPINFRA_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen3-32B\"],\n hostname: \"api.deepinfra.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Gemini via OpenRouter passthrough. Direct Gemini API uses a different\n * dialect (`generateContent`); SDK currently routes through OpenRouter's\n * OpenAI-compatible endpoint so the chat_completions transport works.\n *\n * A future plugin `@theokit-provider-gemini-direct` can override this with\n * `apiMode: \"gemini_generate_content\"` once that transport ships.\n */\nexport const GEMINI: ProviderProfile = {\n name: \"gemini\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENROUTER_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n hostname: \"openrouter.ai\",\n fallbackModels: [\"google/gemini-2.0-flash-001\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Google Gemini via the DIRECT OpenAI-compat endpoint (a Google API key, not OpenRouter). Distinct\n * from the `gemini` builtin (an OpenRouter passthrough) by ADR D3 — two routes, two names. Endpoint + env\n * vars per Google's OpenAI-compatibility docs (mirrored by models.dev `google` + the M44 catalog entry).\n */\nexport const GOOGLE = openAiCompatibleProfile({\n name: \"google\",\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta/openai\",\n envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n fallbackModels: [\"gemini-2.5-pro\", \"gemini-2.5-flash\"],\n hostname: \"generativelanguage.googleapis.com\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Groq. Values per models.dev `groq` (2026-07 snapshot); OpenAI-compat surface under /openai/v1. */\nexport const GROQ = openAiCompatibleProfile({\n name: \"groq\",\n baseUrl: \"https://api.groq.com/openai/v1\",\n envVars: [\"GROQ_API_KEY\"],\n fallbackModels: [\"llama-3.3-70b-versatile\", \"llama-3.1-8b-instant\"],\n hostname: \"api.groq.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * llama.cpp server provider profile (T7.2, ADR D189).\n *\n * llama.cpp ships a HTTP server binary (`./server` since b1500+) that\n * implements the OpenAI-compatible `/v1/chat/completions` endpoint on\n * `http://localhost:8080` by default. Inherits `authType: \"none\"` from\n * D182 — no API key required for local use.\n *\n * llama.cpp idiosyncrasies:\n * - Server loads a single GGUF model at startup via `--model` CLI\n * flag. The `model` field in the chat-completions request is\n * cosmetic — any string works; the response comes from the loaded\n * model regardless. This is documented in\n * `.claude/knowledge-base/reviews/edge-case/ollama-integration-edge-cases-2026-05-21.md`\n * as EC-O.\n * - Tool calling support depends entirely on the underlying model.\n *\n * Override the default URL with `LLAMACPP_HOST`.\n *\n * @internal\n */\nexport const LLAMACPP: ProviderProfile = {\n name: \"llamacpp\",\n aliases: [\"llama-cpp\", \"llama.cpp\"],\n apiMode: \"chat_completions\",\n envVars: [\"LLAMACPP_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:8080\",\n modelsUrl: \"http://localhost:8080/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * LM Studio provider profile (T7.1, ADR D188).\n *\n * LM Studio exposes an OpenAI-compatible `/v1/chat/completions` endpoint\n * on `http://localhost:1234` by default (configurable via the LM Studio\n * UI under \"Local Server\"). Inherits the `authType: \"none\"` primitive\n * from D182 — no API key required for local use.\n *\n * LM Studio idiosyncrasies:\n * - Loads ONE model at a time via the desktop UI. The `model` field in\n * the chat-completions request is informational only — LM Studio\n * serves whatever model is currently loaded.\n * - `/v1/models` returns a single entry pointing to the loaded model.\n * - Tool calling depends on the underlying model.\n *\n * Override the default URL with `LMSTUDIO_HOST` (mirrors `OLLAMA_HOST`).\n *\n * @internal\n */\nexport const LMSTUDIO: ProviderProfile = {\n name: \"lmstudio\",\n aliases: [\"lm-studio\", \"lm_studio\"],\n apiMode: \"chat_completions\",\n envVars: [\"LMSTUDIO_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:1234\",\n modelsUrl: \"http://localhost:1234/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Mistral (La Plateforme). Values per models.dev `mistral` (2026-07 snapshot). */\nexport const MISTRAL = openAiCompatibleProfile({\n name: \"mistral\",\n baseUrl: \"https://api.mistral.ai/v1\",\n envVars: [\"MISTRAL_API_KEY\"],\n fallbackModels: [\"mistral-large-latest\", \"codestral-latest\"],\n hostname: \"api.mistral.ai\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Ollama — local-first LLM runtime (ADR D182).\n *\n * Ships as a builtin so `Agent.create({ model: \"ollama/llama3.2\" })` works\n * with zero configuration when `ollama serve` is running on the default\n * port. `authType: \"none\"` signals the router to skip env-key resolution\n * and use a placeholder credential (Ollama ignores Authorization headers\n * on local installs).\n *\n * Overrides:\n * - `OLLAMA_HOST` — replaces the default `http://localhost:11434` baseUrl\n * (advanced users running Ollama on a remote machine).\n * - `OLLAMA_API_KEY` — replaces the placeholder when Ollama is behind a\n * reverse-proxy with auth or when using Ollama Cloud (paid tier).\n */\nexport const OLLAMA: ProviderProfile = {\n name: \"ollama\",\n apiMode: \"chat_completions\",\n envVars: [\"OLLAMA_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:11434\",\n modelsUrl: \"http://localhost:11434/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"llama3.2\", \"qwen2.5\", \"mistral\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENAI: ProviderProfile = {\n name: \"openai\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.openai.com\",\n modelsUrl: \"https://api.openai.com/v1/models\",\n hostname: \"api.openai.com\",\n fallbackModels: [\"gpt-4o\", \"gpt-4o-mini\"],\n};\n","/**\n * M43 — the ChatGPT \"Codex\" backend as a first-class builtin `ProviderProfile`. Migrated from the\n * agent-builder M40 workaround; the SDK now owns the provider, so a consumer only selects\n * `openai-chatgpt/<model>` and logs in — ZERO provider logic in the consumer.\n *\n * The provider-auth model (see the codex-provider-in-sdk blueprint):\n * - static profile + a `transform.fetch` that resolves the LIVE credential per HTTP request (fresh Bearer +\n * dynamic `ChatGPT-Account-Id`), so a mid-turn expiry refreshes transparently with NO agent rebuild;\n * - the protocol values (endpoint, models, oauth config, `originator` header) are SDK-owned constants.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\n\nimport type { CredentialStoreConfig, OAuthProviderConfig } from \"../../auth/auth-types.js\";\nimport { readStoredOAuth } from \"../../auth/credential-store.js\";\nimport { resolveCredential } from \"../../auth/resolve-credential.js\";\nimport type { ProviderProfile } from \"../types.js\";\n\n/**\n * The SDK-owned ambient credential store the transform reads. Defaults to `~/.theokit/auth.json`. A consumer\n * points it at its existing store dir via the DEDICATED `THEOKIT_AUTH_HOME` env var (NOT `THEOKIT_HOME` — that\n * is the SDK's whole home directory for personality/credential-pool/profiles; overloading it would redirect\n * the entire runtime). The SDK's ambient credential service.\n */\nconst DEFAULT_STORE: CredentialStoreConfig = {\n home: homedir(),\n dirName: \".theokit\",\n fileName: \"auth.json\",\n homeEnvVar: \"THEOKIT_AUTH_HOME\",\n};\n\n/**\n * The OpenAI OAuth config the transform resolves + refreshes against. `provider: \"openai\"` is the STORE\n * provider (what `/login` persists), deliberately distinct from this profile's routing name `openai-chatgpt`\n * — the two-namespace split separates the integration id from the routed provider. Endpoints/clientId/scopes\n * are OpenAI's published OAuth values.\n */\nconst OPENAI_OAUTH_CONFIG: OAuthProviderConfig = {\n provider: \"openai\",\n authorizeEndpoint: \"https://auth.openai.com/oauth/authorize\",\n tokenEndpoint: \"https://auth.openai.com/oauth/token\",\n clientId: \"app_EMoamEEZ73f0CkXaXp7hrann\",\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n redirectUri: \"https://auth.openai.com/deviceauth/callback\",\n};\n\n/**\n * Build the per-request fetch: resolve a FRESH (refreshed) Bearer + the LIVE account-id from the ambient\n * store, and inject them as headers. Re-resolves on EVERY call → mid-turn refresh with no rebuild. A\n * `Headers` object is used so `authorization` is set case-insensitively (never doubled). If no credential is\n * logged in, throw a clear error rather than putting the router's `__oauth_lazy_token__` placeholder on the\n * wire (fail-closed — missing-credential semantics).\n */\nfunction codexFetch(): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n const env = process.env as Record<string, string | undefined>;\n const resolved = await resolveCredential({\n provider: \"openai\",\n store: DEFAULT_STORE,\n oauth: OPENAI_OAUTH_CONFIG,\n env,\n });\n if (resolved === undefined) {\n throw new Error(\n 'openai-chatgpt: no ChatGPT credential found — run the OpenAI device login (e.g. \"/login openai\") first.',\n );\n }\n const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;\n const headers = new Headers(init?.headers);\n headers.set(\"authorization\", `Bearer ${resolved.apiKey}`);\n if (accountId !== undefined) headers.set(\"ChatGPT-Account-Id\", accountId);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport const OPENAI_CHATGPT: ProviderProfile = {\n name: \"openai-chatgpt\",\n apiMode: \"responses_api\",\n authType: \"oauth_device_code\",\n baseUrl: \"https://chatgpt.com/backend-api/codex\",\n envVars: [],\n fallbackModels: [\n \"openai-chatgpt/gpt-5.4\",\n \"openai-chatgpt/gpt-5.4-mini\",\n \"openai-chatgpt/gpt-5.5\",\n ],\n // #165 — this shipped as `codex_cli_rs`, another vendor's client identifier. Claiming to be a different\n // vendor's client is a false statement of identity. Third-party clients send their OWN name against\n // this same endpoint, which also shows the route is not restricted to the official client.\n extraHeaders: { originator: \"theokit\" },\n // usetheokit/theokit-sdk#383 — carry the model's encrypted reasoning between the rounds of a turn.\n // On for THIS profile and no other because this is the endpoint the issue measured: OpenAI Codex\n // sends `include: [\"reasoning.encrypted_content\"]` with `reasoning.context: \"all_turns\"` to the\n // same backend, same model, on the same account, so acceptance is observed rather than assumed.\n // The issue's measurement — a third of our bytes, 2.8x our tokens — is what this closes together\n // with `prompt_cache_key`.\n encryptedReasoning: true,\n transform: {\n // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.\n fetch: () => codexFetch(),\n },\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENROUTER: ProviderProfile = {\n name: \"openrouter\",\n apiMode: \"chat_completions\",\n aliases: [\"or\"],\n // Ordered fallback (EC-10): OPENROUTER_API_KEY preferred, OPENAI_API_KEY as compat.\n envVars: [\"OPENROUTER_API_KEY\", \"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n modelsUrl: \"https://openrouter.ai/api/v1/models\",\n hostname: \"openrouter.ai\",\n // M45 — models refreshed (claude-3-haiku retired upstream).\n fallbackModels: [\"openai/gpt-4o-mini\", \"anthropic/claude-haiku-4-5\"],\n // M45 — OpenRouter app-attribution headers. VALUES are\n // theokit's own — copying another app's referer would misattribute traffic).\n extraHeaders: { \"HTTP-Referer\": \"https://usetheo.dev\", \"X-Title\": \"theokit\" },\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Perplexity. Its endpoint is UNVERSIONED (`/chat/completions`) — the explicit `chatCompletionsPath`\n * escape expresses it (the sonar-online model family was retired; models per models.dev `perplexity`).\n */\nexport const PERPLEXITY = openAiCompatibleProfile({\n name: \"perplexity\",\n baseUrl: \"https://api.perplexity.ai\",\n chatCompletionsPath: \"/chat/completions\",\n envVars: [\"PERPLEXITY_API_KEY\"],\n fallbackModels: [\"sonar-pro\", \"sonar\"],\n hostname: \"api.perplexity.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Together AI (models.dev id `togetherai` — kept as an alias). Values per the 2026-07 snapshot. */\nexport const TOGETHER = openAiCompatibleProfile({\n name: \"together\",\n aliases: [\"togetherai\"],\n baseUrl: \"https://api.together.xyz/v1\",\n envVars: [\"TOGETHER_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen2.5-7B-Instruct-Turbo\"],\n hostname: \"api.together.xyz\",\n});\n","/**\n * GCP Vertex AI profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Required peer dep: `google-auth-library` (D288). Resolves access tokens\n * via ADC (env → gcloud → metadata server → WIF).\n *\n * Model IDs follow the convention `vertex/{dialect}/{model}`:\n * - `vertex/google/gemini-2.0-flash-001` → OpenAI-compat endpoint (D291)\n * - `vertex/anthropic/claude-sonnet-4-5@20250929` → :rawPredict (D292)\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const VERTEX: ProviderProfile = {\n name: \"vertex\",\n apiMode: \"anthropic_messages\", // sub-dispatched in selectTransport by profile.name\n envVars: [\"GOOGLE_APPLICATION_CREDENTIALS\"],\n authType: \"gcp_oauth\",\n baseUrl: \"https://us-central1-aiplatform.googleapis.com\",\n modelsUrl: undefined,\n hostname: \"aiplatform.googleapis.com\",\n fallbackModels: [\n \"vertex/anthropic/claude-sonnet-4-5@20250929\",\n \"vertex/google/gemini-2.0-flash-001\",\n ],\n};\n\n/**\n * D293 absorbed: when location === \"global\", use `aiplatform.googleapis.com`\n * (no `global-` prefix) — known bug `streamRawPredict` 404 at\n * `global-aiplatform.googleapis.com` (a peer#10287).\n */\nexport function resolveVertexBaseUrl(opts: {\n projectId: string;\n location: string;\n modelDialect: \"anthropic\" | \"gemini\";\n}): string {\n const host =\n opts.location === \"global\"\n ? \"aiplatform.googleapis.com\"\n : `${opts.location}-aiplatform.googleapis.com`;\n if (opts.modelDialect === \"gemini\") {\n // OpenAI-compat endpoint (D291) — the client appends `/chat/completions`.\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/endpoints/openapi`;\n }\n // Anthropic — base URL up to `/publishers/anthropic` (model id appended by client).\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/publishers/anthropic`;\n}\n\n/** Detect dialect from a `vertex/{dialect}/{model}` id. Default: gemini. */\nexport function inferModelDialect(modelId: string): \"anthropic\" | \"gemini\" {\n if (modelId.includes(\"/anthropic/\")) return \"anthropic\";\n if (modelId.includes(\"/google/\")) return \"gemini\";\n return \"gemini\";\n}\n\n/** Strip the `vertex/{dialect}/` prefix so the raw model id is used in the URL. */\nexport function stripVertexPrefix(modelId: string): string {\n return modelId.replace(/^vertex\\/(anthropic|google)\\//, \"\");\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — xAI (Grok). Values per models.dev `xai` (2026-07 snapshot; grok-2 retired). */\nexport const XAI = openAiCompatibleProfile({\n name: \"xai\",\n aliases: [\"grok\"],\n baseUrl: \"https://api.x.ai/v1\",\n envVars: [\"XAI_API_KEY\"],\n fallbackModels: [\"grok-4.5\", \"grok-4.3\"],\n hostname: \"api.x.ai\",\n});\n","/**\n * Eager registration of builtin providers (T3.3). Side-effect import:\n * importing this module registers the 4 builtins with the registry.\n *\n * Lazy user-plugin discovery is handled by `discovery.ts` (T3.4).\n *\n * @internal\n */\n\nimport { registerCatalogProviders } from \"../catalog-loader.js\";\nimport { registerProvider } from \"../registry.js\";\nimport { ANTHROPIC } from \"./anthropic.js\";\nimport { BEDROCK } from \"./bedrock.js\";\nimport { CEREBRAS } from \"./cerebras.js\";\nimport { COHERE } from \"./cohere.js\";\nimport { DEEPINFRA } from \"./deepinfra.js\";\nimport { GEMINI } from \"./gemini.js\";\nimport { GOOGLE } from \"./google.js\";\nimport { GROQ } from \"./groq.js\";\nimport { LLAMACPP } from \"./llamacpp.js\";\nimport { LMSTUDIO } from \"./lmstudio.js\";\nimport { MISTRAL } from \"./mistral.js\";\nimport { OLLAMA } from \"./ollama.js\";\nimport { OPENAI } from \"./openai.js\";\nimport { OPENAI_CHATGPT } from \"./openai-chatgpt.js\";\nimport { OPENROUTER } from \"./openrouter.js\";\nimport { PERPLEXITY } from \"./perplexity.js\";\nimport { TOGETHER } from \"./together.js\";\nimport { VERTEX } from \"./vertex.js\";\nimport { XAI } from \"./xai.js\";\n\n// M45 review M2 — the guard lives on globalThis like the registry itself (M44 B1): a process importing both\n// bundle copies (`@theokit/sdk` + `@theokit/sdk/models`) must not re-register 19 builtins with bogus\n// \"overridden by user plugin\" WARNs.\nconst _registeredState = ((): { done: boolean } => {\n const g = globalThis as unknown as Record<symbol, { done: boolean }>;\n const sym = Symbol.for(\"theokit-sdk.providers.builtins-registered\");\n if (g[sym] === undefined) g[sym] = { done: false };\n return g[sym];\n})();\n\nexport function registerBuiltins(): void {\n if (_registeredState.done) return;\n _registeredState.done = true;\n // First-party builtins (take priority — registered first)\n registerProvider(ANTHROPIC);\n registerProvider(OPENAI);\n registerProvider(OPENAI_CHATGPT);\n registerProvider(OPENROUTER);\n registerProvider(GEMINI);\n registerProvider(OLLAMA);\n registerProvider(LMSTUDIO);\n registerProvider(LLAMACPP);\n registerProvider(BEDROCK);\n registerProvider(VERTEX);\n // M45 — the data-provider fleet (one file each on the openai-compatible base).\n registerProvider(GOOGLE);\n registerProvider(MISTRAL);\n registerProvider(GROQ);\n registerProvider(COHERE);\n registerProvider(DEEPINFRA);\n registerProvider(TOGETHER);\n registerProvider(XAI);\n registerProvider(PERPLEXITY);\n registerProvider(CEREBRAS);\n // Dynamic catalog — 40+ providers from JSON (T10.1, ADR D447)\n registerCatalogProviders();\n}\n\n/** Test-only reset. @internal */\nexport function _resetBuiltinsRegistered(): void {\n _registeredState.done = false;\n}\n\nexport {\n ANTHROPIC,\n BEDROCK,\n GEMINI,\n LLAMACPP,\n LMSTUDIO,\n OLLAMA,\n OPENAI,\n OPENAI_CHATGPT,\n OPENROUTER,\n VERTEX,\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/global-singleton.ts","../src/internal/providers/registry.ts","../src/internal/providers/catalog-schema.ts","../src/internal/providers/catalog-loader.ts","../src/internal/providers/builtin/anthropic.ts","../src/internal/providers/builtin/bedrock.ts","../src/internal/providers/builtin/openai-compatible.ts","../src/internal/providers/builtin/cerebras.ts","../src/internal/providers/builtin/cohere.ts","../src/internal/providers/builtin/deepinfra.ts","../src/internal/providers/builtin/gemini.ts","../src/internal/providers/builtin/google.ts","../src/internal/providers/builtin/groq.ts","../src/internal/providers/builtin/llamacpp.ts","../src/internal/providers/builtin/lmstudio.ts","../src/internal/providers/builtin/mistral.ts","../src/internal/providers/builtin/ollama.ts","../src/internal/providers/builtin/openai.ts","../src/internal/providers/builtin/openai-chatgpt.ts","../src/internal/providers/builtin/openrouter.ts","../src/internal/providers/builtin/perplexity.ts","../src/internal/providers/builtin/together.ts","../src/internal/providers/builtin/vertex.ts","../src/internal/providers/builtin/xai.ts","../src/internal/providers/builtin/index.ts"],"names":[],"mappings":";;;;;;;;;;AAYO,SAAS,eAAA,CAAmB,KAAa,MAAA,EAAoB;AAClE,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AAC1B,EAAA,IAAI,EAAE,GAAG,CAAA,KAAM,QAAW,CAAA,CAAE,GAAG,IAAI,MAAA,EAAO;AAC1C,EAAA,OAAO,EAAE,GAAG,CAAA;AACd;;;ACIA,IAAM,QAAA,GAAW,eAAA;AAAA,EACf,gCAAA;AAAA,EACA,0BAAU,GAAA;AACZ,CAAA;AACA,IAAM,UAAU,eA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AA,CAAiB,IAAA,GAAO,IAAA;AAExB,EAAA,gBAAA,CAAiB,SAAS,CAAA;AAC1B,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,cAAc,CAAA;AAC/B,EAAA,gBAAA,CAAiB,UAAU,CAAA;AAC3B,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AAEvB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,EAAA,gBAAA,CAAiB,IAAI,CAAA;AACrB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,SAAS,CAAA;AAC1B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,GAAG,CAAA;AACpB,EAAA,gBAAA,CAAiB,UAAU,CAAA;AAC3B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AAEzB,EAAA,wBAAA,EAAyB;AAC3B","file":"chunk-WLQNMXQE.js","sourcesContent":["/**\n * One singleton per realm, keyed by `Symbol.for`.\n *\n * It exists because a package can be loaded more than once in the same process (two copies in\n * `node_modules`, ESM and CJS side by side, a monorepo with distinct versions) — and then a module-level\n * `const x = new Map()` produces TWO caches that cannot see each other. `Symbol.for` uses the global\n * symbol registry, which belongs to the realm and not the module, so every copy converges on one instance.\n *\n * It was copied verbatim into `providers/discovery.ts` and `providers/catalog-loader.ts`. That is\n * duplicated KNOWLEDGE, not a coincidence of shape: the two copies have to agree on the\n * mechanism, and one fixed without the other produces exactly the bug the function exists to avoid.\n */\nexport function globalSingleton<T>(key: string, create: () => T): T {\n const g = globalThis as unknown as Record<symbol, T>;\n const sym = Symbol.for(key);\n if (g[sym] === undefined) g[sym] = create();\n return g[sym];\n}\n","/**\n * Provider registry (T3.2, ADR D107).\n *\n * `registerProvider` is idempotent and surface-warning: re-registering\n * a `name` logs to stderr (D107 last-writer-wins with WARN). Alias\n * collisions also warn (EC-5).\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport type { ProviderProfile } from \"./types.js\";\n\n/**\n * M44 B1 fix — the registry state lives on `globalThis` keyed by `Symbol.for`, so EVERY bundle copy of this\n * module (tsup bundles each entry separately with `splitting: false` — `dist/index.js` and `dist/models.js`\n * each embed their own copy) shares the SAME maps. Without this, `@theokit/sdk/models`'s\n * `refreshModelCatalog` saw an eternally-empty registry and its patches were invisible to the core bundle's\n * capability/pricing lookups (state duplication made load-bearing by M44).\n */\nconst REGISTRY = globalSingleton(\n \"theokit-sdk.providers.registry\",\n () => new Map<string, ProviderProfile>(),\n);\nconst ALIASES = globalSingleton(\"theokit-sdk.providers.aliases\", () => new Map<string, string>());\n\nexport function registerProvider(profile: ProviderProfile): void {\n if (REGISTRY.has(profile.name)) {\n diag(`[theokit-sdk] Provider \"${profile.name}\" overridden by user plugin.\\n`);\n }\n REGISTRY.set(profile.name, profile);\n for (const alias of profile.aliases ?? []) {\n // EC-5: surface alias collision so operators notice mis-routing.\n const previous = ALIASES.get(alias);\n if (previous !== undefined && previous !== profile.name) {\n diag(`[theokit-sdk] Alias \"${alias}\" collision: was \"${previous}\", now \"${profile.name}\".\\n`);\n }\n ALIASES.set(alias, profile.name);\n }\n}\n\nexport function getProviderProfile(name: string): ProviderProfile | undefined {\n const canonical = ALIASES.get(name) ?? name;\n return REGISTRY.get(canonical);\n}\n\nexport function listProviders(): ProviderProfile[] {\n return Array.from(REGISTRY.values());\n}\n\n/** Test-only reset. @internal */\nexport function _resetProvidersForTests(): void {\n REGISTRY.clear();\n ALIASES.clear();\n}\n","import { z } from \"zod\";\n\n/**\n * M44 — the per-model catalog sub-schema. Field names mirror models.dev VERBATIM (snake_case) so\n * `scripts/refresh-catalog.mjs` regenerates the vendored data mechanically from `api.json` with zero\n * renaming (ADR D1).\n * TOLERANT by design: every field optional, unknown keys ignored — models.dev adds fields over time and\n * additive drift must never break the loader (Blueprint §6.4).\n *\n * theokit extensions beyond models.dev: `structured_output` / `cache_control` (both already exist on the\n * SDK's `ModelCapabilities`; models.dev has no such flags).\n *\n * Semver-exempt: nothing here is declared in `package.json` `exports`. `MODALITIES` is nonetheless\n * reachable from published declarations through the type graph, so it must be EMITTED.\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows; the tag that\n * used to sit here deleted the `MODALITIES` declaration below from the emitted `.d.ts`.\n */\n\nexport const MODALITIES = [\"text\", \"audio\", \"image\", \"video\", \"pdf\"] as const;\n\n/**\n * One input or output medium a model accepts or produces.\n *\n * The union is derived from `MODALITIES`, so it is closed: a models.dev entry whose\n * `modalities.input` or `modalities.output` array contains a string outside this set fails\n * `catalogModelSchema.safeParse`, and `patchIndexFromApiJson` drops that single model rather\n * than the whole payload. Widening the catalog to a new medium means adding it to `MODALITIES`\n * first — nothing else in the schema enumerates media.\n */\nexport type Modality = (typeof MODALITIES)[number];\n\nconst costSchema = z\n .object({\n /** USD per 1M tokens (models.dev convention). */\n input: z.number().nonnegative(),\n output: z.number().nonnegative(),\n cache_read: z.number().nonnegative().optional(),\n cache_write: z.number().nonnegative().optional(),\n })\n .loose();\n\nconst limitSchema = z\n .object({\n context: z.number().positive(),\n input: z.number().positive().optional(),\n output: z.number().positive().optional(),\n })\n .loose();\n\nconst modalitiesSchema = z\n .object({\n input: z.array(z.enum(MODALITIES)).optional(),\n output: z.array(z.enum(MODALITIES)).optional(),\n })\n .loose();\n\nexport const catalogModelSchema = z\n .object({\n name: z.string().optional(),\n release_date: z.string().optional(),\n attachment: z.boolean().optional(),\n reasoning: z.boolean().optional(),\n temperature: z.boolean().optional(),\n tool_call: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsStructuredOutput. */\n structured_output: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsCacheControl. */\n cache_control: z.boolean().optional(),\n cost: costSchema.optional(),\n limit: limitSchema.optional(),\n modalities: modalitiesSchema.optional(),\n status: z.enum([\"alpha\", \"beta\", \"deprecated\"]).optional(),\n })\n .loose();\n\n/**\n * One model entry as it is stored in the vendored catalog and as models.dev publishes it.\n *\n * Every field is optional, so an entry that carries only `name` still parses. Reading a value\n * therefore means handling `undefined` at each level — `model.cost?.cache_read`, not\n * `model.cost.cache_read`. Field names are models.dev's own snake_case, kept verbatim so the\n * refresh script can copy `api.json` across without renaming.\n *\n * The schema is loose rather than strict: unknown keys survive parsing and stay on the returned\n * object instead of being rejected or dropped. That is what lets models.dev add a field without\n * breaking the loader — the cost is that a typo in a key name parses silently, so a caller\n * cannot use \"it parsed\" as evidence that a field it expected was present.\n *\n * `structured_output` and `cache_control` are theokit's own additions; models.dev publishes\n * neither.\n */\nexport type CatalogModel = z.infer<typeof catalogModelSchema>;\n\n/**\n * Per-token pricing for one model, in USD per 1M tokens (models.dev's unit — not per token, and\n * not per 1K).\n *\n * `input` and `output` are required and non-negative; the two cache buckets are optional and\n * absent for models that do not price caching separately. Absent is not zero: a missing\n * `cache_read` means the catalog says nothing about the cost of a cache hit, so a caller that\n * defaults it to 0 is asserting free cache reads on its own authority.\n *\n * Like `CatalogModel`, the shape is loose — unknown pricing keys published upstream are kept on\n * the parsed value.\n */\nexport type CatalogModelCost = z.infer<typeof costSchema>;\n","/**\n * Dynamic provider catalog loader (T10.1, ADR D447).\n *\n * Loads provider metadata from `provider-catalog.json` at runtime.\n * Malformed entries are skipped with WARN (EC-1) — never crash.\n *\n * @internal\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { diag } from \"../diagnostics.js\";\nimport { globalSingleton } from \"../global-singleton.js\";\nimport { type CatalogModel, catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile, registerProvider } from \"./registry.js\";\nimport type { ApiMode, AuthType, ProviderProfile } from \"./types.js\";\n\nconst __dirname_resolved = dirname(fileURLToPath(import.meta.url));\n\nexport interface ProviderCapabilities {\n supportsToolUse: boolean;\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsStreaming: boolean;\n supportsCacheControl: boolean;\n maxContextTokens?: number;\n maxOutputTokens?: number;\n}\n\nexport interface CatalogEntry {\n id: string;\n displayName: string;\n apiMode: ApiMode;\n authType: AuthType;\n baseUrl: string;\n envVars: string[];\n fallbackModels: string[];\n capabilities: ProviderCapabilities;\n aliases?: string[];\n modelsUrl?: string;\n hostname?: string;\n extraHeaders?: Record<string, string>;\n /**\n * M44 — OPTIONAL per-model data (models.dev shape, snake_case — see `catalog-schema.ts`), keyed by the\n * BARE model id. Additive: entries without it behave byte-identically to before. The loader indexes this\n * into the model-info index (`getCatalogModelInfo`) rather than onto `ProviderProfile` (ADR D2 — the\n * builtins-first registration skip means profile-attached data would never reach builtin providers).\n */\n models?: Record<string, CatalogModel>;\n}\n\n/**\n * M44 — the model-info index: `provider/model` → per-model catalog data (the EXACT-map key convention).\n * Populated by the vendored catalog load AND patched by the optional models-dev source (cache entries win\n * per model). The single lookup surface for capability / cost / limit enrichment.\n */\n// M44 B1 fix — index state on globalThis (Symbol.for) so every bundle copy shares the SAME maps (see the\n// identical pattern + rationale in registry.ts).\nconst modelInfoIndex = globalSingleton(\n \"theokit-sdk.providers.model-info-index\",\n () => new Map<string, CatalogModel>(),\n);\n/** M44 M5 fix — keys patched by the live models-dev source (honest pricing provenance). */\nconst patchedModelKeys = globalSingleton(\n \"theokit-sdk.providers.model-info-patched\",\n () => new Set<string>(),\n);\nconst indexState = globalSingleton(\"theokit-sdk.providers.model-info-loaded\", () => ({\n loaded: false,\n}));\n\n/**\n * Look up per-model catalog data by `provider/model` key.\n *\n * Semver-exempt: not declared in `package.json` `exports`, but re-exported by\n * `catalog-source-models-dev.ts`, whose declaration is reachable from published entries — so it\n * must be EMITTED.\n */\nexport function getCatalogModelInfo(key: string): CatalogModel | undefined {\n ensureModelIndexLoaded();\n return modelInfoIndex.get(key);\n}\n\n/** Was this key patched by the LIVE models-dev source (vs the vendored catalog)? @internal */\nexport function isPatchedModelKey(key: string): boolean {\n return patchedModelKeys.has(key);\n}\n\n/**\n * Patch the index with fresher per-model data (the models-dev source). M44 H2 fix — a per-FIELD shallow\n * MERGE, not a wholesale replace: models.dev can never supply the theokit extension fields\n * (`cache_control`, `structured_output` overlays), so a replace would wipe them and silently flip\n * capability answers. Incoming fields win; existing fields survive when the patch omits them.\n * @internal\n */\nexport function patchModelInfo(key: string, model: CatalogModel): void {\n ensureModelIndexLoaded();\n const existing = modelInfoIndex.get(key);\n modelInfoIndex.set(key, existing === undefined ? model : { ...existing, ...model });\n patchedModelKeys.add(key);\n}\n\n/** All indexed `provider/model` keys (for maintenance/tests). @internal */\nexport function listModelInfoKeys(): string[] {\n ensureModelIndexLoaded();\n return [...modelInfoIndex.keys()];\n}\n\nfunction ensureModelIndexLoaded(): void {\n if (indexState.loaded) return;\n indexState.loaded = true;\n // M44 L9 fix — never throw from a capability/pricing lookup: a missing/corrupt vendored catalog degrades\n // to conservative defaults with a WARN (the deleted EXACT map could never throw; keep that property).\n try {\n const catalog = loadProviderCatalog();\n for (const entry of Object.values(catalog)) {\n indexEntryModels(entry);\n }\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: provider catalog unavailable (${(err as Error).message}) — per-model data disabled\\n`,\n );\n }\n}\n\n/**\n * Index an entry's `models` block. Runs for EVERY catalog entry — including those whose PROVIDER\n * registration is skipped builtins-first — so builtin providers still get their per-model data (ADR D2).\n * A malformed model sub-entry drops THAT MODEL with WARN and keeps the provider (EC-1 philosophy extended).\n */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction indexEntryModels(entry: CatalogEntry): void {\n if (entry.models === undefined || typeof entry.models !== \"object\") return;\n for (const [modelId, raw] of Object.entries(entry.models)) {\n const parsed = catalogModelSchema.safeParse(raw);\n if (!parsed.success) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog model \"${entry.id}/${modelId}\": ` +\n `${parsed.error.issues[0]?.message ?? \"invalid\"}\\n`,\n );\n continue;\n }\n // Index under the entry id AND every alias — capability lookups are VENDOR-keyed (e.g.\n // `google/gemini-2.5-pro` while the entry id is `google-gemini` with alias `google`), so alias keys are\n // what make the vendor-keyed convention resolve without a second mapping table.\n modelInfoIndex.set(`${entry.id}/${modelId}`, parsed.data);\n for (const alias of entry.aliases ?? []) {\n const key = `${alias}/${modelId}`;\n if (!modelInfoIndex.has(key)) modelInfoIndex.set(key, parsed.data);\n }\n }\n}\n\n/** Test-only reset for the model-info index. @internal */\nexport function _resetModelInfoIndexForTests(): void {\n modelInfoIndex.clear();\n patchedModelKeys.clear();\n indexState.loaded = false;\n}\n\ninterface LoadOptions {\n _testInjectMalformed?: boolean;\n}\n\nfunction validateEntry(raw: Record<string, unknown>): CatalogEntry | null {\n if (\n typeof raw.id !== \"string\" ||\n typeof raw.displayName !== \"string\" ||\n typeof raw.apiMode !== \"string\" ||\n typeof raw.authType !== \"string\" ||\n typeof raw.baseUrl !== \"string\" ||\n !Array.isArray(raw.envVars) ||\n !Array.isArray(raw.fallbackModels) ||\n raw.capabilities == null ||\n typeof raw.capabilities !== \"object\"\n ) {\n return null;\n }\n return raw as unknown as CatalogEntry;\n}\n\nexport function loadProviderCatalog(opts?: LoadOptions): Record<string, CatalogEntry> {\n const catalogPath = join(__dirname_resolved, \"provider-catalog.json\");\n const rawText = readFileSync(catalogPath, \"utf-8\");\n let entries: Record<string, unknown>[] = JSON.parse(rawText);\n\n if (opts?._testInjectMalformed) {\n entries = [\n ...entries,\n { id: \"malformed-provider\", displayName: \"Bad\" } as Record<string, unknown>,\n ];\n }\n\n const result: Record<string, CatalogEntry> = {};\n for (const raw of entries) {\n const validated = validateEntry(raw as Record<string, unknown>);\n if (validated === null) {\n diag(\n `[theokit-sdk] WARN: Skipping malformed catalog entry: ${JSON.stringify(raw).slice(0, 100)}\\n`,\n );\n continue;\n }\n result[validated.id] = validated;\n }\n return result;\n}\n\nlet _capabilitiesCache: Record<string, ProviderCapabilities> | null = null;\n\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nexport function getCatalogCapabilities(providerId: string): ProviderCapabilities | undefined {\n if (_capabilitiesCache === null) {\n const catalog = loadProviderCatalog();\n _capabilitiesCache = {};\n for (const entry of Object.values(catalog)) {\n _capabilitiesCache[entry.id] = entry.capabilities;\n // M45 review L4 — alias keys too (e.g. entry `google-gemini` alias `google`), consistent with the\n // model-info index's alias-keyed convention.\n for (const alias of entry.aliases ?? []) {\n if (_capabilitiesCache[alias] === undefined) _capabilitiesCache[alias] = entry.capabilities;\n }\n }\n }\n return _capabilitiesCache[providerId];\n}\n\nexport function registerCatalogProviders(opts?: LoadOptions): void {\n const catalog = loadProviderCatalog(opts);\n for (const entry of Object.values(catalog)) {\n // Skip catalog entries that would overwrite first-party builtins.\n // Builtins have richer env-var handling and are registered first.\n // Also skip if any alias collides with an existing provider name.\n if (getProviderProfile(entry.id) !== undefined) continue;\n if (entry.aliases?.some((a) => getProviderProfile(a) !== undefined)) continue;\n\n const profile: ProviderProfile = {\n name: entry.id,\n apiMode: entry.apiMode,\n authType: entry.authType,\n baseUrl: entry.baseUrl,\n envVars: entry.envVars,\n fallbackModels: entry.fallbackModels,\n displayName: entry.displayName,\n aliases: entry.aliases,\n modelsUrl: entry.modelsUrl,\n hostname: entry.hostname,\n extraHeaders: entry.extraHeaders,\n };\n registerProvider(profile);\n }\n}\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const ANTHROPIC: ProviderProfile = {\n name: \"anthropic\",\n apiMode: \"anthropic_messages\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.anthropic.com\",\n modelsUrl: \"https://api.anthropic.com/v1/models\",\n hostname: \"api.anthropic.com\",\n fallbackModels: [\"claude-opus-4-7\", \"claude-sonnet-4-6\", \"claude-haiku-4-5-20251001\"],\n // M45 — the Anthropic beta-features header (interleaved thinking + fine-grained tool streaming). An\n // Anthropic API constant. The\n // SANCTIONED behavior delta of M45 (ADR D4) — consumed by the anthropic transport's extraHeaders wiring.\n extraHeaders: {\n \"anthropic-beta\": \"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\",\n },\n};\n","/**\n * AWS Bedrock profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Bearer-only auth via `AWS_BEARER_TOKEN_BEDROCK` env (GA Sep 2025).\n * Optional `@aws/bedrock-token-generator` peer dep auto-refreshes short-term\n * tokens (D287). Transport via native `fetch`; no `@aws-sdk/*` dependency.\n *\n * Model IDs follow the `bedrock/{aws-id}` convention so the router can\n * infer the provider via prefix routing (D186). The client strips the\n * `bedrock/` prefix before building the URL.\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const BEDROCK: ProviderProfile = {\n name: \"bedrock\",\n apiMode: \"bedrock_anthropic\",\n envVars: [\"AWS_BEARER_TOKEN_BEDROCK\"],\n authType: \"aws_bearer\",\n baseUrl: \"https://bedrock-runtime.us-east-1.amazonaws.com\",\n modelsUrl: undefined,\n hostname: \"bedrock-runtime.amazonaws.com\",\n fallbackModels: [\n \"bedrock/us.anthropic.claude-sonnet-4-5-v1:0\",\n \"bedrock/us.anthropic.claude-opus-4-7-v1:0\",\n \"bedrock/global.anthropic.claude-haiku-4-5-v1:0\",\n ],\n};\n\n/** Strip `\"bedrock/\"` prefix so the raw AWS model id is used in the URL. */\nexport function stripBedrockPrefix(modelId: string): string {\n return modelId.replace(/^bedrock\\//, \"\");\n}\n\n/**\n * Infer AWS region from a Bedrock model id prefix (D290).\n *\n * `global.*` routes via `us-east-1` (AWS default entrypoint for global\n * inference profiles).\n */\nexport function inferRegionFromModelId(modelId: string): string | undefined {\n const id = stripBedrockPrefix(modelId);\n if (id.startsWith(\"global.\")) return \"us-east-1\";\n if (id.startsWith(\"us.\")) return process.env.AWS_REGION ?? \"us-east-1\";\n if (id.startsWith(\"eu.\")) return process.env.AWS_REGION ?? \"eu-west-1\";\n if (id.startsWith(\"apac.\")) return process.env.AWS_REGION ?? \"ap-southeast-1\";\n if (id.startsWith(\"jp.\")) return \"ap-northeast-1\";\n return undefined;\n}\n\n/** Resolve baseUrl from model id; falls back to `AWS_REGION` env or `us-east-1`. */\nexport function resolveBedrockBaseUrl(modelId: string): string {\n const region = inferRegionFromModelId(modelId) ?? process.env.AWS_REGION ?? \"us-east-1\";\n return `https://bedrock-runtime.${region}.amazonaws.com`;\n}\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * M45 — the data-only base for OpenAI-compatible chat_completions providers. A profile-map pattern\n * flattened to\n * theokit's data model: leaves declare name/baseUrl/envVars (+ overrides) in ~10 lines; the router's\n * URL-join rule (version-segment detection + `chatCompletionsPath` escape) derives the endpoint.\n *\n * @internal\n */\nexport function openAiCompatibleProfile(\n p: { name: string; baseUrl: string; envVars: readonly string[] } & Partial<ProviderProfile>,\n): ProviderProfile {\n return {\n apiMode: \"chat_completions\",\n authType: \"api_key\",\n fallbackModels: [],\n ...p,\n };\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cerebras. The integration header value is theokit's own: the header attributes TRAFFIC.\n * Models per models.dev (2026-07 snapshot).\n */\nexport const CEREBRAS = openAiCompatibleProfile({\n name: \"cerebras\",\n baseUrl: \"https://api.cerebras.ai/v1\",\n envVars: [\"CEREBRAS_API_KEY\"],\n fallbackModels: [\"gpt-oss-120b\", \"zai-glm-4.7\"],\n extraHeaders: { \"X-Cerebras-3rd-Party-Integration\": \"theokit\" },\n hostname: \"api.cerebras.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cohere via its OpenAI-compatibility surface (`api.cohere.ai/compatibility/v1` — the native v2 API\n * is NOT chat_completions; the discovery flagged the old catalog baseUrl as doubly wrong). Models per\n * models.dev `cohere` (2026-07 snapshot). SOURCE NOTE (review L2): the compatibility endpoint + `CO_API_KEY`\n * come from Cohere's own docs/python-SDK convention (not vendored in this repo's references) — verify with a\n * live smoke when a key is available.\n */\nexport const COHERE = openAiCompatibleProfile({\n name: \"cohere\",\n baseUrl: \"https://api.cohere.ai/compatibility/v1\",\n envVars: [\"COHERE_API_KEY\", \"CO_API_KEY\"],\n fallbackModels: [\"command-a-03-2025\"],\n hostname: \"api.cohere.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — DeepInfra. OpenAI-compat surface under /v1/openai (models.dev `deepinfra`). */\nexport const DEEPINFRA = openAiCompatibleProfile({\n name: \"deepinfra\",\n baseUrl: \"https://api.deepinfra.com/v1/openai\",\n envVars: [\"DEEPINFRA_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen3-32B\"],\n hostname: \"api.deepinfra.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Gemini via OpenRouter passthrough. Direct Gemini API uses a different\n * dialect (`generateContent`); SDK currently routes through OpenRouter's\n * OpenAI-compatible endpoint so the chat_completions transport works.\n *\n * A future plugin `@theokit-provider-gemini-direct` can override this with\n * `apiMode: \"gemini_generate_content\"` once that transport ships.\n */\nexport const GEMINI: ProviderProfile = {\n name: \"gemini\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENROUTER_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n hostname: \"openrouter.ai\",\n fallbackModels: [\"google/gemini-2.0-flash-001\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Google Gemini via the DIRECT OpenAI-compat endpoint (a Google API key, not OpenRouter). Distinct\n * from the `gemini` builtin (an OpenRouter passthrough) by ADR D3 — two routes, two names. Endpoint + env\n * vars per Google's OpenAI-compatibility docs (mirrored by models.dev `google` + the M44 catalog entry).\n */\nexport const GOOGLE = openAiCompatibleProfile({\n name: \"google\",\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta/openai\",\n envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n fallbackModels: [\"gemini-2.5-pro\", \"gemini-2.5-flash\"],\n hostname: \"generativelanguage.googleapis.com\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Groq. Values per models.dev `groq` (2026-07 snapshot); OpenAI-compat surface under /openai/v1. */\nexport const GROQ = openAiCompatibleProfile({\n name: \"groq\",\n baseUrl: \"https://api.groq.com/openai/v1\",\n envVars: [\"GROQ_API_KEY\"],\n fallbackModels: [\"llama-3.3-70b-versatile\", \"llama-3.1-8b-instant\"],\n hostname: \"api.groq.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * llama.cpp server provider profile (T7.2, ADR D189).\n *\n * llama.cpp ships a HTTP server binary (`./server` since b1500+) that\n * implements the OpenAI-compatible `/v1/chat/completions` endpoint on\n * `http://localhost:8080` by default. Inherits `authType: \"none\"` from\n * D182 — no API key required for local use.\n *\n * llama.cpp idiosyncrasies:\n * - Server loads a single GGUF model at startup via `--model` CLI\n * flag. The `model` field in the chat-completions request is\n * cosmetic — any string works; the response comes from the loaded\n * model regardless. This is documented in\n * `.claude/knowledge-base/reviews/edge-case/ollama-integration-edge-cases-2026-05-21.md`\n * as EC-O.\n * - Tool calling support depends entirely on the underlying model.\n *\n * Override the default URL with `LLAMACPP_HOST`.\n *\n * @internal\n */\nexport const LLAMACPP: ProviderProfile = {\n name: \"llamacpp\",\n aliases: [\"llama-cpp\", \"llama.cpp\"],\n apiMode: \"chat_completions\",\n envVars: [\"LLAMACPP_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:8080\",\n modelsUrl: \"http://localhost:8080/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * LM Studio provider profile (T7.1, ADR D188).\n *\n * LM Studio exposes an OpenAI-compatible `/v1/chat/completions` endpoint\n * on `http://localhost:1234` by default (configurable via the LM Studio\n * UI under \"Local Server\"). Inherits the `authType: \"none\"` primitive\n * from D182 — no API key required for local use.\n *\n * LM Studio idiosyncrasies:\n * - Loads ONE model at a time via the desktop UI. The `model` field in\n * the chat-completions request is informational only — LM Studio\n * serves whatever model is currently loaded.\n * - `/v1/models` returns a single entry pointing to the loaded model.\n * - Tool calling depends on the underlying model.\n *\n * Override the default URL with `LMSTUDIO_HOST` (mirrors `OLLAMA_HOST`).\n *\n * @internal\n */\nexport const LMSTUDIO: ProviderProfile = {\n name: \"lmstudio\",\n aliases: [\"lm-studio\", \"lm_studio\"],\n apiMode: \"chat_completions\",\n envVars: [\"LMSTUDIO_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:1234\",\n modelsUrl: \"http://localhost:1234/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Mistral (La Plateforme). Values per models.dev `mistral` (2026-07 snapshot). */\nexport const MISTRAL = openAiCompatibleProfile({\n name: \"mistral\",\n baseUrl: \"https://api.mistral.ai/v1\",\n envVars: [\"MISTRAL_API_KEY\"],\n fallbackModels: [\"mistral-large-latest\", \"codestral-latest\"],\n hostname: \"api.mistral.ai\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Ollama — local-first LLM runtime (ADR D182).\n *\n * Ships as a builtin so `Agent.create({ model: \"ollama/llama3.2\" })` works\n * with zero configuration when `ollama serve` is running on the default\n * port. `authType: \"none\"` signals the router to skip env-key resolution\n * and use a placeholder credential (Ollama ignores Authorization headers\n * on local installs).\n *\n * Overrides:\n * - `OLLAMA_HOST` — replaces the default `http://localhost:11434` baseUrl\n * (advanced users running Ollama on a remote machine).\n * - `OLLAMA_API_KEY` — replaces the placeholder when Ollama is behind a\n * reverse-proxy with auth or when using Ollama Cloud (paid tier).\n */\nexport const OLLAMA: ProviderProfile = {\n name: \"ollama\",\n apiMode: \"chat_completions\",\n envVars: [\"OLLAMA_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:11434\",\n modelsUrl: \"http://localhost:11434/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"llama3.2\", \"qwen2.5\", \"mistral\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENAI: ProviderProfile = {\n name: \"openai\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.openai.com\",\n modelsUrl: \"https://api.openai.com/v1/models\",\n hostname: \"api.openai.com\",\n fallbackModels: [\"gpt-4o\", \"gpt-4o-mini\"],\n};\n","/**\n * M43 — the ChatGPT \"Codex\" backend as a first-class builtin `ProviderProfile`. Migrated from the\n * agent-builder M40 workaround; the SDK now owns the provider, so a consumer only selects\n * `openai-chatgpt/<model>` and logs in — ZERO provider logic in the consumer.\n *\n * The provider-auth model (see the codex-provider-in-sdk blueprint):\n * - static profile + a `transform.fetch` that resolves the LIVE credential per HTTP request (fresh Bearer +\n * dynamic `ChatGPT-Account-Id`), so a mid-turn expiry refreshes transparently with NO agent rebuild;\n * - the protocol values (endpoint, models, oauth config, `originator` header) are SDK-owned constants.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\n\nimport type { CredentialStoreConfig, OAuthProviderConfig } from \"../../auth/auth-types.js\";\nimport { readStoredOAuth } from \"../../auth/credential-store.js\";\nimport { resolveCredential } from \"../../auth/resolve-credential.js\";\nimport type { ProviderProfile } from \"../types.js\";\n\n/**\n * The SDK-owned ambient credential store the transform reads. Defaults to `~/.theokit/auth.json`. A consumer\n * points it at its existing store dir via the DEDICATED `THEOKIT_AUTH_HOME` env var (NOT `THEOKIT_HOME` — that\n * is the SDK's whole home directory for personality/credential-pool/profiles; overloading it would redirect\n * the entire runtime). The SDK's ambient credential service.\n */\nconst DEFAULT_STORE: CredentialStoreConfig = {\n home: homedir(),\n dirName: \".theokit\",\n fileName: \"auth.json\",\n homeEnvVar: \"THEOKIT_AUTH_HOME\",\n};\n\n/**\n * The OpenAI OAuth config the transform resolves + refreshes against. `provider: \"openai\"` is the STORE\n * provider (what `/login` persists), deliberately distinct from this profile's routing name `openai-chatgpt`\n * — the two-namespace split separates the integration id from the routed provider. Endpoints/clientId/scopes\n * are OpenAI's published OAuth values.\n */\nconst OPENAI_OAUTH_CONFIG: OAuthProviderConfig = {\n provider: \"openai\",\n authorizeEndpoint: \"https://auth.openai.com/oauth/authorize\",\n tokenEndpoint: \"https://auth.openai.com/oauth/token\",\n clientId: \"app_EMoamEEZ73f0CkXaXp7hrann\",\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n redirectUri: \"https://auth.openai.com/deviceauth/callback\",\n};\n\n/**\n * Build the per-request fetch: resolve a FRESH (refreshed) Bearer + the LIVE account-id from the ambient\n * store, and inject them as headers. Re-resolves on EVERY call → mid-turn refresh with no rebuild. A\n * `Headers` object is used so `authorization` is set case-insensitively (never doubled). If no credential is\n * logged in, throw a clear error rather than putting the router's `__oauth_lazy_token__` placeholder on the\n * wire (fail-closed — missing-credential semantics).\n */\nfunction codexFetch(): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n const env = process.env as Record<string, string | undefined>;\n const resolved = await resolveCredential({\n provider: \"openai\",\n store: DEFAULT_STORE,\n oauth: OPENAI_OAUTH_CONFIG,\n env,\n });\n if (resolved === undefined) {\n throw new Error(\n 'openai-chatgpt: no ChatGPT credential found — run the OpenAI device login (e.g. \"/login openai\") first.',\n );\n }\n const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;\n const headers = new Headers(init?.headers);\n headers.set(\"authorization\", `Bearer ${resolved.apiKey}`);\n if (accountId !== undefined) headers.set(\"ChatGPT-Account-Id\", accountId);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport const OPENAI_CHATGPT: ProviderProfile = {\n name: \"openai-chatgpt\",\n apiMode: \"responses_api\",\n authType: \"oauth_device_code\",\n baseUrl: \"https://chatgpt.com/backend-api/codex\",\n envVars: [],\n fallbackModels: [\n \"openai-chatgpt/gpt-5.4\",\n \"openai-chatgpt/gpt-5.4-mini\",\n \"openai-chatgpt/gpt-5.5\",\n ],\n // #165 — this shipped as `codex_cli_rs`, another vendor's client identifier. Claiming to be a different\n // vendor's client is a false statement of identity. Third-party clients send their OWN name against\n // this same endpoint, which also shows the route is not restricted to the official client.\n extraHeaders: { originator: \"theokit\" },\n // usetheokit/theokit-sdk#383 — carry the model's encrypted reasoning between the rounds of a turn.\n // On for THIS profile and no other because this is the endpoint the issue measured: OpenAI Codex\n // sends `include: [\"reasoning.encrypted_content\"]` with `reasoning.context: \"all_turns\"` to the\n // same backend, same model, on the same account, so acceptance is observed rather than assumed.\n // The issue's measurement — a third of our bytes, 2.8x our tokens — is what this closes together\n // with `prompt_cache_key`.\n encryptedReasoning: true,\n transform: {\n // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.\n fetch: () => codexFetch(),\n },\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENROUTER: ProviderProfile = {\n name: \"openrouter\",\n apiMode: \"chat_completions\",\n aliases: [\"or\"],\n // Ordered fallback (EC-10): OPENROUTER_API_KEY preferred, OPENAI_API_KEY as compat.\n envVars: [\"OPENROUTER_API_KEY\", \"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n modelsUrl: \"https://openrouter.ai/api/v1/models\",\n hostname: \"openrouter.ai\",\n // M45 — models refreshed (claude-3-haiku retired upstream).\n fallbackModels: [\"openai/gpt-4o-mini\", \"anthropic/claude-haiku-4-5\"],\n // M45 — OpenRouter app-attribution headers. VALUES are\n // theokit's own — copying another app's referer would misattribute traffic).\n extraHeaders: { \"HTTP-Referer\": \"https://usetheo.dev\", \"X-Title\": \"theokit\" },\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Perplexity. Its endpoint is UNVERSIONED (`/chat/completions`) — the explicit `chatCompletionsPath`\n * escape expresses it (the sonar-online model family was retired; models per models.dev `perplexity`).\n */\nexport const PERPLEXITY = openAiCompatibleProfile({\n name: \"perplexity\",\n baseUrl: \"https://api.perplexity.ai\",\n chatCompletionsPath: \"/chat/completions\",\n envVars: [\"PERPLEXITY_API_KEY\"],\n fallbackModels: [\"sonar-pro\", \"sonar\"],\n hostname: \"api.perplexity.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Together AI (models.dev id `togetherai` — kept as an alias). Values per the 2026-07 snapshot. */\nexport const TOGETHER = openAiCompatibleProfile({\n name: \"together\",\n aliases: [\"togetherai\"],\n baseUrl: \"https://api.together.xyz/v1\",\n envVars: [\"TOGETHER_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen2.5-7B-Instruct-Turbo\"],\n hostname: \"api.together.xyz\",\n});\n","/**\n * GCP Vertex AI profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Required peer dep: `google-auth-library` (D288). Resolves access tokens\n * via ADC (env → gcloud → metadata server → WIF).\n *\n * Model IDs follow the convention `vertex/{dialect}/{model}`:\n * - `vertex/google/gemini-2.0-flash-001` → OpenAI-compat endpoint (D291)\n * - `vertex/anthropic/claude-sonnet-4-5@20250929` → :rawPredict (D292)\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const VERTEX: ProviderProfile = {\n name: \"vertex\",\n apiMode: \"anthropic_messages\", // sub-dispatched in selectTransport by profile.name\n envVars: [\"GOOGLE_APPLICATION_CREDENTIALS\"],\n authType: \"gcp_oauth\",\n baseUrl: \"https://us-central1-aiplatform.googleapis.com\",\n modelsUrl: undefined,\n hostname: \"aiplatform.googleapis.com\",\n fallbackModels: [\n \"vertex/anthropic/claude-sonnet-4-5@20250929\",\n \"vertex/google/gemini-2.0-flash-001\",\n ],\n};\n\n/**\n * D293 absorbed: when location === \"global\", use `aiplatform.googleapis.com`\n * (no `global-` prefix) — known bug `streamRawPredict` 404 at\n * `global-aiplatform.googleapis.com` (a peer#10287).\n */\nexport function resolveVertexBaseUrl(opts: {\n projectId: string;\n location: string;\n modelDialect: \"anthropic\" | \"gemini\";\n}): string {\n const host =\n opts.location === \"global\"\n ? \"aiplatform.googleapis.com\"\n : `${opts.location}-aiplatform.googleapis.com`;\n if (opts.modelDialect === \"gemini\") {\n // OpenAI-compat endpoint (D291) — the client appends `/chat/completions`.\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/endpoints/openapi`;\n }\n // Anthropic — base URL up to `/publishers/anthropic` (model id appended by client).\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/publishers/anthropic`;\n}\n\n/** Detect dialect from a `vertex/{dialect}/{model}` id. Default: gemini. */\nexport function inferModelDialect(modelId: string): \"anthropic\" | \"gemini\" {\n if (modelId.includes(\"/anthropic/\")) return \"anthropic\";\n if (modelId.includes(\"/google/\")) return \"gemini\";\n return \"gemini\";\n}\n\n/** Strip the `vertex/{dialect}/` prefix so the raw model id is used in the URL. */\nexport function stripVertexPrefix(modelId: string): string {\n return modelId.replace(/^vertex\\/(anthropic|google)\\//, \"\");\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — xAI (Grok). Values per models.dev `xai` (2026-07 snapshot; grok-2 retired). */\nexport const XAI = openAiCompatibleProfile({\n name: \"xai\",\n aliases: [\"grok\"],\n baseUrl: \"https://api.x.ai/v1\",\n envVars: [\"XAI_API_KEY\"],\n fallbackModels: [\"grok-4.5\", \"grok-4.3\"],\n hostname: \"api.x.ai\",\n});\n","/**\n * Eager registration of builtin providers (T3.3). Side-effect import:\n * importing this module registers the 4 builtins with the registry.\n *\n * Lazy user-plugin discovery is handled by `discovery.ts` (T3.4).\n *\n * @internal\n */\n\nimport { registerCatalogProviders } from \"../catalog-loader.js\";\nimport { registerProvider } from \"../registry.js\";\nimport { ANTHROPIC } from \"./anthropic.js\";\nimport { BEDROCK } from \"./bedrock.js\";\nimport { CEREBRAS } from \"./cerebras.js\";\nimport { COHERE } from \"./cohere.js\";\nimport { DEEPINFRA } from \"./deepinfra.js\";\nimport { GEMINI } from \"./gemini.js\";\nimport { GOOGLE } from \"./google.js\";\nimport { GROQ } from \"./groq.js\";\nimport { LLAMACPP } from \"./llamacpp.js\";\nimport { LMSTUDIO } from \"./lmstudio.js\";\nimport { MISTRAL } from \"./mistral.js\";\nimport { OLLAMA } from \"./ollama.js\";\nimport { OPENAI } from \"./openai.js\";\nimport { OPENAI_CHATGPT } from \"./openai-chatgpt.js\";\nimport { OPENROUTER } from \"./openrouter.js\";\nimport { PERPLEXITY } from \"./perplexity.js\";\nimport { TOGETHER } from \"./together.js\";\nimport { VERTEX } from \"./vertex.js\";\nimport { XAI } from \"./xai.js\";\n\n// M45 review M2 — the guard lives on globalThis like the registry itself (M44 B1): a process importing both\n// bundle copies (`@theokit/sdk` + `@theokit/sdk/models`) must not re-register 19 builtins with bogus\n// \"overridden by user plugin\" WARNs.\nconst _registeredState = ((): { done: boolean } => {\n const g = globalThis as unknown as Record<symbol, { done: boolean }>;\n const sym = Symbol.for(\"theokit-sdk.providers.builtins-registered\");\n if (g[sym] === undefined) g[sym] = { done: false };\n return g[sym];\n})();\n\nexport function registerBuiltins(): void {\n if (_registeredState.done) return;\n _registeredState.done = true;\n // First-party builtins (take priority — registered first)\n registerProvider(ANTHROPIC);\n registerProvider(OPENAI);\n registerProvider(OPENAI_CHATGPT);\n registerProvider(OPENROUTER);\n registerProvider(GEMINI);\n registerProvider(OLLAMA);\n registerProvider(LMSTUDIO);\n registerProvider(LLAMACPP);\n registerProvider(BEDROCK);\n registerProvider(VERTEX);\n // M45 — the data-provider fleet (one file each on the openai-compatible base).\n registerProvider(GOOGLE);\n registerProvider(MISTRAL);\n registerProvider(GROQ);\n registerProvider(COHERE);\n registerProvider(DEEPINFRA);\n registerProvider(TOGETHER);\n registerProvider(XAI);\n registerProvider(PERPLEXITY);\n registerProvider(CEREBRAS);\n // Dynamic catalog — 40+ providers from JSON (T10.1, ADR D447)\n registerCatalogProviders();\n}\n\n/** Test-only reset. @internal */\nexport function _resetBuiltinsRegistered(): void {\n _registeredState.done = false;\n}\n\nexport {\n ANTHROPIC,\n BEDROCK,\n GEMINI,\n LLAMACPP,\n LMSTUDIO,\n OLLAMA,\n OPENAI,\n OPENAI_CHATGPT,\n OPENROUTER,\n VERTEX,\n};\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkUALX2J2Q_cjs = require('./chunk-UALX2J2Q.cjs');
|
|
4
4
|
var promises = require('fs/promises');
|
|
5
5
|
var path = require('path');
|
|
6
6
|
|
|
@@ -180,7 +180,7 @@ var JsonFileWorkflowSnapshotStore = class {
|
|
|
180
180
|
);
|
|
181
181
|
}
|
|
182
182
|
await promises.mkdir(this.dir, { recursive: true });
|
|
183
|
-
await
|
|
183
|
+
await chunkUALX2J2Q_cjs.atomicWriteText(this.filePath(snapshot.runId), serialized);
|
|
184
184
|
}
|
|
185
185
|
async load(runId) {
|
|
186
186
|
try {
|
|
@@ -264,5 +264,5 @@ exports.WorkflowSnapshotNotFoundError = WorkflowSnapshotNotFoundError;
|
|
|
264
264
|
exports.WorkflowStateError = WorkflowStateError;
|
|
265
265
|
exports.__resetSnapshotStoresForTests = __resetSnapshotStoresForTests;
|
|
266
266
|
exports.getSnapshotStoreFor = getSnapshotStoreFor;
|
|
267
|
-
//# sourceMappingURL=chunk-
|
|
268
|
-
//# sourceMappingURL=chunk-
|
|
267
|
+
//# sourceMappingURL=chunk-WNO3C3N2.cjs.map
|
|
268
|
+
//# sourceMappingURL=chunk-WNO3C3N2.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/workflow.ts","../src/internal/workflow/snapshot-store.ts"],"names":["join","mkdir","atomicWriteText","readFile","readdir"],"mappings":";;;;;;;AAkcO,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAEtD,YAA4B,MAAA,EAAgB;AAC1C,IAAA,KAAA,CAAM,CAAA,mBAAA,EAAsB,MAAM,CAAA,cAAA,CAAgB,CAAA;AADxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAE5B;AAAA,EAF4B,MAAA;AAAA,EADV,IAAA,GAAO,8BAAA;AAI3B;AAMO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAE5C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,kCAAA,EAAqC,MAAM,CAAA,CAAE,CAAA;AAH5D,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAGlB;AAAA,EAJkB,YAAA;AAAA,EACA,MAAA;AAAA,EAHA,IAAA,GAAO,oBAAA;AAO3B;AAMO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAE7C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,mCAAA,EAAsC,MAAM,CAAA,CAAE,CAAA;AAH7D,IAAA,I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EAAiD;AACnF,EAAA,IAAI,OAAA,CAAQ,WAAA,EAAa,OAAA,KAAY,MAAA,EAAQ;AAC3C,IAAA,MAAM,GAAA,GAAM,QAAQ,WAAA,CAAY,GAAA;AAChC,IAAA,IAAI,KAAA,GAAQ,UAAA,CAAW,GAAA,CAAI,GAAG,CAAA;AAC9B,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,KAAA,GAAQ,IAAI,8BAA8B,GAAG,CAAA;AAC7C,MAAA,UAAA,CAAW,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IAC3B;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,WAAA;AACT;AAGO,SAAS,6BAAA,GAAsC;AACpD,EAAA,UAAA,CAAW,KAAA,EAAM;AAGjB,EAAC,WAAA,CAAoB,IAAI,KAAA,EAAM;AACjC","file":"chunk-XWL6O3SW.cjs","sourcesContent":["/**\n * Public type contract for `Workflow.create / .run / .resume` (Adoption\n * Roadmap #5; ADRs D230-D248).\n *\n * Step types form a discriminated union by `kind`. Helper factory functions\n * (`fn()`, `agentStep()`) live in `workflow.ts` and hide the discriminator\n * from end users.\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\n\nimport type { SDKAgent } from \"./agent.js\";\nimport type { MessageOrigin } from \"./run.js\";\n\n/* ─── Step discriminated union (D232) ─── */\n\n/**\n * Any node of a committed workflow, discriminated by `kind`.\n *\n * Build these with the helpers rather than by hand: `fn()` and `agentStep()` set the discriminator,\n * validate the id, and parse the retry policy at construction — where a mistake is cheap — while the\n * builder methods `.parallel()`, `.branch()`, `.foreach()`, `.dowhile()`, `.sleep()` and `.suspend()`\n * cover the remaining variants and mint a positional default id (`parallel_0`, `branch_1`, ...) when\n * you do not pass one.\n *\n * Every id, nested ones included, must match `^[a-z0-9][a-z0-9_-]*$` case-insensitively and be at\n * most 64 characters, and must be unique across the whole workflow. `.commit()` walks the tree —\n * parallel branches, branch predicates, the fallback, and the inner step of a `foreach`/`dowhile` —\n * and throws {@link WorkflowDuplicateStepIdError} on the second occurrence.\n */\nexport type Step =\n | FnStep\n | AgentStep\n | ParallelStep\n | BranchStep\n | ForeachStep\n | DowhileStep\n | SleepStep\n | SuspendStep;\n\n/** A pure function step. */\nexport interface FnStep {\n readonly kind: \"fn\";\n readonly id: string;\n readonly fn: (input: unknown, ctx: StepContext) => Promise<unknown> | unknown;\n readonly inputSchema?: ZodType;\n readonly outputSchema?: ZodType;\n readonly retry?: RetryPolicy;\n /** D238 — slot reserved; runtime throws if engine not yet implemented. */\n readonly compensate?: (input: unknown, output: unknown, error: Error) => Promise<void> | void;\n}\n\n/** An agent.send-driven step. */\nexport interface AgentStep {\n readonly kind: \"agent\";\n readonly id: string;\n readonly agent: SDKAgent;\n readonly promptTemplate: string | ((input: unknown) => string);\n readonly retry?: RetryPolicy;\n /**\n * SE3 — provenance stamped onto this step's `agent.send()` (forwarded to\n * `RunResult.origin`). Squad sets `{ kind: \"peer\", from: \"agent-<i-1>\" }` on\n * every step after the first so a peer-driven turn is attributable.\n */\n readonly origin?: MessageOrigin;\n}\n\n/** N concurrent branches, each its own mini-step-list. */\nexport interface ParallelStep {\n readonly kind: \"parallel\";\n readonly id: string;\n readonly branches: ReadonlyArray<ReadonlyArray<Step>>;\n readonly concurrency?: number;\n readonly errorPolicy?: \"fail-fast\" | \"collect\";\n}\n\n/** First-match-wins predicates + optional fallback. */\nexport interface BranchStep {\n readonly kind: \"branch\";\n readonly id: string;\n readonly predicates: ReadonlyArray<\n readonly [(input: unknown) => boolean | Promise<boolean>, ReadonlyArray<Step>]\n >;\n readonly fallback?: ReadonlyArray<Step>;\n}\n\n/** Map a step over an upstream array output. */\nexport interface ForeachStep {\n readonly kind: \"foreach\";\n readonly id: string;\n /** ID of an upstream top-level step whose output is iterable. */\n readonly iterableFrom: string;\n readonly step: Step;\n readonly concurrency?: number;\n}\n\n/** Loop a step until condFn returns false. */\nexport interface DowhileStep {\n readonly kind: \"dowhile\";\n readonly id: string;\n readonly step: Step;\n readonly condFn: (output: unknown, iteration: number) => boolean | Promise<boolean>;\n readonly maxIterations?: number;\n}\n\n/** Pause for a fixed duration. */\nexport interface SleepStep {\n readonly kind: \"sleep\";\n readonly id: string;\n readonly durationMs: number;\n}\n\n/** Standalone explicit suspend point. */\nexport interface SuspendStep {\n readonly kind: \"suspend\";\n readonly id: string;\n readonly payloadSchema?: ZodType;\n}\n\n/* ─── Reflection (theokit#161) ─── */\n\n/**\n * theokit#161 — one step of a workflow, as a reflection surface sees it.\n *\n * `id` and `kind` are the only fields every step variant shares, and they are what a reflection\n * endpoint renders. Everything else a step carries is an executable — a predicate, a condition, an\n * agent, a prompt template — which cannot cross a process boundary and means nothing to a caller\n * enumerating shape.\n *\n * @public\n */\nexport interface WorkflowStepDescription {\n readonly id: string;\n readonly kind: Step[\"kind\"];\n /**\n * Nested steps, for the variants that contain them: `parallel` (all branches, flattened — the\n * branch grouping is a scheduling detail, not shape a reader needs), `branch` (each predicate's\n * steps plus the fallback), `foreach` and `dowhile` (their single inner step).\n *\n * Absent for leaf steps. A flat list would misreport a parallel or branching workflow as linear.\n */\n readonly steps?: readonly WorkflowStepDescription[];\n}\n\n/**\n * theokit#161 — the read-only shape of a committed workflow.\n *\n * Returned by `Workflow.describe()`. There is deliberately NO workflow registry to enumerate: a\n * `Workflow` is a value the caller constructs and holds, so the caller already knows which ones\n * exist. What it lacked was a way to DESCRIBE one. A registry would have added process-global state\n * that nothing ever releases, to re-answer a question the host can answer itself.\n *\n * @public\n */\nexport interface WorkflowDescription {\n readonly name: string;\n readonly steps: readonly WorkflowStepDescription[];\n}\n\n/* ─── Supporting types ─── */\n\n/** D237 — retry policy applied per fn/agent step. */\nexport interface RetryPolicy {\n /** Total attempts (MIN 1, MAX 20). `1` = no retry. */\n readonly maxAttempts: number;\n readonly initialBackoffMs?: number;\n readonly backoffCoefficient?: number;\n readonly maximumBackoffMs?: number;\n readonly nonRetryableErrors?: ReadonlyArray<string>;\n}\n\n/** D247 — context handed to every step.fn. */\nexport interface StepContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly log: {\n debug: (msg: string, attrs?: Record<string, unknown>) => void;\n info: (msg: string, attrs?: Record<string, unknown>) => void;\n warn: (msg: string, attrs?: Record<string, unknown>) => void;\n };\n /** Pause the workflow; resume via `Workflow.resume({...})`. */\n readonly suspend: (payload?: unknown) => Promise<never>;\n /**\n * SE29 — the workflow's shared state (from `WorkflowOptions.initialState`,\n * mutated by {@link setState}), visible to every subsequent step in the run.\n * `undefined` when no `initialState`/`setState` has run. Persisted across\n * suspend/resume.\n */\n readonly state: unknown;\n /**\n * SE29 — update the shared state for subsequent steps. Validated against\n * `WorkflowOptions.stateSchema` when set (a mismatch throws\n * {@link WorkflowStateError}, which fails the step/run — Rule 8).\n */\n readonly setState: (next: unknown) => void;\n}\n\n/* ─── Result types ─── */\n\n/**\n * The outcome of one step, appended to `WorkflowRun.stepResults` in execution order.\n *\n * A failing step does not throw out of `run()`. It lands here with `status: \"failed\"` and its error\n * flattened to `{ name, message }` — the thrown instance is gone by the time a caller sees it, so\n * match on `error.name` and never on `instanceof`.\n *\n * `\"skipped\"` occurs only for a `branch` step whose predicates all returned false and which declared\n * no fallback; its `output` is the step input, passed through unchanged. `\"suspended\"` marks the step\n * that called `StepContext.suspend()`, is always the last entry of the run, and carries no output.\n *\n * `attempts` means different things per kind. For `fn` and `agent` it counts execution attempts: 1\n * without a `retry` policy, and 0 when the step failed before its body ran — an `inputSchema`\n * rejection, a prompt template that threw, a `compensate` v1 refuses, or a cloud agent. For `dowhile`\n * it counts loop iterations instead.\n */\nexport interface StepResult {\n readonly stepId: string;\n readonly kind: Step[\"kind\"];\n readonly status: \"completed\" | \"failed\" | \"skipped\" | \"suspended\";\n readonly attempts: number;\n readonly durationMs: number;\n readonly output?: unknown;\n readonly error?: { name: string; message: string };\n}\n\n/**\n * The terminal record of one run — what `Workflow.run()` resolves to, what `Workflow.resume()`\n * returns, and what the `result` promise of `Workflow.stream()` settles with.\n *\n * Read `status`; do not rely on `catch`. A step that throws does not reject the promise, it ends the\n * run with `status: \"failed\"` and the error in `error`. Only `completed` populates `output`; `failed`\n * and `cancelled` (an aborted `signal`) populate `error`; `suspended` populates neither and means a\n * snapshot exists under `id` for `Workflow.resume()`. `running` is part of the union for the benefit\n * of a host tracking a run in flight — the executor only ever assembles a terminal one.\n *\n * `stepResults` is cumulative across a resume: the executor seeds it with the snapshot's prior\n * results, so the record of a resumed run covers the steps that ran before the suspend as well.\n */\nexport interface WorkflowRun<TOutput = unknown> {\n readonly id: string;\n readonly name: string;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly output?: TOutput;\n readonly error?: { name: string; message: string };\n readonly startedAt: number;\n readonly endedAt?: number;\n readonly stepResults: ReadonlyArray<StepResult>;\n}\n\n/**\n * The persisted state of a suspended run: written when a step calls `StepContext.suspend()`, read\n * back by `Workflow.resume()`. Callers never construct one — the type is exported so a host can\n * inspect what the persistence backend wrote.\n *\n * Snapshots are single-shot. `resume()` deletes the snapshot before re-entering the executor, so the\n * same one cannot be resumed twice; a second attempt raises\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * Everything reachable from here must survive `JSON.stringify` — the store serializes on save even\n * for the memory backend, and raises `WorkflowNotSerializableError` rather than letting a `TypeError`\n * escape. That rules out BigInt, circular references and class instances in step outputs, in\n * `accumulatedInput` and in `state`.\n *\n * `currentStepId` is the suspending step, and resume continues from the step AFTER it. A workflow\n * definition edited between suspend and resume therefore either fails with\n * `WorkflowResumeStepNotFoundError` (the id is gone) or resumes at a position the author did not\n * intend (the id moved).\n */\nexport interface WorkflowSnapshot {\n /** v1 = pre-SE29 (no `state`); v2 = SE29 (carries `state`). Resume reads both. */\n readonly _schemaVersion: 1 | 2;\n readonly runId: string;\n readonly workflowName: string;\n readonly currentStepId: string;\n readonly suspendedPayload?: unknown;\n readonly stepResults: ReadonlyArray<StepResult>;\n readonly accumulatedInput: unknown;\n /** SE29 — shared state captured at suspend (v2). Absent on a v1 snapshot. */\n readonly state?: unknown;\n readonly suspendedAt: number;\n}\n\n/* ─── SE28 — streaming ─── */\n\n/**\n * SE28 — a step-level workflow event emitted by `Workflow.stream()` as top-level\n * steps run. Coarse-grained (one event per top-level step; nested\n * parallel/branch/foreach emit as their single wrapping step), distinct from the\n * token-delta agent stream. Discriminate on `type`.\n *\n * @public\n */\nexport type WorkflowEvent =\n | { readonly type: \"step_started\"; readonly stepId: string }\n | { readonly type: \"step_completed\"; readonly stepId: string; readonly output: unknown }\n | {\n readonly type: \"step_failed\";\n readonly stepId: string;\n readonly error: { readonly name: string; readonly message: string };\n }\n | { readonly type: \"workflow_suspended\"; readonly stepId: string }\n | { readonly type: \"workflow_completed\" };\n\n/**\n * SE28 — the async iterator returned by `Workflow.stream()`. Yields\n * {@link WorkflowEvent}s in execution order; `result` resolves to the same\n * terminal {@link WorkflowRun} the `run()` path returns (the authoritative\n * outcome — the stream ends when the run terminates).\n *\n * @public\n */\nexport type WorkflowStream<TOutput = unknown> = AsyncIterableIterator<WorkflowEvent> & {\n readonly result: Promise<WorkflowRun<TOutput>>;\n};\n\n/* ─── Options ─── */\n\n/**\n * Where suspend snapshots are kept. Omitting `WorkflowOptions.persistence` selects the same store\n * `backend: \"memory\"` selects explicitly.\n *\n * `\"memory\"` is one process-wide map shared by every workflow, so a run suspended under it can only\n * be resumed by the process that suspended it, and only until it exits. `\"json\"` writes one\n * `{runId}.json` per snapshot into `dir` through an atomic write and survives a restart. Any suspend\n * point that waits on a human or an external system needs `\"json\"`; `\"memory\"` is for tests and for\n * suspends resolved within the same process.\n *\n * `dir` is required when `backend` is `\"json\"` and ignored otherwise — `Workflow.create()` rejects\n * the options up front when it is missing or empty, rather than failing at the first suspend.\n */\nexport interface WorkflowPersistenceOptions {\n readonly backend: \"memory\" | \"json\";\n /** Required for `backend: \"json\"`. */\n readonly dir?: string;\n}\n\n/**\n * Configuration for `Workflow.create()`, validated by Zod before the builder is handed back: a `name`\n * outside 1..128 characters, or `persistence.backend: \"json\"` without a `dir`, throws there rather\n * than at run time.\n *\n * `name` is an observability and error-message label, not an identity. Two workflows may share one;\n * the identity behind the single-flight lock is minted per `.commit()` call, so two separately\n * committed workflows never block each other however they are named.\n *\n * The three schemas are independent and each optional: `inputSchema` guards `run(input)` before step\n * 1, `outputSchema` guards the final value on the completed path only (a suspended or failed run\n * skips it), and `stateSchema` guards `initialState` plus every `StepContext.setState()` call. All\n * three must be synchronous — a schema carrying an async refinement is reported as a validation\n * failure with that explanation, never awaited.\n */\nexport interface WorkflowOptions {\n readonly name: string;\n readonly persistence?: WorkflowPersistenceOptions;\n /**\n * SE27 — Zod schema for the WHOLE workflow's input. When set, `run(input)`\n * validates `input` BEFORE step 1; a mismatch yields `status: \"failed\"` with a\n * typed {@link WorkflowInputError} in `error` (fail-fast, no step runs, no\n * silent coerce). Absent ⇒ no whole-workflow input validation (unchanged).\n */\n readonly inputSchema?: ZodType;\n /**\n * SE27 — Zod schema for the workflow's final output. When set, the terminal\n * `completed` output is validated before `WorkflowRun.output` is populated; a\n * mismatch yields `status: \"failed\"` with a typed {@link WorkflowOutputError}.\n * Only validated on the `completed` path (suspended/failed runs skip it).\n */\n readonly outputSchema?: ZodType;\n /**\n * SE29 — Zod schema for the workflow's shared state (see `StepContext.state` /\n * `setState`). When set, `initialState` and every `setState(next)` are\n * validated against it (a mismatch throws {@link WorkflowStateError}). When\n * `initialState` is absent, `state` starts as `undefined` and validation fires\n * on the first `setState` call.\n */\n readonly stateSchema?: ZodType;\n /**\n * SE29 — the initial shared state, seeded onto `StepContext.state` before\n * step 1. Validated against `stateSchema` when both are set. Persisted across\n * suspend/resume.\n */\n readonly initialState?: unknown;\n /** Internal — minted at `.commit()`. Not user-facing. */\n readonly workflowId?: string;\n}\n\n/**\n * Per-run options for `Workflow.run()` and `Workflow.stream()`.\n *\n * `signal` is combined with the run's internal single-flight signal and reaches every step through\n * `StepContext.signal`. The executor itself checks it at step boundaries, so a step that ignores the\n * signal runs to completion before the run reports `status: \"cancelled\"` — a step doing long I/O\n * should pass `ctx.signal` down to make abort prompt.\n *\n * `runId` is minted per call (`wfr-` plus 8 hex) unless you pass it, which is why concurrent runs of\n * one workflow do not interfere. Pinning it buys a deterministic id for resume, and buys the\n * single-flight lock with it: starting a second run of the same committed workflow under a `runId`\n * that is still in flight throws {@link WorkflowAlreadyRunningError}.\n */\nexport interface WorkflowRunOptions {\n readonly signal?: AbortSignal;\n /** Override run ID for deterministic resume (advanced; default = mintRunId). */\n readonly runId?: string;\n /**\n * Opt-in Task wrapping (ADRs D363, D374). Registers the workflow run\n * as a `Task` (kind=\"workflow\") with a `wf-` namespaced id (D368,\n * EC-5). The task transitions terminal when `Workflow.run` resolves.\n *\n * Auto-id: `wf-{runId}`.\n *\n * @public\n */\n readonly task?: true | { id?: string; meta?: Record<string, unknown> };\n}\n\n/**\n * Arguments for `Workflow.resume()`.\n *\n * `workflow` is typed structurally as `{ run }`, but resume needs more than `run`: it reads the\n * committed steps and options off the instance and throws a plain `Error` — \"Workflow.resume requires\n * an instance from Workflow.create().commit()\" — for anything else. Pass the same committed\n * `Workflow` the suspended run came from, not a stand-in.\n *\n * `runId` selects the snapshot. An id with no snapshot throws\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * `payload` becomes the input of the step after the suspend point, and is parsed against the\n * suspending step's `payloadSchema` first when it declared one (a mismatch throws out of `resume`).\n * Omit it to resume from the accumulated input captured in the snapshot instead — the two are\n * alternatives, not a merge.\n */\nexport interface WorkflowResumeOptions<TI = unknown> {\n readonly runId: string;\n readonly workflow: { run: (input: TI, opts?: WorkflowRunOptions) => Promise<WorkflowRun> };\n readonly payload?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/* ─── Error classes ─── */\n\n/**\n * Thrown by `.commit()` when one step id appears twice anywhere in the workflow — including inside a\n * parallel branch, a branch predicate, the fallback, and the inner step of a `foreach` or `dowhile`.\n *\n * Ids address steps in snapshots and on resume, so this is refused at build time rather than\n * discovered mid-run. Workflows nested with `workflowStep()` are exempt: the child runs in its own\n * executor with its own id-space, so its ids cannot collide with the parent's.\n */\nexport class WorkflowDuplicateStepIdError extends Error {\n override readonly name = \"WorkflowDuplicateStepIdError\";\n constructor(public readonly stepId: string) {\n super(`Duplicate step id \"${stepId}\" in workflow.`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `inputSchema` rejected `run(input)` (before step 1).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowInputError extends Error {\n override readonly name = \"WorkflowInputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" input failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `outputSchema` rejected the final output (on `completed`).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowOutputError extends Error {\n override readonly name = \"WorkflowOutputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" output failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE29 — `WorkflowOptions.stateSchema` rejected an `initialState` or a\n * `setState(next)` call. `detail` is a pre-formatted issues summary.\n */\nexport class WorkflowStateError extends Error {\n override readonly name = \"WorkflowStateError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" state failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE30 — a nested workflow (via `workflowStep`) did not `complete`. A nested\n * `suspended` is NOT resumable in v1 (resume continues AFTER the step, so the\n * child would be skipped) — restructure with a top-level suspend. A nested\n * `failed`/`cancelled` fails the parent step with the child's error attached.\n */\nexport class WorkflowNestedError extends Error {\n override readonly name = \"WorkflowNestedError\";\n constructor(\n public readonly stepId: string,\n public readonly childName: string,\n public readonly childStatus: Exclude<WorkflowRun[\"status\"], \"completed\">,\n public readonly childError?: { name: string; message: string },\n ) {\n super(\n `Nested workflow \"${childName}\" (step \"${stepId}\") ended with status \"${childStatus}\"${\n childStatus === \"suspended\"\n ? \" — nested suspend/resume is not supported in v1 (use a top-level suspend)\"\n : \"\"\n }${childError ? `: ${childError.name}: ${childError.message}` : \"\"}`,\n // Reconstruct a synthetic Error from the serialized child-error shape so\n // debuggers surface the nested cause chain — the original Error instance is\n // lost at the WorkflowRun serialization boundary, so this is the best\n // achievable without changing the run protocol.\n childError\n ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) }\n : undefined,\n );\n }\n}\n\n/**\n * Thrown out of `Workflow.run()` — one of the few workflow failures that rejects instead of arriving\n * as `run.status === \"failed\"` — when the committed workflow already has a run in flight under the\n * same run id.\n *\n * The lock key pairs the id minted at `.commit()` with the run id, not `WorkflowOptions.name`, so\n * two workflows sharing a name are independent and concurrent runs with distinct minted ids never\n * collide. In practice this only fires when a caller pins `WorkflowRunOptions.runId`, or resumes a\n * run id that is still executing. The registry is an in-process map: a crash releases every lock, and\n * it says nothing about runs in other processes.\n */\nexport class WorkflowAlreadyRunningError extends Error {\n override readonly name = \"WorkflowAlreadyRunningError\";\n constructor(\n public readonly workflowName: string,\n public readonly runId: string,\n ) {\n super(`Workflow \"${workflowName}\" run \"${runId}\" already in-flight.`);\n }\n}\n\n/**\n * Thrown by `Workflow.resume()` when no snapshot exists for the given run id.\n *\n * The message suggests configuring persistence, which is the common cause but not the only one. The\n * run may never have suspended; it may have suspended under the default memory backend in a process\n * that has since exited; or the snapshot may already have been consumed, since resume deletes it\n * before re-entering the executor and a second resume of the same run id lands here.\n */\nexport class WorkflowSnapshotNotFoundError extends Error {\n override readonly name = \"WorkflowSnapshotNotFoundError\";\n constructor(public readonly runId: string) {\n super(`No snapshot found for runId \"${runId}\". Configure persistence to enable resume.`);\n }\n}\n\n/**\n * Raised when a `dowhile` step's condition kept returning true past `maxIterations` (default 100).\n *\n * It does not escape `run()`: the step fails, the run ends `status: \"failed\"`, and the error reaches\n * the caller flattened as `run.error` with `name: \"WorkflowMaxIterationsExceededError\"` — match on\n * the name, the instance does not survive. The guard is evaluated before each iteration, so the inner\n * step runs at most `maxIterations` times; raising the ceiling is a `maxIterations` on the step, and\n * there is no global default to change.\n */\nexport class WorkflowMaxIterationsExceededError extends Error {\n override readonly name = \"WorkflowMaxIterationsExceededError\";\n constructor(\n public readonly stepId: string,\n public readonly maxIterations: number,\n ) {\n super(`Step \"${stepId}\" exceeded max iterations (${maxIterations}).`);\n }\n}\n\n/** EC-4 absorbed — JSON.stringify failed on snapshot payload. */\nexport class WorkflowNotSerializableError extends Error {\n override readonly name = \"WorkflowNotSerializableError\";\n constructor(\n public readonly stepId: string,\n public readonly underlying: Error,\n ) {\n super(\n `Workflow snapshot at step \"${stepId}\" failed to serialize as JSON: ${underlying.message}. ` +\n `Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`,\n );\n }\n}\n\n/** EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. */\nexport class WorkflowResumeStepNotFoundError extends Error {\n override readonly name = \"WorkflowResumeStepNotFoundError\";\n constructor(\n public readonly stepId: string,\n public readonly workflowName: string,\n ) {\n super(\n `Cannot resume: step \"${stepId}\" not found in workflow \"${workflowName}\". ` +\n `The Workflow definition diverged from the snapshot.`,\n );\n }\n}\n\n/** Aggregate failure from parallel branches. */\nexport class WorkflowParallelError extends AggregateError {\n override readonly name = \"WorkflowParallelError\";\n constructor(\n errors: ReadonlyArray<Error>,\n public readonly stepId: string,\n ) {\n super(errors, `${errors.length} branch(es) failed in parallel step \"${stepId}\".`);\n }\n}\n\n/** D238 — saga engine not yet implemented. */\nexport class WorkflowCompensateNotImplementedError extends Error {\n override readonly name = \"WorkflowCompensateNotImplementedError\";\n constructor(public readonly stepId: string) {\n super(\n `Step \"${stepId}\" defines compensate, but saga engine is deferred to v1.2. ` +\n `Remove compensate or implement rollback manually.`,\n );\n }\n}\n","/**\n * Snapshot store interface + InMemory and JsonFile backends (ADR D235).\n *\n * EC-4 absorbed: serialization happens here. `JSON.stringify` failure raises\n * `WorkflowNotSerializableError` instead of letting the underlying `TypeError`\n * leak.\n *\n * @internal\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n WorkflowNotSerializableError,\n type WorkflowOptions,\n type WorkflowSnapshot,\n} from \"../../types/workflow.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nexport interface WorkflowSnapshotStore {\n save(snapshot: WorkflowSnapshot): Promise<void>;\n load(runId: string): Promise<WorkflowSnapshot | undefined>;\n delete(runId: string): Promise<void>;\n list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>>;\n}\n\n/* ─── InMemory backend (default) ─── */\n\nclass InMemoryWorkflowSnapshotStore implements WorkflowSnapshotStore {\n private readonly map = new Map<string, WorkflowSnapshot>();\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n // Verify serializability even in-memory so behavior is consistent with json backend.\n try {\n JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n this.map.set(snapshot.runId, snapshot);\n }\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n return this.map.get(runId);\n }\n async delete(runId: string): Promise<void> {\n this.map.delete(runId);\n }\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n return [...this.map.values()]\n .filter((s) => workflowName === undefined || s.workflowName === workflowName)\n .map((s) => ({\n runId: s.runId,\n workflowName: s.workflowName,\n suspendedAt: s.suspendedAt,\n }));\n }\n}\n\n/* ─── Json file backend (opt-in) ─── */\n\nclass JsonFileWorkflowSnapshotStore implements WorkflowSnapshotStore {\n constructor(private readonly dir: string) {}\n\n private filePath(runId: string): string {\n return join(this.dir, `${runId}.json`);\n }\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n let serialized: string;\n try {\n serialized = JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n await mkdir(this.dir, { recursive: true });\n await atomicWriteText(this.filePath(snapshot.runId), serialized);\n }\n\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(this.filePath(runId), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n }\n\n async delete(runId: string): Promise<void> {\n try {\n await (await import(\"node:fs/promises\")).unlink(this.filePath(runId));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n private async readEntriesOrEmpty(): Promise<string[]> {\n try {\n return await readdir(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n }\n\n private async readSnapshotSafe(file: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(join(this.dir, file), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch {\n return undefined;\n }\n }\n\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n const entries = await this.readEntriesOrEmpty();\n const results: Array<{ runId: string; workflowName: string; suspendedAt: number }> = [];\n for (const file of entries) {\n if (!file.endsWith(\".json\")) continue;\n const snap = await this.readSnapshotSafe(file);\n if (snap === undefined) continue;\n if (workflowName !== undefined && snap.workflowName !== workflowName) continue;\n results.push({\n runId: snap.runId,\n workflowName: snap.workflowName,\n suspendedAt: snap.suspendedAt,\n });\n }\n return results;\n }\n}\n\n/* ─── Resolver: per-Workflow store cache ─── */\n\nconst memoryStore = new InMemoryWorkflowSnapshotStore();\nconst jsonStores = new Map<string, JsonFileWorkflowSnapshotStore>();\n\nexport function getSnapshotStoreFor(options: WorkflowOptions): WorkflowSnapshotStore {\n if (options.persistence?.backend === \"json\") {\n const dir = options.persistence.dir as string; // schema enforces dir is set\n let store = jsonStores.get(dir);\n if (store === undefined) {\n store = new JsonFileWorkflowSnapshotStore(dir);\n jsonStores.set(dir, store);\n }\n return store;\n }\n return memoryStore;\n}\n\n/** Test seam — clear in-memory store between tests. */\nexport function __resetSnapshotStoresForTests(): void {\n jsonStores.clear();\n // memoryStore has private map; reset via assignment.\n // biome-ignore lint/suspicious/noExplicitAny: test-only seam\n (memoryStore as any).map.clear();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/workflow.ts","../src/internal/workflow/snapshot-store.ts"],"names":["join","mkdir","atomicWriteText","readFile","readdir"],"mappings":";;;;;;;AAkcO,IAAM,4BAAA,GAAN,cAA2C,KAAA,CAAM;AAAA,EAEtD,YAA4B,MAAA,EAAgB;AAC1C,IAAA,KAAA,CAAM,CAAA,mBAAA,EAAsB,MAAM,CAAA,cAAA,CAAgB,CAAA;AADxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAE5B;AAAA,EAF4B,MAAA;AAAA,EADV,IAAA,GAAO,8BAAA;AAI3B;AAMO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAE5C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,kCAAA,EAAqC,MAAM,CAAA,CAAE,CAAA;AAH5D,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAGlB;AAAA,EAJkB,YAAA;AAAA,EACA,MAAA;AAAA,EAHA,IAAA,GAAO,oBAAA;AAO3B;AAMO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAE7C,WAAA,CACkB,cACA,MAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,UAAA,EAAa,YAAY,CAAA,mCAAA,EAAsC,MAAM,CAAA,CAAE,CAAA;AAH7D,IAAA,IAAA,CAAA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nF,EAAA,IAAI,OAAA,CAAQ,WAAA,EAAa,OAAA,KAAY,MAAA,EAAQ;AAC3C,IAAA,MAAM,GAAA,GAAM,QAAQ,WAAA,CAAY,GAAA;AAChC,IAAA,IAAI,KAAA,GAAQ,UAAA,CAAW,GAAA,CAAI,GAAG,CAAA;AAC9B,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,KAAA,GAAQ,IAAI,8BAA8B,GAAG,CAAA;AAC7C,MAAA,UAAA,CAAW,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,IAC3B;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,WAAA;AACT;AAGO,SAAS,6BAAA,GAAsC;AACpD,EAAA,UAAA,CAAW,KAAA,EAAM;AAGjB,EAAC,WAAA,CAAoB,IAAI,KAAA,EAAM;AACjC","file":"chunk-WNO3C3N2.cjs","sourcesContent":["/**\n * Public type contract for `Workflow.create / .run / .resume` (Adoption\n * Roadmap #5; ADRs D230-D248).\n *\n * Step types form a discriminated union by `kind`. Helper factory functions\n * (`fn()`, `agentStep()`) live in `workflow.ts` and hide the discriminator\n * from end users.\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\n\nimport type { SDKAgent } from \"./agent.js\";\nimport type { MessageOrigin } from \"./run.js\";\n\n/* ─── Step discriminated union (D232) ─── */\n\n/**\n * Any node of a committed workflow, discriminated by `kind`.\n *\n * Build these with the helpers rather than by hand: `fn()` and `agentStep()` set the discriminator,\n * validate the id, and parse the retry policy at construction — where a mistake is cheap — while the\n * builder methods `.parallel()`, `.branch()`, `.foreach()`, `.dowhile()`, `.sleep()` and `.suspend()`\n * cover the remaining variants and mint a positional default id (`parallel_0`, `branch_1`, ...) when\n * you do not pass one.\n *\n * Every id, nested ones included, must match `^[a-z0-9][a-z0-9_-]*$` case-insensitively and be at\n * most 64 characters, and must be unique across the whole workflow. `.commit()` walks the tree —\n * parallel branches, branch predicates, the fallback, and the inner step of a `foreach`/`dowhile` —\n * and throws {@link WorkflowDuplicateStepIdError} on the second occurrence.\n */\nexport type Step =\n | FnStep\n | AgentStep\n | ParallelStep\n | BranchStep\n | ForeachStep\n | DowhileStep\n | SleepStep\n | SuspendStep;\n\n/** A pure function step. */\nexport interface FnStep {\n readonly kind: \"fn\";\n readonly id: string;\n readonly fn: (input: unknown, ctx: StepContext) => Promise<unknown> | unknown;\n readonly inputSchema?: ZodType;\n readonly outputSchema?: ZodType;\n readonly retry?: RetryPolicy;\n /** D238 — slot reserved; runtime throws if engine not yet implemented. */\n readonly compensate?: (input: unknown, output: unknown, error: Error) => Promise<void> | void;\n}\n\n/** An agent.send-driven step. */\nexport interface AgentStep {\n readonly kind: \"agent\";\n readonly id: string;\n readonly agent: SDKAgent;\n readonly promptTemplate: string | ((input: unknown) => string);\n readonly retry?: RetryPolicy;\n /**\n * SE3 — provenance stamped onto this step's `agent.send()` (forwarded to\n * `RunResult.origin`). Squad sets `{ kind: \"peer\", from: \"agent-<i-1>\" }` on\n * every step after the first so a peer-driven turn is attributable.\n */\n readonly origin?: MessageOrigin;\n}\n\n/** N concurrent branches, each its own mini-step-list. */\nexport interface ParallelStep {\n readonly kind: \"parallel\";\n readonly id: string;\n readonly branches: ReadonlyArray<ReadonlyArray<Step>>;\n readonly concurrency?: number;\n readonly errorPolicy?: \"fail-fast\" | \"collect\";\n}\n\n/** First-match-wins predicates + optional fallback. */\nexport interface BranchStep {\n readonly kind: \"branch\";\n readonly id: string;\n readonly predicates: ReadonlyArray<\n readonly [(input: unknown) => boolean | Promise<boolean>, ReadonlyArray<Step>]\n >;\n readonly fallback?: ReadonlyArray<Step>;\n}\n\n/** Map a step over an upstream array output. */\nexport interface ForeachStep {\n readonly kind: \"foreach\";\n readonly id: string;\n /** ID of an upstream top-level step whose output is iterable. */\n readonly iterableFrom: string;\n readonly step: Step;\n readonly concurrency?: number;\n}\n\n/** Loop a step until condFn returns false. */\nexport interface DowhileStep {\n readonly kind: \"dowhile\";\n readonly id: string;\n readonly step: Step;\n readonly condFn: (output: unknown, iteration: number) => boolean | Promise<boolean>;\n readonly maxIterations?: number;\n}\n\n/** Pause for a fixed duration. */\nexport interface SleepStep {\n readonly kind: \"sleep\";\n readonly id: string;\n readonly durationMs: number;\n}\n\n/** Standalone explicit suspend point. */\nexport interface SuspendStep {\n readonly kind: \"suspend\";\n readonly id: string;\n readonly payloadSchema?: ZodType;\n}\n\n/* ─── Reflection (theokit#161) ─── */\n\n/**\n * theokit#161 — one step of a workflow, as a reflection surface sees it.\n *\n * `id` and `kind` are the only fields every step variant shares, and they are what a reflection\n * endpoint renders. Everything else a step carries is an executable — a predicate, a condition, an\n * agent, a prompt template — which cannot cross a process boundary and means nothing to a caller\n * enumerating shape.\n *\n * @public\n */\nexport interface WorkflowStepDescription {\n readonly id: string;\n readonly kind: Step[\"kind\"];\n /**\n * Nested steps, for the variants that contain them: `parallel` (all branches, flattened — the\n * branch grouping is a scheduling detail, not shape a reader needs), `branch` (each predicate's\n * steps plus the fallback), `foreach` and `dowhile` (their single inner step).\n *\n * Absent for leaf steps. A flat list would misreport a parallel or branching workflow as linear.\n */\n readonly steps?: readonly WorkflowStepDescription[];\n}\n\n/**\n * theokit#161 — the read-only shape of a committed workflow.\n *\n * Returned by `Workflow.describe()`. There is deliberately NO workflow registry to enumerate: a\n * `Workflow` is a value the caller constructs and holds, so the caller already knows which ones\n * exist. What it lacked was a way to DESCRIBE one. A registry would have added process-global state\n * that nothing ever releases, to re-answer a question the host can answer itself.\n *\n * @public\n */\nexport interface WorkflowDescription {\n readonly name: string;\n readonly steps: readonly WorkflowStepDescription[];\n}\n\n/* ─── Supporting types ─── */\n\n/** D237 — retry policy applied per fn/agent step. */\nexport interface RetryPolicy {\n /** Total attempts (MIN 1, MAX 20). `1` = no retry. */\n readonly maxAttempts: number;\n readonly initialBackoffMs?: number;\n readonly backoffCoefficient?: number;\n readonly maximumBackoffMs?: number;\n readonly nonRetryableErrors?: ReadonlyArray<string>;\n}\n\n/** D247 — context handed to every step.fn. */\nexport interface StepContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly log: {\n debug: (msg: string, attrs?: Record<string, unknown>) => void;\n info: (msg: string, attrs?: Record<string, unknown>) => void;\n warn: (msg: string, attrs?: Record<string, unknown>) => void;\n };\n /** Pause the workflow; resume via `Workflow.resume({...})`. */\n readonly suspend: (payload?: unknown) => Promise<never>;\n /**\n * SE29 — the workflow's shared state (from `WorkflowOptions.initialState`,\n * mutated by {@link setState}), visible to every subsequent step in the run.\n * `undefined` when no `initialState`/`setState` has run. Persisted across\n * suspend/resume.\n */\n readonly state: unknown;\n /**\n * SE29 — update the shared state for subsequent steps. Validated against\n * `WorkflowOptions.stateSchema` when set (a mismatch throws\n * {@link WorkflowStateError}, which fails the step/run — Rule 8).\n */\n readonly setState: (next: unknown) => void;\n}\n\n/* ─── Result types ─── */\n\n/**\n * The outcome of one step, appended to `WorkflowRun.stepResults` in execution order.\n *\n * A failing step does not throw out of `run()`. It lands here with `status: \"failed\"` and its error\n * flattened to `{ name, message }` — the thrown instance is gone by the time a caller sees it, so\n * match on `error.name` and never on `instanceof`.\n *\n * `\"skipped\"` occurs only for a `branch` step whose predicates all returned false and which declared\n * no fallback; its `output` is the step input, passed through unchanged. `\"suspended\"` marks the step\n * that called `StepContext.suspend()`, is always the last entry of the run, and carries no output.\n *\n * `attempts` means different things per kind. For `fn` and `agent` it counts execution attempts: 1\n * without a `retry` policy, and 0 when the step failed before its body ran — an `inputSchema`\n * rejection, a prompt template that threw, a `compensate` v1 refuses, or a cloud agent. For `dowhile`\n * it counts loop iterations instead.\n */\nexport interface StepResult {\n readonly stepId: string;\n readonly kind: Step[\"kind\"];\n readonly status: \"completed\" | \"failed\" | \"skipped\" | \"suspended\";\n readonly attempts: number;\n readonly durationMs: number;\n readonly output?: unknown;\n readonly error?: { name: string; message: string };\n}\n\n/**\n * The terminal record of one run — what `Workflow.run()` resolves to, what `Workflow.resume()`\n * returns, and what the `result` promise of `Workflow.stream()` settles with.\n *\n * Read `status`; do not rely on `catch`. A step that throws does not reject the promise, it ends the\n * run with `status: \"failed\"` and the error in `error`. Only `completed` populates `output`; `failed`\n * and `cancelled` (an aborted `signal`) populate `error`; `suspended` populates neither and means a\n * snapshot exists under `id` for `Workflow.resume()`. `running` is part of the union for the benefit\n * of a host tracking a run in flight — the executor only ever assembles a terminal one.\n *\n * `stepResults` is cumulative across a resume: the executor seeds it with the snapshot's prior\n * results, so the record of a resumed run covers the steps that ran before the suspend as well.\n */\nexport interface WorkflowRun<TOutput = unknown> {\n readonly id: string;\n readonly name: string;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly output?: TOutput;\n readonly error?: { name: string; message: string };\n readonly startedAt: number;\n readonly endedAt?: number;\n readonly stepResults: ReadonlyArray<StepResult>;\n}\n\n/**\n * The persisted state of a suspended run: written when a step calls `StepContext.suspend()`, read\n * back by `Workflow.resume()`. Callers never construct one — the type is exported so a host can\n * inspect what the persistence backend wrote.\n *\n * Snapshots are single-shot. `resume()` deletes the snapshot before re-entering the executor, so the\n * same one cannot be resumed twice; a second attempt raises\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * Everything reachable from here must survive `JSON.stringify` — the store serializes on save even\n * for the memory backend, and raises `WorkflowNotSerializableError` rather than letting a `TypeError`\n * escape. That rules out BigInt, circular references and class instances in step outputs, in\n * `accumulatedInput` and in `state`.\n *\n * `currentStepId` is the suspending step, and resume continues from the step AFTER it. A workflow\n * definition edited between suspend and resume therefore either fails with\n * `WorkflowResumeStepNotFoundError` (the id is gone) or resumes at a position the author did not\n * intend (the id moved).\n */\nexport interface WorkflowSnapshot {\n /** v1 = pre-SE29 (no `state`); v2 = SE29 (carries `state`). Resume reads both. */\n readonly _schemaVersion: 1 | 2;\n readonly runId: string;\n readonly workflowName: string;\n readonly currentStepId: string;\n readonly suspendedPayload?: unknown;\n readonly stepResults: ReadonlyArray<StepResult>;\n readonly accumulatedInput: unknown;\n /** SE29 — shared state captured at suspend (v2). Absent on a v1 snapshot. */\n readonly state?: unknown;\n readonly suspendedAt: number;\n}\n\n/* ─── SE28 — streaming ─── */\n\n/**\n * SE28 — a step-level workflow event emitted by `Workflow.stream()` as top-level\n * steps run. Coarse-grained (one event per top-level step; nested\n * parallel/branch/foreach emit as their single wrapping step), distinct from the\n * token-delta agent stream. Discriminate on `type`.\n *\n * @public\n */\nexport type WorkflowEvent =\n | { readonly type: \"step_started\"; readonly stepId: string }\n | { readonly type: \"step_completed\"; readonly stepId: string; readonly output: unknown }\n | {\n readonly type: \"step_failed\";\n readonly stepId: string;\n readonly error: { readonly name: string; readonly message: string };\n }\n | { readonly type: \"workflow_suspended\"; readonly stepId: string }\n | { readonly type: \"workflow_completed\" };\n\n/**\n * SE28 — the async iterator returned by `Workflow.stream()`. Yields\n * {@link WorkflowEvent}s in execution order; `result` resolves to the same\n * terminal {@link WorkflowRun} the `run()` path returns (the authoritative\n * outcome — the stream ends when the run terminates).\n *\n * @public\n */\nexport type WorkflowStream<TOutput = unknown> = AsyncIterableIterator<WorkflowEvent> & {\n readonly result: Promise<WorkflowRun<TOutput>>;\n};\n\n/* ─── Options ─── */\n\n/**\n * Where suspend snapshots are kept. Omitting `WorkflowOptions.persistence` selects the same store\n * `backend: \"memory\"` selects explicitly.\n *\n * `\"memory\"` is one process-wide map shared by every workflow, so a run suspended under it can only\n * be resumed by the process that suspended it, and only until it exits. `\"json\"` writes one\n * `{runId}.json` per snapshot into `dir` through an atomic write and survives a restart. Any suspend\n * point that waits on a human or an external system needs `\"json\"`; `\"memory\"` is for tests and for\n * suspends resolved within the same process.\n *\n * `dir` is required when `backend` is `\"json\"` and ignored otherwise — `Workflow.create()` rejects\n * the options up front when it is missing or empty, rather than failing at the first suspend.\n */\nexport interface WorkflowPersistenceOptions {\n readonly backend: \"memory\" | \"json\";\n /** Required for `backend: \"json\"`. */\n readonly dir?: string;\n}\n\n/**\n * Configuration for `Workflow.create()`, validated by Zod before the builder is handed back: a `name`\n * outside 1..128 characters, or `persistence.backend: \"json\"` without a `dir`, throws there rather\n * than at run time.\n *\n * `name` is an observability and error-message label, not an identity. Two workflows may share one;\n * the identity behind the single-flight lock is minted per `.commit()` call, so two separately\n * committed workflows never block each other however they are named.\n *\n * The three schemas are independent and each optional: `inputSchema` guards `run(input)` before step\n * 1, `outputSchema` guards the final value on the completed path only (a suspended or failed run\n * skips it), and `stateSchema` guards `initialState` plus every `StepContext.setState()` call. All\n * three must be synchronous — a schema carrying an async refinement is reported as a validation\n * failure with that explanation, never awaited.\n */\nexport interface WorkflowOptions {\n readonly name: string;\n readonly persistence?: WorkflowPersistenceOptions;\n /**\n * SE27 — Zod schema for the WHOLE workflow's input. When set, `run(input)`\n * validates `input` BEFORE step 1; a mismatch yields `status: \"failed\"` with a\n * typed {@link WorkflowInputError} in `error` (fail-fast, no step runs, no\n * silent coerce). Absent ⇒ no whole-workflow input validation (unchanged).\n */\n readonly inputSchema?: ZodType;\n /**\n * SE27 — Zod schema for the workflow's final output. When set, the terminal\n * `completed` output is validated before `WorkflowRun.output` is populated; a\n * mismatch yields `status: \"failed\"` with a typed {@link WorkflowOutputError}.\n * Only validated on the `completed` path (suspended/failed runs skip it).\n */\n readonly outputSchema?: ZodType;\n /**\n * SE29 — Zod schema for the workflow's shared state (see `StepContext.state` /\n * `setState`). When set, `initialState` and every `setState(next)` are\n * validated against it (a mismatch throws {@link WorkflowStateError}). When\n * `initialState` is absent, `state` starts as `undefined` and validation fires\n * on the first `setState` call.\n */\n readonly stateSchema?: ZodType;\n /**\n * SE29 — the initial shared state, seeded onto `StepContext.state` before\n * step 1. Validated against `stateSchema` when both are set. Persisted across\n * suspend/resume.\n */\n readonly initialState?: unknown;\n /** Internal — minted at `.commit()`. Not user-facing. */\n readonly workflowId?: string;\n}\n\n/**\n * Per-run options for `Workflow.run()` and `Workflow.stream()`.\n *\n * `signal` is combined with the run's internal single-flight signal and reaches every step through\n * `StepContext.signal`. The executor itself checks it at step boundaries, so a step that ignores the\n * signal runs to completion before the run reports `status: \"cancelled\"` — a step doing long I/O\n * should pass `ctx.signal` down to make abort prompt.\n *\n * `runId` is minted per call (`wfr-` plus 8 hex) unless you pass it, which is why concurrent runs of\n * one workflow do not interfere. Pinning it buys a deterministic id for resume, and buys the\n * single-flight lock with it: starting a second run of the same committed workflow under a `runId`\n * that is still in flight throws {@link WorkflowAlreadyRunningError}.\n */\nexport interface WorkflowRunOptions {\n readonly signal?: AbortSignal;\n /** Override run ID for deterministic resume (advanced; default = mintRunId). */\n readonly runId?: string;\n /**\n * Opt-in Task wrapping (ADRs D363, D374). Registers the workflow run\n * as a `Task` (kind=\"workflow\") with a `wf-` namespaced id (D368,\n * EC-5). The task transitions terminal when `Workflow.run` resolves.\n *\n * Auto-id: `wf-{runId}`.\n *\n * @public\n */\n readonly task?: true | { id?: string; meta?: Record<string, unknown> };\n}\n\n/**\n * Arguments for `Workflow.resume()`.\n *\n * `workflow` is typed structurally as `{ run }`, but resume needs more than `run`: it reads the\n * committed steps and options off the instance and throws a plain `Error` — \"Workflow.resume requires\n * an instance from Workflow.create().commit()\" — for anything else. Pass the same committed\n * `Workflow` the suspended run came from, not a stand-in.\n *\n * `runId` selects the snapshot. An id with no snapshot throws\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * `payload` becomes the input of the step after the suspend point, and is parsed against the\n * suspending step's `payloadSchema` first when it declared one (a mismatch throws out of `resume`).\n * Omit it to resume from the accumulated input captured in the snapshot instead — the two are\n * alternatives, not a merge.\n */\nexport interface WorkflowResumeOptions<TI = unknown> {\n readonly runId: string;\n readonly workflow: { run: (input: TI, opts?: WorkflowRunOptions) => Promise<WorkflowRun> };\n readonly payload?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/* ─── Error classes ─── */\n\n/**\n * Thrown by `.commit()` when one step id appears twice anywhere in the workflow — including inside a\n * parallel branch, a branch predicate, the fallback, and the inner step of a `foreach` or `dowhile`.\n *\n * Ids address steps in snapshots and on resume, so this is refused at build time rather than\n * discovered mid-run. Workflows nested with `workflowStep()` are exempt: the child runs in its own\n * executor with its own id-space, so its ids cannot collide with the parent's.\n */\nexport class WorkflowDuplicateStepIdError extends Error {\n override readonly name = \"WorkflowDuplicateStepIdError\";\n constructor(public readonly stepId: string) {\n super(`Duplicate step id \"${stepId}\" in workflow.`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `inputSchema` rejected `run(input)` (before step 1).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowInputError extends Error {\n override readonly name = \"WorkflowInputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" input failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `outputSchema` rejected the final output (on `completed`).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowOutputError extends Error {\n override readonly name = \"WorkflowOutputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" output failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE29 — `WorkflowOptions.stateSchema` rejected an `initialState` or a\n * `setState(next)` call. `detail` is a pre-formatted issues summary.\n */\nexport class WorkflowStateError extends Error {\n override readonly name = \"WorkflowStateError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" state failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE30 — a nested workflow (via `workflowStep`) did not `complete`. A nested\n * `suspended` is NOT resumable in v1 (resume continues AFTER the step, so the\n * child would be skipped) — restructure with a top-level suspend. A nested\n * `failed`/`cancelled` fails the parent step with the child's error attached.\n */\nexport class WorkflowNestedError extends Error {\n override readonly name = \"WorkflowNestedError\";\n constructor(\n public readonly stepId: string,\n public readonly childName: string,\n public readonly childStatus: Exclude<WorkflowRun[\"status\"], \"completed\">,\n public readonly childError?: { name: string; message: string },\n ) {\n super(\n `Nested workflow \"${childName}\" (step \"${stepId}\") ended with status \"${childStatus}\"${\n childStatus === \"suspended\"\n ? \" — nested suspend/resume is not supported in v1 (use a top-level suspend)\"\n : \"\"\n }${childError ? `: ${childError.name}: ${childError.message}` : \"\"}`,\n // Reconstruct a synthetic Error from the serialized child-error shape so\n // debuggers surface the nested cause chain — the original Error instance is\n // lost at the WorkflowRun serialization boundary, so this is the best\n // achievable without changing the run protocol.\n childError\n ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) }\n : undefined,\n );\n }\n}\n\n/**\n * Thrown out of `Workflow.run()` — one of the few workflow failures that rejects instead of arriving\n * as `run.status === \"failed\"` — when the committed workflow already has a run in flight under the\n * same run id.\n *\n * The lock key pairs the id minted at `.commit()` with the run id, not `WorkflowOptions.name`, so\n * two workflows sharing a name are independent and concurrent runs with distinct minted ids never\n * collide. In practice this only fires when a caller pins `WorkflowRunOptions.runId`, or resumes a\n * run id that is still executing. The registry is an in-process map: a crash releases every lock, and\n * it says nothing about runs in other processes.\n */\nexport class WorkflowAlreadyRunningError extends Error {\n override readonly name = \"WorkflowAlreadyRunningError\";\n constructor(\n public readonly workflowName: string,\n public readonly runId: string,\n ) {\n super(`Workflow \"${workflowName}\" run \"${runId}\" already in-flight.`);\n }\n}\n\n/**\n * Thrown by `Workflow.resume()` when no snapshot exists for the given run id.\n *\n * The message suggests configuring persistence, which is the common cause but not the only one. The\n * run may never have suspended; it may have suspended under the default memory backend in a process\n * that has since exited; or the snapshot may already have been consumed, since resume deletes it\n * before re-entering the executor and a second resume of the same run id lands here.\n */\nexport class WorkflowSnapshotNotFoundError extends Error {\n override readonly name = \"WorkflowSnapshotNotFoundError\";\n constructor(public readonly runId: string) {\n super(`No snapshot found for runId \"${runId}\". Configure persistence to enable resume.`);\n }\n}\n\n/**\n * Raised when a `dowhile` step's condition kept returning true past `maxIterations` (default 100).\n *\n * It does not escape `run()`: the step fails, the run ends `status: \"failed\"`, and the error reaches\n * the caller flattened as `run.error` with `name: \"WorkflowMaxIterationsExceededError\"` — match on\n * the name, the instance does not survive. The guard is evaluated before each iteration, so the inner\n * step runs at most `maxIterations` times; raising the ceiling is a `maxIterations` on the step, and\n * there is no global default to change.\n */\nexport class WorkflowMaxIterationsExceededError extends Error {\n override readonly name = \"WorkflowMaxIterationsExceededError\";\n constructor(\n public readonly stepId: string,\n public readonly maxIterations: number,\n ) {\n super(`Step \"${stepId}\" exceeded max iterations (${maxIterations}).`);\n }\n}\n\n/** EC-4 absorbed — JSON.stringify failed on snapshot payload. */\nexport class WorkflowNotSerializableError extends Error {\n override readonly name = \"WorkflowNotSerializableError\";\n constructor(\n public readonly stepId: string,\n public readonly underlying: Error,\n ) {\n super(\n `Workflow snapshot at step \"${stepId}\" failed to serialize as JSON: ${underlying.message}. ` +\n `Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`,\n );\n }\n}\n\n/** EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. */\nexport class WorkflowResumeStepNotFoundError extends Error {\n override readonly name = \"WorkflowResumeStepNotFoundError\";\n constructor(\n public readonly stepId: string,\n public readonly workflowName: string,\n ) {\n super(\n `Cannot resume: step \"${stepId}\" not found in workflow \"${workflowName}\". ` +\n `The Workflow definition diverged from the snapshot.`,\n );\n }\n}\n\n/** Aggregate failure from parallel branches. */\nexport class WorkflowParallelError extends AggregateError {\n override readonly name = \"WorkflowParallelError\";\n constructor(\n errors: ReadonlyArray<Error>,\n public readonly stepId: string,\n ) {\n super(errors, `${errors.length} branch(es) failed in parallel step \"${stepId}\".`);\n }\n}\n\n/** D238 — saga engine not yet implemented. */\nexport class WorkflowCompensateNotImplementedError extends Error {\n override readonly name = \"WorkflowCompensateNotImplementedError\";\n constructor(public readonly stepId: string) {\n super(\n `Step \"${stepId}\" defines compensate, but saga engine is deferred to v1.2. ` +\n `Remove compensate or implement rollback manually.`,\n );\n }\n}\n","/**\n * Snapshot store interface + InMemory and JsonFile backends (ADR D235).\n *\n * EC-4 absorbed: serialization happens here. `JSON.stringify` failure raises\n * `WorkflowNotSerializableError` instead of letting the underlying `TypeError`\n * leak.\n *\n * @internal\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n WorkflowNotSerializableError,\n type WorkflowOptions,\n type WorkflowSnapshot,\n} from \"../../types/workflow.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nexport interface WorkflowSnapshotStore {\n save(snapshot: WorkflowSnapshot): Promise<void>;\n load(runId: string): Promise<WorkflowSnapshot | undefined>;\n delete(runId: string): Promise<void>;\n list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>>;\n}\n\n/* ─── InMemory backend (default) ─── */\n\nclass InMemoryWorkflowSnapshotStore implements WorkflowSnapshotStore {\n private readonly map = new Map<string, WorkflowSnapshot>();\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n // Verify serializability even in-memory so behavior is consistent with json backend.\n try {\n JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n this.map.set(snapshot.runId, snapshot);\n }\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n return this.map.get(runId);\n }\n async delete(runId: string): Promise<void> {\n this.map.delete(runId);\n }\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n return [...this.map.values()]\n .filter((s) => workflowName === undefined || s.workflowName === workflowName)\n .map((s) => ({\n runId: s.runId,\n workflowName: s.workflowName,\n suspendedAt: s.suspendedAt,\n }));\n }\n}\n\n/* ─── Json file backend (opt-in) ─── */\n\nclass JsonFileWorkflowSnapshotStore implements WorkflowSnapshotStore {\n constructor(private readonly dir: string) {}\n\n private filePath(runId: string): string {\n return join(this.dir, `${runId}.json`);\n }\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n let serialized: string;\n try {\n serialized = JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n await mkdir(this.dir, { recursive: true });\n await atomicWriteText(this.filePath(snapshot.runId), serialized);\n }\n\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(this.filePath(runId), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n }\n\n async delete(runId: string): Promise<void> {\n try {\n await (await import(\"node:fs/promises\")).unlink(this.filePath(runId));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n private async readEntriesOrEmpty(): Promise<string[]> {\n try {\n return await readdir(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n }\n\n private async readSnapshotSafe(file: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(join(this.dir, file), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch {\n return undefined;\n }\n }\n\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n const entries = await this.readEntriesOrEmpty();\n const results: Array<{ runId: string; workflowName: string; suspendedAt: number }> = [];\n for (const file of entries) {\n if (!file.endsWith(\".json\")) continue;\n const snap = await this.readSnapshotSafe(file);\n if (snap === undefined) continue;\n if (workflowName !== undefined && snap.workflowName !== workflowName) continue;\n results.push({\n runId: snap.runId,\n workflowName: snap.workflowName,\n suspendedAt: snap.suspendedAt,\n });\n }\n return results;\n }\n}\n\n/* ─── Resolver: per-Workflow store cache ─── */\n\nconst memoryStore = new InMemoryWorkflowSnapshotStore();\nconst jsonStores = new Map<string, JsonFileWorkflowSnapshotStore>();\n\nexport function getSnapshotStoreFor(options: WorkflowOptions): WorkflowSnapshotStore {\n if (options.persistence?.backend === \"json\") {\n const dir = options.persistence.dir as string; // schema enforces dir is set\n let store = jsonStores.get(dir);\n if (store === undefined) {\n store = new JsonFileWorkflowSnapshotStore(dir);\n jsonStores.set(dir, store);\n }\n return store;\n }\n return memoryStore;\n}\n\n/** Test seam — clear in-memory store between tests. */\nexport function __resetSnapshotStoresForTests(): void {\n jsonStores.clear();\n // memoryStore has private map; reset via assignment.\n // biome-ignore lint/suspicious/noExplicitAny: test-only seam\n (memoryStore as any).map.clear();\n}\n"]}
|
|
@@ -14,7 +14,22 @@ function diag(message) {
|
|
|
14
14
|
} catch {
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
+
function diagFailure(message) {
|
|
18
|
+
const sink = currentSink();
|
|
19
|
+
if (sink !== void 0) {
|
|
20
|
+
try {
|
|
21
|
+
sink(message);
|
|
22
|
+
return;
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
globalThis.process?.stderr?.write(`${message}
|
|
28
|
+
`);
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
}
|
|
17
32
|
|
|
18
|
-
export { diag, setDiagnosticsSink };
|
|
19
|
-
//# sourceMappingURL=chunk-
|
|
20
|
-
//# sourceMappingURL=chunk-
|
|
33
|
+
export { diag, diagFailure, setDiagnosticsSink };
|
|
34
|
+
//# sourceMappingURL=chunk-XEQ3TM66.js.map
|
|
35
|
+
//# sourceMappingURL=chunk-XEQ3TM66.js.map
|