@theokit/sdk 4.63.0 → 4.63.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/dist/a2a/index.cjs +2 -2
- package/dist/a2a/index.js +1 -1
- package/dist/agent-WK7MKIMH.cjs +66 -0
- package/dist/{agent-5KYMG63I.cjs.map → agent-WK7MKIMH.cjs.map} +1 -1
- package/dist/agent-YWMBM7LX.js +57 -0
- package/dist/{agent-536OOESZ.js.map → agent-YWMBM7LX.js.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-MG3SOM3M.js → chunk-BVJJ3DRV.js} +6 -6
- package/dist/{chunk-MG3SOM3M.js.map → chunk-BVJJ3DRV.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-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-CHKH5452.js → chunk-KIH6IZ43.js} +60 -45
- package/dist/chunk-KIH6IZ43.js.map +1 -0
- 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-CASUEY42.cjs → chunk-Q7LPTOD6.cjs} +24 -24
- package/dist/{chunk-CASUEY42.cjs.map → chunk-Q7LPTOD6.cjs.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-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-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-NLXOGBRJ.cjs → chunk-ZMRD5DZQ.cjs} +338 -323
- package/dist/chunk-ZMRD5DZQ.cjs.map +1 -0
- 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,5 +1,5 @@
|
|
|
1
|
-
import { AuthenticationError, RateLimitError, ConfigurationError, NetworkError, UnknownAgentError } from './chunk-
|
|
2
|
-
import { redactSecrets } from './chunk-
|
|
1
|
+
import { AuthenticationError, RateLimitError, ConfigurationError, NetworkError, UnknownAgentError } from './chunk-ZZMZWBR6.js';
|
|
2
|
+
import { redactSecrets } from './chunk-D4CUGAKZ.js';
|
|
3
3
|
|
|
4
4
|
// src/internal/error-mappers/shared.ts
|
|
5
5
|
var RAW_MAX_BYTES = 2048;
|
|
@@ -96,5 +96,5 @@ function formatMessage(providerId, status, code) {
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
export { buildErrorMetadata, mapOpenAICompatibleError };
|
|
99
|
-
//# sourceMappingURL=chunk-
|
|
100
|
-
//# sourceMappingURL=chunk-
|
|
99
|
+
//# sourceMappingURL=chunk-7YGCPMGB.js.map
|
|
100
|
+
//# sourceMappingURL=chunk-7YGCPMGB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/error-mappers/shared.ts","../src/internal/error-mappers/openai-compatible.ts"],"names":[],"mappings":";;;;AAaA,IAAM,aAAA,GAAgB,IAAA;AAUf,SAAS,gBAAgB,OAAA,EAAkD;AAChF,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,MAAA;AAClC,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA;AACrC,EAAA,IAAI,GAAA,KAAQ,MAAM,OAAO,MAAA;AACzB,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,MAAA,CAAO,SAAS,CAAC,CAAA,IAAK,KAAK,CAAA,EAAG,OAAO,IAAA,CAAK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AAA,IACpC,OAAA,CAAQ,QAAA,CAAS,eAAe,CAAA,EAChC;AACA,IAAA,OAAO,mBAAA;AAAA,EACT;AAMA,EAAA,IACE,MAAA,KAAW,OACX,OAAA,CAAQ,QAAA,CAAS,oBAAoB,CAAA,IACrC,OAAA,CAAQ,QAAA,CAAS,gBAAgB,CAAA,EACjC;AACA,IAAA,OAAO,gBAAA;AAAA,EACT;AAEA,EAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK,OAAO,aAAA;AAC7C,EAAA,IAAI,MAAA,KAAW,KAAK,OAAO,YAAA;AAC3B,EAAA,IAAI,MAAA,KAAW,KAAK,OAAO,SAAA;AAC3B,EAAA,IAAI,MAAA,KAAW,KAAK,OAAO,iBAAA;AAC3B,EAAA,IAAI,MAAA,IAAU,GAAA,IAAO,MAAA,GAAS,GAAA,EAAK,OAAO,cAAA;AAC1C,EAAA,OAAO,SAAA;AACT;AAEA,SAAS,aAAA,CAAc,UAAA,EAAoB,MAAA,EAAgB,IAAA,EAAyB;AAClF,EAAA,OAAO,CAAA,EAAG,UAAU,CAAA,YAAA,EAAe,IAAI,UAAU,MAAM,CAAA,CAAA,CAAA;AACzD","file":"chunk-5JLFFPCH.js","sourcesContent":["/**\n * Helpers shared between provider HTTP error mappers (ADR D67).\n *\n * Extracted to dedupe identical logic in `anthropic.ts` and\n * `openai-compatible.ts` — retry-after parsing, raw-body truncation,\n * and metadata assembly are dialect-agnostic.\n *\n * @internal\n */\n\nimport type { ErrorCode, ErrorMetadata } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\n\nconst RAW_MAX_BYTES = 2048;\n\n/**\n * Parse the `Retry-After` header (RFC 7231) into seconds. Both forms are\n * supported: numeric-seconds (`Retry-After: 30`) and HTTP-date\n * (`Retry-After: Wed, 21 Oct 2025 07:28:00 GMT` → seconds until that instant,\n * clamped at 0 for a past date). Garbage / missing header → `undefined`.\n *\n * @internal\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n // HTTP-date form — seconds until the given instant (0 if already elapsed).\n const dateMs = Date.parse(raw);\n if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n *\n * Post T1.1 (secret-redaction-discipline, ADR D68): every error metadata\n * goes through `redactSecrets` before exposure. Note the shape change —\n * pre-T1.1 the function preserved the original `body` shape when ≤2KB;\n * now it always returns a (possibly redacted) string, because redaction\n * coerces non-strings to JSON. Consumers who used to do `err.metadata.raw.foo`\n * must now `JSON.parse(err.metadata.raw)` first — but a workspace-wide\n * grep at T1.1 land time confirmed zero such callers.\n *\n * @internal\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n const truncated = s.length <= RAW_MAX_BYTES ? s : `${s.slice(0, RAW_MAX_BYTES)}…`;\n return redactSecrets(truncated);\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output). Caller passes\n * dialect-specific fields (`provider`, `endpoint`, `code`); shared\n * fields (`statusCode`, `retryAfter`, `raw`) are derived here.\n *\n * @internal\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\n/**\n * D314: extract the provider's request id (`x-request-id` is OpenAI/most;\n * `request-id` is Anthropic). Returns `undefined` when neither is present.\n *\n * @internal\n */\nexport function parseRequestId(headers: Headers | undefined): string | undefined {\n if (headers === undefined) return undefined;\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67).\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 400) {\n return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — OpenAI 402 / OpenRouter \"Insufficient credits\" / `insufficient_quota`\n // body code now flow to canonical `quota_exceeded`. Pre-T3.7 we returned\n // `invalid_request` because the ErrorCode union lacked the bucket; T3.7\n // added it. AgentRunError.code (KnownAgentRunErrorCode, post-T1.1) has\n // always carried this value; this fix closes the metadata.code surface.\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(providerId: string, status: number, code: ErrorCode): string {\n return `${providerId} API error: ${code} (HTTP ${status})`;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/error-mappers/shared.ts","../src/internal/error-mappers/openai-compatible.ts"],"names":[],"mappings":";;;;AAaA,IAAM,aAAA,GAAgB,IAAA;AAUf,SAAS,gBAAgB,OAAA,EAAkD;AAChF,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,MAAA;AAClC,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA;AACrC,EAAA,IAAI,GAAA,KAAQ,MAAM,OAAO,MAAA;AACzB,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,MAAA,CAAO,SAAS,CAAC,CAAA,IAAK,KAAK,CAAA,EAAG,OAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA;AAEpD,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,EAAA,IAAI,MAAA,CAAO,QAAA,CAAS,MAAM,CAAA,SAAU,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,MAAM,MAAA,GAAS,IAAA,CAAK,GAAA,EAAI,IAAK,GAAI,CAAC,CAAA;AACvF,EAAA,OAAO,MAAA;AACT;AAkBO,SAAS,YAAY,IAAA,EAAwB;AAClD,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,IAAA,KAAS,MAAA,EAAW,OAAO,MAAA;AAChD,EAAA,MAAM,IAAI,OAAO,IAAA,KAAS,WAAW,IAAA,GAAO,IAAA,CAAK,UAAU,IAAI,CAAA;AAC/D,EAAA,MAAM,SAAA,GAAY,CAAA,CAAE,MAAA,IAAU,aAAA,GAAgB,CAAA,GAAI,GAAG,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,aAAa,CAAC,CAAA,MAAA,CAAA;AAC9E,EAAA,OAAO,cAAc,SAAS,CAAA;AAChC;AAUO,SAAS,mBAAmB,IAAA,EAOjB;AAChB,EAAA,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ACzD","file":"chunk-7YGCPMGB.js","sourcesContent":["/**\n * Helpers shared between provider HTTP error mappers (ADR D67).\n *\n * Extracted to dedupe identical logic in `anthropic.ts` and\n * `openai-compatible.ts` — retry-after parsing, raw-body truncation,\n * and metadata assembly are dialect-agnostic.\n *\n * @internal\n */\n\nimport type { ErrorCode, ErrorMetadata } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\n\nconst RAW_MAX_BYTES = 2048;\n\n/**\n * Parse the `Retry-After` header (RFC 7231) into seconds. Both forms are\n * supported: numeric-seconds (`Retry-After: 30`) and HTTP-date\n * (`Retry-After: Wed, 21 Oct 2025 07:28:00 GMT` → seconds until that instant,\n * clamped at 0 for a past date). Garbage / missing header → `undefined`.\n *\n * @internal\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n // HTTP-date form — seconds until the given instant (0 if already elapsed).\n const dateMs = Date.parse(raw);\n if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n *\n * Post T1.1 (secret-redaction-discipline, ADR D68): every error metadata\n * goes through `redactSecrets` before exposure. Note the shape change —\n * pre-T1.1 the function preserved the original `body` shape when ≤2KB;\n * now it always returns a (possibly redacted) string, because redaction\n * coerces non-strings to JSON. Consumers who used to do `err.metadata.raw.foo`\n * must now `JSON.parse(err.metadata.raw)` first — but a workspace-wide\n * grep at T1.1 land time confirmed zero such callers.\n *\n * @internal\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n const truncated = s.length <= RAW_MAX_BYTES ? s : `${s.slice(0, RAW_MAX_BYTES)}…`;\n return redactSecrets(truncated);\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output). Caller passes\n * dialect-specific fields (`provider`, `endpoint`, `code`); shared\n * fields (`statusCode`, `retryAfter`, `raw`) are derived here.\n *\n * @internal\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\n/**\n * D314: extract the provider's request id (`x-request-id` is OpenAI/most;\n * `request-id` is Anthropic). Returns `undefined` when neither is present.\n *\n * @internal\n */\nexport function parseRequestId(headers: Headers | undefined): string | undefined {\n if (headers === undefined) return undefined;\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67).\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { buildErrorMetadata } from \"./shared.js\";\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 400) {\n return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — OpenAI 402 / OpenRouter \"Insufficient credits\" / `insufficient_quota`\n // body code now flow to canonical `quota_exceeded`. Pre-T3.7 we returned\n // `invalid_request` because the ErrorCode union lacked the bucket; T3.7\n // added it. AgentRunError.code (KnownAgentRunErrorCode, post-T1.1) has\n // always carried this value; this fix closes the metadata.code surface.\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(providerId: string, status: number, code: ErrorCode): string {\n return `${providerId} API error: ${code} (HTTP ${status})`;\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { getTracer, noopSpan } from './chunk-K2BQQ445.js';
|
|
2
|
-
import { createSemaphore } from './chunk-
|
|
3
|
-
import { InMemoryTaskStore, getTaskStoreFor, isValidTaskId } from './chunk-
|
|
4
|
-
import { InvalidTaskIdError, TaskNotFoundError } from './chunk-
|
|
5
|
-
import { diag } from './chunk-
|
|
2
|
+
import { createSemaphore } from './chunk-4QZSA2HJ.js';
|
|
3
|
+
import { InMemoryTaskStore, getTaskStoreFor, isValidTaskId } from './chunk-KQRW2GPZ.js';
|
|
4
|
+
import { InvalidTaskIdError, TaskNotFoundError } from './chunk-ZZMZWBR6.js';
|
|
5
|
+
import { diag } from './chunk-XEQ3TM66.js';
|
|
6
6
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
7
7
|
import { randomUUID } from 'crypto';
|
|
8
8
|
|
|
@@ -483,5 +483,5 @@ var subscribe = buildSubscribe({
|
|
|
483
483
|
});
|
|
484
484
|
|
|
485
485
|
export { __getSubscribersCountForTests, __resetTaskRegistryForTests, cancel, configure, emitRunEvent, get, list, submit, subscribe };
|
|
486
|
-
//# sourceMappingURL=chunk-
|
|
487
|
-
//# sourceMappingURL=chunk-
|
|
486
|
+
//# sourceMappingURL=chunk-A46SWMIF.js.map
|
|
487
|
+
//# sourceMappingURL=chunk-A46SWMIF.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/run-events.ts","../src/internal/task/ring-buffer.ts","../src/internal/task/subscribe.ts","../src/internal/task/task-run-event-bridge.ts","../src/internal/task/telemetry.ts","../src/internal/task/registry.ts"],"names":["subscribe"],"mappings":";;;;;;;;;AAmMO,SAAS,YAAA,CAAa,MAAgC,KAAA,EAAuB;AAClF,EAAA,IAAI,SAAS,MAAA,EAAW;AACxB,EAAA,IAAI;AACF,IAAA,IAAA,CAAK,KAAK,CAAA;AAAA,EACZ,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;;;AChMO,IAAM,aAAN,MAAoB;AAAA,EAIzB,YAA6B,GAAA,EAAa;AAAb,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,GAAG,CAAA,IAAK,MAAM,CAAA,EAAG;AACrC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,oDAAA,EAAuD,GAAG,CAAA,CAAE,CAAA;AAAA,IAC9E;AAAA,EACF;AAAA,EAJ6B,GAAA;AAAA,EAHZ,MAAW,EAAC;AAAA,EACrB,SAAA,GAAY,KAAA;AAAA,EAQpB,KAAK,IAAA,EAAe;AAClB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,IAAU,IAAA,CAAK,GAAA,EAAK;AAC/B,MAAA,IAAA,CAAK,IAAI,KAAA,EAAM;AACf,MAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AAAA,IACnB;AACA,IAAA,IAAA,CAAK,GAAA,CAAI,KAAK,IAAI,CAAA;AAAA,EACpB;AAAA,EAEA,KAAA,GAAuE;AACrE,IAAA,OAAO,EAAE,OAAO,IAAA,CAAK,GAAA,CAAI,OA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/**\n * SE2 — typed runtime EVENT stream, ADDITIVE to the `SDKMessage` content stream.\n *\n * `Run.stream()` yields `SDKMessage`s (the conversation content). `RunEvent`s are\n * out-of-band runtime-OBSERVABILITY signals — the model's content is unaffected —\n * delivered opt-in via `SendOptions.onRunEvent`. Discriminate on `type`. Mirrors\n * the Anthropic `SDKMessage`-union approach (rate-limit, permission-denied, task\n * lifecycle, compaction boundary).\n *\n * The union is the forward-compatible CONTRACT (discriminate exhaustively). The\n * runtime EMITS every variant end-to-end: `tool_progress` + `permission_denied`\n * (agent-loop tool-dispatch seam), `rate_limit` (pool-aware LLM client 429 retry),\n * `compact_boundary` (session auto-compaction), and `task_*` (opt-in bridge from a\n * `Task.submit({ onRunEvent })` task's lifecycle). A consumer switching on `type`\n * sees the real signal.\n *\n * @public\n */\nexport type RunEvent =\n | RunToolProgressEvent\n | RunRateLimitEvent\n | RunPermissionDeniedEvent\n | RunTaskStartedEvent\n | RunTaskUpdatedEvent\n | RunTaskCompletedEvent\n | RunCompactBoundaryEvent\n | RunCompactionFallbackEvent\n | RunTripwireEvent\n | RunCompletionCheckEvent\n | RunMcpServerFailedEvent\n | RunMcpServerReadyEvent;\n\n/**\n * theokit#188 — an MCP server was configured but its tools could not be listed, so NONE of its\n * tools exist for this run.\n *\n * The failure was always caught (`safeListTools` returns `[]` so one broken server cannot take the\n * turn down) and always DIAGNOSED — to `diag()`, i.e. the SDK's stderr. Nothing reached the\n * consumer, so a UI listing configured servers could show one as present while every tool it\n * provides had silently vanished. Degrading gracefully is right; degrading INVISIBLY is not.\n *\n * Emitted once per failing server per run, on the same catch path that already had both the name\n * and the reason.\n */\nexport interface RunMcpServerFailedEvent {\n readonly type: \"mcp_server_failed\";\n /** The server as named in the MCP configuration, so the consumer can match it to what it lists. */\n readonly serverName: string;\n /** Why listing failed — a spawn error, a handshake timeout, a protocol error. */\n readonly message: string;\n}\n\n/**\n * usetheokit/theokit#426 — an MCP server came up, and these are the tools it delivered.\n *\n * The sibling of {@link RunMcpServerFailedEvent}, emitted from the same function, on the other\n * branch. Without it a consumer could see what was CONFIGURED and what BROKE, and could not tell a\n * server that came up with twelve tools from one that came up with none — which is exactly the case\n * an operator opens a server-status panel to find. `tools: []` on a healthy server is a real and\n * previously unreportable state.\n *\n * An EVENT rather than a getter, because the state is scoped to the run: with\n * `mcpLifecycle: \"run\"` a server may not exist by the time anyone asks, so a getter would have to\n * answer about something already gone. This says what was true when the run started.\n *\n * Emitted once per successfully-listed server per run.\n */\nexport interface RunMcpServerReadyEvent {\n readonly type: \"mcp_server_ready\";\n /** The server as named in the MCP configuration — the key a consumer already lists it under. */\n readonly serverName: string;\n /**\n * The tool names the server reported, as IT names them.\n *\n * Not the `mcp_<server>_<tool>` form the model sees: that spelling is sanitized for the provider,\n * and a consumer matching it back to a server's own documentation would have to undo the mangling.\n */\n readonly tools: readonly string[];\n}\n\n/**\n * SE24 — a guardrail processor called `abort()`; the run stops with a tripwire.\n * Delivered via {@link SendOptions.onRunEvent} (mirrors the `RunResult.tripwire`\n * surfaced on `wait()`).\n */\nexport interface RunTripwireEvent {\n readonly type: \"tripwire\";\n readonly reason: string;\n readonly processorId: string;\n}\n\n/** A tool call is being dispatched (before its result). */\nexport interface RunToolProgressEvent {\n readonly type: \"tool_progress\";\n readonly toolName: string;\n readonly toolCallId: string;\n}\n\n/** The provider returned a rate-limit (HTTP 429); the loop will back off + retry. */\nexport interface RunRateLimitEvent {\n readonly type: \"rate_limit\";\n /** Retry attempt number (1-based) about to be delayed. */\n readonly attempt: number;\n /** Delay in ms before the retry, when the provider/policy supplied one. */\n readonly retryAfterMs?: number;\n}\n\n/**\n * A tool call was DENIED before dispatch — by the permission gate/plugin (SE1),\n * an operator file-hook `preToolUse`, or the fork tool-whitelist. `source`\n * discriminates which. `toolCallId` joins the event to the tool-call log.\n */\nexport interface RunPermissionDeniedEvent {\n readonly type: \"permission_denied\";\n readonly toolName: string;\n readonly toolCallId: string;\n /** Which layer blocked the call. */\n readonly source: \"plugin\" | \"file_hook\" | \"fork_whitelist\";\n /** The rejection message surfaced to the model. */\n readonly message: string;\n}\n\n/** A background task/subagent started. */\nexport interface RunTaskStartedEvent {\n readonly type: \"task_started\";\n readonly taskId: string;\n readonly description?: string;\n}\n\n/** A background task/subagent changed state. */\nexport interface RunTaskUpdatedEvent {\n readonly type: \"task_updated\";\n readonly taskId: string;\n readonly status: string;\n}\n\n/** A background task/subagent finished. */\nexport interface RunTaskCompletedEvent {\n readonly type: \"task_completed\";\n readonly taskId: string;\n readonly status: \"completed\" | \"failed\" | \"stopped\";\n}\n\n/**\n * SE34 — the per-send completion check (`isTaskComplete`) produced a verdict.\n * Emitted once, after a finished run's reply is judged against\n * {@link SendOptions.completionCheck}. Distinct from `task_completed` (which is\n * background-task/subagent lifecycle). Mirrors {@link RunResult.completionCheck}.\n */\nexport interface RunCompletionCheckEvent {\n readonly type: \"completion_check\";\n readonly complete: boolean;\n readonly reason: string;\n}\n\n/** The conversation crossed a compaction boundary (history was summarized). */\nexport interface RunCompactBoundaryEvent {\n readonly type: \"compact_boundary\";\n readonly trigger: \"manual\" | \"auto\";\n /** Token count before compaction, when known. */\n readonly preTokens?: number;\n}\n\n/**\n * M77 — auto-compaction is budgeting against a FLOOR, because neither the catalog nor the caller\n * supplied a context window for this model.\n *\n * The prior behaviour was to disable auto-compaction entirely and write one line to stderr per\n * process. That is fail-OPEN: the conversation grows until the provider rejects it. This event exists\n * so a surface can say \"I am running without a real budget\" instead of the user discovering it at the\n * moment of failure.\n *\n * Not emitted when the window came from the catalog (the normal path) or from an explicit caller\n * override (the caller already knows).\n */\nexport interface RunCompactionFallbackEvent {\n readonly type: \"compaction_fallback\";\n /** The model whose window is unknown — what the user needs to fix in configuration. */\n readonly model: string;\n /** The floor being budgeted against, after the safety margin. */\n readonly window: number;\n}\n\n/**\n * SE2 — the opt-in sink for {@link RunEvent}s. Supplied via `SendOptions.onRunEvent`.\n * Synchronous + best-effort: a throwing sink must never break the run (the emitter\n * try-catches it), so keep it fast (push to a queue, don't await).\n */\nexport type RunEventSink = (event: RunEvent) => void;\n\n/**\n * SE2 — emit a {@link RunEvent} to an optional sink, swallowing any sink error so\n * observability can never break the run (fail-safe, mirrors the EventBus EC-2\n * contract). No-op when the sink is absent.\n */\nexport function emitRunEvent(sink: RunEventSink | undefined, event: RunEvent): void {\n if (sink === undefined) return;\n try {\n sink(event);\n } catch {\n // best-effort: an observability sink must never break the run.\n }\n}\n","/**\n * Bounded FIFO ring buffer for late-attach replay (ADR D372).\n *\n * Push always succeeds; when the buffer is at capacity the oldest\n * entry is dropped and the `truncated` flag flips to `true`. Drain\n * returns a snapshot + the current truncated flag.\n *\n * @internal\n */\n\nexport class RingBuffer<T> {\n private readonly buf: T[] = [];\n private truncated = false;\n\n constructor(private readonly cap: number) {\n if (!Number.isInteger(cap) || cap < 1) {\n throw new Error(`RingBuffer capacity must be a positive integer, got ${cap}`);\n }\n }\n\n push(item: T): void {\n if (this.buf.length >= this.cap) {\n this.buf.shift();\n this.truncated = true;\n }\n this.buf.push(item);\n }\n\n drain(): { readonly items: readonly T[]; readonly truncated: boolean } {\n return { items: this.buf.slice(), truncated: this.truncated };\n }\n\n size(): number {\n return this.buf.length;\n }\n\n wasTruncated(): boolean {\n return this.truncated;\n }\n}\n","/**\n * `subscribe(id)` — emits the per-task event stream (D372 ring buffer\n * + live tail). The returned AsyncIterable implements `return()` for\n * leak-free cleanup (EC-10).\n *\n * @internal\n */\n\nimport { TaskNotFoundError } from \"../../errors.js\";\nimport { isValidTaskId, type TaskEvent } from \"../../types/task.js\";\nimport type { RingBuffer } from \"./ring-buffer.js\";\n\nexport interface SubscribeDeps {\n getBuffer(id: string): RingBuffer<TaskEvent> | undefined;\n getOrCreateSubscriberSet(id: string): Set<(e: TaskEvent) => void>;\n removeSubscriber(id: string, cb: (e: TaskEvent) => void): void;\n}\n\nfunction isTerminalEvent(event: TaskEvent): boolean {\n return event.type === \"finished\" || event.type === \"errored\" || event.type === \"cancelled\";\n}\n\nfunction drainBuffered(buffer: RingBuffer<TaskEvent>): TaskEvent[] {\n const { items, truncated } = buffer.drain();\n const queue = items.slice();\n if (truncated && queue.length > 0) {\n const first = queue[0];\n if (first !== undefined && first.type === \"submitted\") {\n queue[0] = { ...first, truncated: true } satisfies TaskEvent;\n }\n }\n return queue;\n}\n\nclass TaskIterator implements AsyncIterator<TaskEvent> {\n private readonly queue: TaskEvent[];\n private pendingResolve?: (v: IteratorResult<TaskEvent>) => void;\n private done = false;\n private readonly callback: (e: TaskEvent) => void;\n\n constructor(\n buffer: RingBuffer<TaskEvent>,\n private readonly id: string,\n private readonly deps: SubscribeDeps,\n ) {\n this.queue = drainBuffered(buffer);\n this.callback = (e) => this.deliver(e);\n deps.getOrCreateSubscriberSet(id).add(this.callback);\n }\n\n private deliver(e: TaskEvent): void {\n if (this.done) return;\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: e, done: false });\n } else {\n this.queue.push(e);\n }\n }\n\n private cleanup(): void {\n if (this.done) return;\n this.done = true;\n this.deps.removeSubscriber(this.id, this.callback);\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: undefined, done: true });\n }\n }\n\n private dequeue(): IteratorResult<TaskEvent> | undefined {\n const event = this.queue.shift();\n if (event === undefined) return undefined;\n if (isTerminalEvent(event)) queueMicrotask(() => this.cleanup());\n return { value: event, done: false };\n }\n\n next(): Promise<IteratorResult<TaskEvent>> {\n if (this.done) return Promise.resolve({ value: undefined, done: true });\n const queued = this.dequeue();\n if (queued !== undefined) return Promise.resolve(queued);\n return new Promise((resolve) => {\n this.pendingResolve = resolve;\n });\n }\n\n return(): Promise<IteratorResult<TaskEvent>> {\n this.cleanup();\n return Promise.resolve({ value: undefined, done: true });\n }\n}\n\nexport function buildSubscribe(deps: SubscribeDeps) {\n return function subscribe(id: string): AsyncIterable<TaskEvent> {\n if (!isValidTaskId(id, true)) throw new TaskNotFoundError(id);\n const buffer = deps.getBuffer(id);\n if (buffer === undefined) throw new TaskNotFoundError(id);\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<TaskEvent> {\n return new TaskIterator(buffer, id, deps);\n },\n };\n };\n}\n","/**\n * SE2 — the `TaskEvent` → `task_*` RunEvent bridge for the opt-in `onRunEvent`\n * sink. Extracted from `registry.ts` (a pure, self-contained mapping) to keep\n * the registry within the G8 LoC budget and give the bridge one home.\n *\n * @internal\n */\n\nimport type { RunEvent } from \"../../types/run-events.js\";\nimport type { TaskEvent, TaskKind } from \"../../types/task.js\";\n\n/** Map a `TaskEvent` to a `task_*` RunEvent, or `undefined` when it has no counterpart. */\nexport function taskEventToRunEvent(\n event: TaskEvent,\n taskId: string,\n kind: TaskKind,\n): RunEvent | undefined {\n switch (event.type) {\n case \"started\":\n return { type: \"task_started\", taskId, description: kind };\n case \"progress\":\n return { type: \"task_updated\", taskId, status: \"progress\" };\n case \"finished\":\n return { type: \"task_completed\", taskId, status: \"completed\" };\n case \"errored\":\n return { type: \"task_completed\", taskId, status: \"failed\" };\n case \"cancelled\":\n return { type: \"task_completed\", taskId, status: \"stopped\" };\n default:\n return undefined; // `submitted` (queued) has no RunEvent counterpart\n }\n}\n","/**\n * OTel telemetry for the Task registry (ADR D371).\n *\n * Spans:\n * - `task.submit` — short-lived span around the submit + insert.\n * - `task.transition` — per state transition (attrs: from / to).\n * - `task.cancel` — invoked from `Task.cancel` or via cancelRequested honor.\n *\n * Uses the existing tracer seam (D34); when OTel is absent, every helper\n * returns the shared no-op span. No new peer deps.\n *\n * @internal\n */\n\nimport { getTracer, noopSpan, type SpanLike } from \"../telemetry/tracer-loader.js\";\n\nconst TRACER_NAME = \"@theokit/sdk/task\";\n\nexport function startTaskSubmitSpan(info: { taskId: string; kind: string }): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.submit\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.kind\": info.kind,\n },\n });\n}\n\nexport function startTaskTransitionSpan(info: {\n taskId: string;\n from: string;\n to: string;\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.transition\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.state.from\": info.from,\n \"task.state.to\": info.to,\n },\n });\n}\n\nexport function startTaskCancelSpan(info: {\n taskId: string;\n reason?: string;\n via: \"api\" | \"cancelRequested\";\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.cancel\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.cancel.via\": info.via,\n ...(info.reason !== undefined ? { \"task.cancel.reason\": info.reason } : {}),\n },\n });\n}\n","/**\n * `TaskRegistry` — the singleton coordinating Task submit/list/get/cancel/\n * subscribe. Wraps the pluggable `TaskStore` (D364), the `AsyncSemaphore`\n * (D135 / D369) and a per-task `RingBuffer<TaskEvent>` (D372) for\n * late-attach replay.\n *\n * Edge cases absorbed:\n * - EC-3: work-fn invocation goes through `Promise.resolve().then(...)`\n * so synchronous throws become rejected promises.\n * - EC-4: pre-aborted signal short-circuits to `cancelled` without\n * acquiring a semaphore slot.\n * - EC-7: cross-process cancel via the `cancelRequested` flag on\n * `TaskHandle`. Registry polls at start + each progress event.\n * - EC-9: store-update failures are caught + logged; the event is\n * still emitted so subscribers always observe a terminal event.\n * - EC-10: subscribe iterator implements `return()` for leak-free\n * cleanup.\n * - EC-11: reentrant submit (work-fn calling `Task.submit`) uses an\n * ALS marker to bypass the semaphore queue, avoiding deadlock under\n * low concurrency caps.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport { emitRunEvent } from \"../../types/run-events.js\";\nimport {\n isValidTaskId,\n type TaskCancelResult,\n type TaskEvent,\n type TaskFilter,\n type TaskHandle,\n type TaskKind,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { type AsyncSemaphore, createSemaphore } from \"../runtime/concurrency/async-semaphore.js\";\nimport { RingBuffer } from \"./ring-buffer.js\";\nimport { getTaskStoreFor, InMemoryTaskStore, type TaskStore } from \"./store.js\";\nimport { buildSubscribe } from \"./subscribe.js\";\nimport { taskEventToRunEvent } from \"./task-run-event-bridge.js\";\nimport { startTaskCancelSpan, startTaskSubmitSpan, startTaskTransitionSpan } from \"./telemetry.js\";\n\nconst DEFAULT_CONCURRENCY = 8;\nconst DEFAULT_RETENTION_MS = 60 * 60 * 1000;\nconst EVICTION_INTERVAL_MS = 5 * 60 * 1000;\nconst RING_CAP = 64;\n\n/** EC-11 — ALS flag indicating we are inside a task work-fn. Reentrant submits bypass the semaphore. */\nconst reentryAls = new AsyncLocalStorage<boolean>();\n\nexport interface TaskRegistryOptions {\n readonly store?: TaskStoreOptions;\n readonly maxConcurrent?: number;\n readonly retentionMs?: number;\n}\n\nexport interface TaskWorkContext {\n readonly signal: AbortSignal;\n emit(payload: unknown): void;\n}\n\ntype WorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;\n\ninterface InternalState {\n readonly store: TaskStore;\n readonly semaphore: AsyncSemaphore;\n readonly aborters: Map<string, AbortController>;\n readonly buffers: Map<string, RingBuffer<TaskEvent>>;\n readonly subscribers: Map<string, Set<(e: TaskEvent) => void>>;\n retentionMs: number;\n evictTimer?: NodeJS.Timeout;\n firstSubmitSeen: boolean;\n}\n\nfunction buildState(opts: TaskRegistryOptions): InternalState {\n const store = opts.store === undefined ? new InMemoryTaskStore() : getTaskStoreFor(opts.store);\n return {\n store,\n semaphore: createSemaphore(opts.maxConcurrent ?? DEFAULT_CONCURRENCY),\n aborters: new Map(),\n buffers: new Map(),\n subscribers: new Map(),\n retentionMs: opts.retentionMs ?? DEFAULT_RETENTION_MS,\n firstSubmitSeen: false,\n };\n}\n\nlet state: InternalState = buildState({});\n\nexport function __resetTaskRegistryForTests(): void {\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState({});\n}\n\nexport function __getSubscribersCountForTests(taskId: string): number {\n return state.subscribers.get(taskId)?.size ?? 0;\n}\n\nexport function configure(opts: TaskRegistryOptions): void {\n if (state.firstSubmitSeen) {\n diag(\n \"[task] configure() ignored — registry already in use; reset via __resetTaskRegistryForTests()\\n\",\n );\n return;\n }\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState(opts);\n}\n\nfunction emitToSubscribers(taskId: string, event: TaskEvent): void {\n const buffer = state.buffers.get(taskId);\n if (buffer !== undefined) buffer.push(event);\n const subs = state.subscribers.get(taskId);\n if (subs === undefined) return;\n for (const cb of subs) {\n try {\n cb(event);\n } catch (err) {\n diag(`[task] subscriber threw: ${(err as Error).message}\\n`);\n }\n }\n}\n\nasync function safeUpdate(\n taskId: string,\n mutate: (h: TaskHandle) => TaskHandle,\n): Promise<TaskHandle | undefined> {\n try {\n return await state.store.update(taskId, mutate);\n } catch (err) {\n // EC-9: store failure should not swallow the event.\n diag(`[task] store.update failed for ${taskId}: ${(err as Error).message}\\n`);\n return undefined;\n }\n}\n\nfunction startEvictTimerIfNeeded(): void {\n if (state.evictTimer !== undefined) return;\n state.evictTimer = setInterval(() => {\n const cutoff = Date.now() - state.retentionMs;\n void state.store\n .evictTerminalOlderThan(cutoff)\n .then((count) => {\n if (count === 0) return;\n // Also drop buffers + subscribers for evicted tasks. We don't\n // know which ones were dropped — clean up any task whose store\n // entry is gone.\n for (const id of state.buffers.keys()) {\n void state.store.get(id).then((h) => {\n if (h === undefined) {\n state.buffers.delete(id);\n state.subscribers.delete(id);\n state.aborters.delete(id);\n }\n });\n }\n })\n .catch(() => {\n /* swallow timer errors */\n });\n }, EVICTION_INTERVAL_MS).unref();\n}\n\nfunction buildSubmittedEvent(handle: TaskHandle): TaskEvent {\n return {\n type: \"submitted\",\n taskId: handle.id,\n kind: handle.kind,\n submittedAt: handle.submittedAt,\n ...(handle.meta !== undefined ? { meta: handle.meta } : {}),\n };\n}\n\nasync function shortCircuitAborted(handle: TaskHandle, signal: AbortSignal): Promise<TaskHandle> {\n // EC-4: pre-aborted signal — skip queue/semaphore.\n const cancelled: TaskHandle = {\n ...handle,\n state: \"cancelled\",\n cancelledAt: Date.now(),\n };\n await state.store.insert(cancelled);\n state.buffers.set(handle.id, new RingBuffer(RING_CAP));\n emitToSubscribers(handle.id, buildSubmittedEvent(cancelled));\n emitToSubscribers(handle.id, {\n type: \"cancelled\",\n taskId: handle.id,\n cancelledAt: cancelled.cancelledAt ?? Date.now(),\n reason: signal.reason instanceof Error ? signal.reason.message : \"pre-aborted\",\n });\n return cancelled;\n}\n\nasync function transition<T extends TaskState>(\n taskId: string,\n next: T,\n patch: Partial<TaskHandle>,\n): Promise<void> {\n const before = await state.store.get(taskId);\n const span = startTaskTransitionSpan({\n taskId,\n from: before?.state ?? \"unknown\",\n to: next,\n });\n try {\n await safeUpdate(taskId, (h) => ({ ...h, state: next, ...patch }));\n } finally {\n span.end();\n }\n}\n\ninterface SubmitInternal<T> {\n readonly kind: TaskKind;\n readonly work: WorkFn<T>;\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n readonly signal?: AbortSignal;\n /** When true (adapter-internal), the validator allows reserved prefixes. */\n readonly allowReservedPrefix?: boolean;\n /** SE2 — forward this task's lifecycle to the run-event sink as `task_*` RunEvents. */\n readonly onRunEvent?: import(\"../../types/run-events.js\").RunEventSink;\n}\n\nasync function buildAndInsertQueued(\n internal: SubmitInternal<unknown>,\n resolvedId: string,\n): Promise<TaskHandle> {\n const submittedAt = Date.now();\n const handle: TaskHandle = {\n id: resolvedId,\n kind: internal.kind,\n state: \"queued\",\n submittedAt,\n ...(internal.meta !== undefined ? { meta: internal.meta } : {}),\n };\n await state.store.insert(handle);\n state.buffers.set(resolvedId, new RingBuffer(RING_CAP));\n emitToSubscribers(resolvedId, buildSubmittedEvent(handle));\n return handle;\n}\n\nfunction resolveIdInternal(internal: SubmitInternal<unknown>): string {\n if (internal.id === undefined) return randomUUID();\n if (!isValidTaskId(internal.id, internal.allowReservedPrefix ?? false)) {\n throw new InvalidTaskIdError(`invalid task id: ${internal.id}`, internal.id);\n }\n return internal.id;\n}\n\nasync function runWorkAndFinalize<T>(\n taskId: string,\n aborter: AbortController,\n work: WorkFn<T>,\n): Promise<void> {\n const ctx: TaskWorkContext = {\n signal: aborter.signal,\n emit(payload) {\n // EC-7: check cancelRequested at every progress checkpoint.\n void checkCancelRequestedAt(taskId, aborter);\n emitToSubscribers(taskId, {\n type: \"progress\",\n taskId,\n at: Date.now(),\n payload,\n });\n },\n };\n\n try {\n const result = await reentryAls.run(true, () => Promise.resolve().then(() => work(ctx)));\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const finishedAt = Date.now();\n await transition(taskId, \"finished\", { finishedAt, result });\n emitToSubscribers(taskId, { type: \"finished\", taskId, finishedAt, result });\n } catch (err) {\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const erroredAt = Date.now();\n const error =\n err instanceof Error\n ? { code: (err as { code?: string }).code ?? \"work_threw\", message: err.message }\n : { code: \"work_threw\", message: String(err) };\n await transition(taskId, \"error\", { erroredAt, error });\n emitToSubscribers(taskId, { type: \"errored\", taskId, erroredAt, error });\n }\n}\n\nasync function checkCancelRequestedAt(taskId: string, aborter: AbortController): Promise<void> {\n if (aborter.signal.aborted) return;\n try {\n const handle = await state.store.get(taskId);\n if (handle?.cancelRequested === true) {\n aborter.abort(\"cancelRequested\");\n }\n } catch {\n /* ignore — best-effort poll */\n }\n}\n\nasync function acquireSlot(): Promise<() => void> {\n if (reentryAls.getStore() === true) {\n // EC-11: reentrant submit bypasses the queue.\n return () => {\n /* no-op */\n };\n }\n return state.semaphore.acquire();\n}\n\n/**\n * Submit a task. Validates id (D368, EC-5 via allowReservedPrefix),\n * handles pre-aborted signals (EC-4), enforces single-flight by id\n * (D367), runs work under semaphore (D369/EC-11 reentrant bypass),\n * and produces the canonical event stream (D366).\n */\nexport async function submit<T>(internal: SubmitInternal<T>): Promise<TaskHandle> {\n state.firstSubmitSeen = true;\n startEvictTimerIfNeeded();\n\n const resolvedId = resolveIdInternal(internal);\n // SE2 — bridge the task lifecycle to the caller's run-event sink (opt-in).\n if (internal.onRunEvent !== undefined) {\n const sink = internal.onRunEvent;\n const kind = internal.kind;\n const subs = state.subscribers.get(resolvedId) ?? new Set();\n subs.add((e: TaskEvent) => {\n const runEvent = taskEventToRunEvent(e, resolvedId, kind);\n if (runEvent !== undefined) emitRunEvent(sink, runEvent);\n });\n state.subscribers.set(resolvedId, subs);\n }\n const submitSpan = startTaskSubmitSpan({ taskId: resolvedId, kind: internal.kind });\n\n // D367 single-flight.\n const existing = await state.store.get(resolvedId);\n if (existing !== undefined) {\n submitSpan.end();\n return existing;\n }\n\n const queuedHandle = await buildAndInsertQueued(internal, resolvedId);\n submitSpan.end();\n\n // EC-4: pre-aborted signal — short-circuit.\n if (internal.signal?.aborted === true) {\n return shortCircuitAborted(queuedHandle, internal.signal);\n }\n\n const aborter = new AbortController();\n state.aborters.set(resolvedId, aborter);\n if (internal.signal !== undefined) {\n internal.signal.addEventListener(\"abort\", () => aborter.abort(internal.signal?.reason), {\n once: true,\n });\n }\n\n // Fire and forget the actual run; the returned handle is the queued one.\n const release = await acquireSlot();\n void (async () => {\n try {\n // Check cancelRequested before starting (EC-7).\n await checkCancelRequestedAt(resolvedId, aborter);\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(resolvedId, \"cancelled\", { cancelledAt });\n emitToSubscribers(resolvedId, { type: \"cancelled\", taskId: resolvedId, cancelledAt });\n return;\n }\n const startedAt = Date.now();\n await transition(resolvedId, \"running\", { startedAt });\n emitToSubscribers(resolvedId, { type: \"started\", taskId: resolvedId, startedAt });\n await runWorkAndFinalize(resolvedId, aborter, internal.work as WorkFn<unknown>);\n } finally {\n release();\n state.aborters.delete(resolvedId);\n }\n })();\n\n return queuedHandle;\n}\n\nexport async function list(filter: TaskFilter = {}): Promise<TaskHandle[]> {\n return state.store.list(filter);\n}\n\nexport async function get(id: string): Promise<TaskHandle | undefined> {\n if (!isValidTaskId(id, true)) return undefined;\n return state.store.get(id);\n}\n\nexport async function cancel(id: string, reason?: string): Promise<TaskCancelResult> {\n if (!isValidTaskId(id, true)) return { cancelled: false, alreadyTerminal: false };\n const handle = await state.store.get(id);\n if (handle === undefined) return { cancelled: false, alreadyTerminal: false };\n if (handle.state === \"finished\" || handle.state === \"error\" || handle.state === \"cancelled\") {\n return { cancelled: false, alreadyTerminal: true };\n }\n const span = startTaskCancelSpan({\n taskId: id,\n ...(reason !== undefined ? { reason } : {}),\n via: \"api\",\n });\n try {\n return await cancelInternal(id, handle.state, reason);\n } finally {\n span.end();\n }\n}\n\nasync function cancelInternal(\n id: string,\n currentState: TaskState,\n reason?: string,\n): Promise<TaskCancelResult> {\n if (currentState === \"queued\") {\n const cancelledAt = Date.now();\n await transition(id, \"cancelled\", { cancelledAt });\n emitToSubscribers(id, {\n type: \"cancelled\",\n taskId: id,\n cancelledAt,\n ...(reason !== undefined ? { reason } : {}),\n });\n state.aborters.delete(id);\n return { cancelled: true, alreadyTerminal: false };\n }\n // running: trigger AbortController; runWorkAndFinalize handles the transition.\n const aborter = state.aborters.get(id);\n if (aborter !== undefined) aborter.abort(reason ?? \"cancelled\");\n return { cancelled: true, alreadyTerminal: false };\n}\n\nexport const subscribe = buildSubscribe({\n getBuffer: (id) => state.buffers.get(id),\n getOrCreateSubscriberSet: (id) => {\n let subs = state.subscribers.get(id);\n if (subs === undefined) {\n subs = new Set();\n state.subscribers.set(id, subs);\n }\n return subs;\n },\n removeSubscriber: (id, cb) => {\n const set = state.subscribers.get(id);\n set?.delete(cb);\n if (set !== undefined && set.size === 0) state.subscribers.delete(id);\n },\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/run-events.ts","../src/internal/task/ring-buffer.ts","../src/internal/task/subscribe.ts","../src/internal/task/task-run-event-bridge.ts","../src/internal/task/telemetry.ts","../src/internal/task/registry.ts"],"names":["subscribe"],"mappings":";;;;;;;;;AAmMO,SAAS,YAAA,CAAa,MAAgC,KAAA,EAAuB;AAClF,EAAA,IAAI,SAAS,MAAA,EAAW;AACxB,EAAA,IAAI;AACF,IAAA,IAAA,CAAK,KAAK,CAAA;AAAA,EACZ,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;;;AChMO,IAAM,aAAN,MAAoB;AAAA,EAIzB,YAA6B,GAAA,EAAa;AAAb,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,GAAG,CAAA,IAAK,MAAM,CAAA,EAAG;AACrC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,oDAAA,EAAuD,GAAG,CAAA,CAAE,CAAA;AAAA,IAC9E;AAAA,EACF;AAAA,EAJ6B,GAAA;AAAA,EAHZ,MAAW,EAAC;AAAA,EACrB,SAAA,GAAY,KAAA;AAAA,EAQpB,KAAK,IAAA,EAAe;AAClB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,IAAU,IAAA,CAAK,GAAA,EAAK;AAC/B,MAAA,IAAA,CAAK,IAAI,KAAA,EAAM;AACf,MAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AAAA,IACnB;AACA,IAAA,IAAA,CAAK,GAAA,CAAI,KAAK,IAAI,CAAA;AAAA,EACpB;AAAA,EAEA,KAAA,GAAuE;AACrE,IAAA,OAAO,EAAE,OAAO,IAAA,CAAK,GAAA,CAAI,OAAM,EAAG,SAAA,EAAW,KAAK,SAAA,EAAU;AAAA,EAC9D;AAAA,EAEA,IAAA,GAAe;AACb,IAAA,OAAO,K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AA,CAAM,QAAA,CAAS,OAAO,EAAE,CAAA;AACxB,IAAA,OAAO,EAAE,SAAA,EAAW,IAAA,EAAM,eAAA,EAAiB,KAAA,EAAM;AAAA,EACnD;AAEA,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,QAAA,CAAS,GAAA,CAAI,EAAE,CAAA;AACrC,EAAA,IAAI,OAAA,KAAY,MAAA,EAAW,OAAA,CAAQ,KAAA,CAAM,UAAU,WAAW,CAAA;AAC9D,EAAA,OAAO,EAAE,SAAA,EAAW,IAAA,EAAM,eAAA,EAAiB,KAAA,EAAM;AACnD;AAEO,IAAM,YAAY,cAAA,CAAe;AAAA,EACtC,WAAW,CAAC,EAAA,KAAO,KAAA,CAAM,OAAA,CAAQ,IAAI,EAAE,CAAA;AAAA,EACvC,wBAAA,EAA0B,CAAC,EAAA,KAAO;AAChC,IAAA,IAAI,IAAA,GAAO,KAAA,CAAM,WAAA,CAAY,GAAA,CAAI,EAAE,CAAA;AACnC,IAAA,IAAI,SAAS,MAAA,EAAW;AACtB,MAAA,IAAA,uBAAW,GAAA,EAAI;AACf,MAAA,KAAA,CAAM,WAAA,CAAY,GAAA,CAAI,EAAA,EAAI,IAAI,CAAA;AAAA,IAChC;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AAAA,EACA,gBAAA,EAAkB,CAAC,EAAA,EAAI,EAAA,KAAO;AAC5B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,WAAA,CAAY,GAAA,CAAI,EAAE,CAAA;AACpC,IAAA,GAAA,EAAK,OAAO,EAAE,CAAA;AACd,IAAA,IAAI,GAAA,KAAQ,UAAa,GAAA,CAAI,IAAA,KAAS,GAAG,KAAA,CAAM,WAAA,CAAY,OAAO,EAAE,CAAA;AAAA,EACtE;AACF,CAAC","file":"chunk-A46SWMIF.js","sourcesContent":["/**\n * SE2 — typed runtime EVENT stream, ADDITIVE to the `SDKMessage` content stream.\n *\n * `Run.stream()` yields `SDKMessage`s (the conversation content). `RunEvent`s are\n * out-of-band runtime-OBSERVABILITY signals — the model's content is unaffected —\n * delivered opt-in via `SendOptions.onRunEvent`. Discriminate on `type`. Mirrors\n * the Anthropic `SDKMessage`-union approach (rate-limit, permission-denied, task\n * lifecycle, compaction boundary).\n *\n * The union is the forward-compatible CONTRACT (discriminate exhaustively). The\n * runtime EMITS every variant end-to-end: `tool_progress` + `permission_denied`\n * (agent-loop tool-dispatch seam), `rate_limit` (pool-aware LLM client 429 retry),\n * `compact_boundary` (session auto-compaction), and `task_*` (opt-in bridge from a\n * `Task.submit({ onRunEvent })` task's lifecycle). A consumer switching on `type`\n * sees the real signal.\n *\n * @public\n */\nexport type RunEvent =\n | RunToolProgressEvent\n | RunRateLimitEvent\n | RunPermissionDeniedEvent\n | RunTaskStartedEvent\n | RunTaskUpdatedEvent\n | RunTaskCompletedEvent\n | RunCompactBoundaryEvent\n | RunCompactionFallbackEvent\n | RunTripwireEvent\n | RunCompletionCheckEvent\n | RunMcpServerFailedEvent\n | RunMcpServerReadyEvent;\n\n/**\n * theokit#188 — an MCP server was configured but its tools could not be listed, so NONE of its\n * tools exist for this run.\n *\n * The failure was always caught (`safeListTools` returns `[]` so one broken server cannot take the\n * turn down) and always DIAGNOSED — to `diag()`, i.e. the SDK's stderr. Nothing reached the\n * consumer, so a UI listing configured servers could show one as present while every tool it\n * provides had silently vanished. Degrading gracefully is right; degrading INVISIBLY is not.\n *\n * Emitted once per failing server per run, on the same catch path that already had both the name\n * and the reason.\n */\nexport interface RunMcpServerFailedEvent {\n readonly type: \"mcp_server_failed\";\n /** The server as named in the MCP configuration, so the consumer can match it to what it lists. */\n readonly serverName: string;\n /** Why listing failed — a spawn error, a handshake timeout, a protocol error. */\n readonly message: string;\n}\n\n/**\n * usetheokit/theokit#426 — an MCP server came up, and these are the tools it delivered.\n *\n * The sibling of {@link RunMcpServerFailedEvent}, emitted from the same function, on the other\n * branch. Without it a consumer could see what was CONFIGURED and what BROKE, and could not tell a\n * server that came up with twelve tools from one that came up with none — which is exactly the case\n * an operator opens a server-status panel to find. `tools: []` on a healthy server is a real and\n * previously unreportable state.\n *\n * An EVENT rather than a getter, because the state is scoped to the run: with\n * `mcpLifecycle: \"run\"` a server may not exist by the time anyone asks, so a getter would have to\n * answer about something already gone. This says what was true when the run started.\n *\n * Emitted once per successfully-listed server per run.\n */\nexport interface RunMcpServerReadyEvent {\n readonly type: \"mcp_server_ready\";\n /** The server as named in the MCP configuration — the key a consumer already lists it under. */\n readonly serverName: string;\n /**\n * The tool names the server reported, as IT names them.\n *\n * Not the `mcp_<server>_<tool>` form the model sees: that spelling is sanitized for the provider,\n * and a consumer matching it back to a server's own documentation would have to undo the mangling.\n */\n readonly tools: readonly string[];\n}\n\n/**\n * SE24 — a guardrail processor called `abort()`; the run stops with a tripwire.\n * Delivered via {@link SendOptions.onRunEvent} (mirrors the `RunResult.tripwire`\n * surfaced on `wait()`).\n */\nexport interface RunTripwireEvent {\n readonly type: \"tripwire\";\n readonly reason: string;\n readonly processorId: string;\n}\n\n/** A tool call is being dispatched (before its result). */\nexport interface RunToolProgressEvent {\n readonly type: \"tool_progress\";\n readonly toolName: string;\n readonly toolCallId: string;\n}\n\n/** The provider returned a rate-limit (HTTP 429); the loop will back off + retry. */\nexport interface RunRateLimitEvent {\n readonly type: \"rate_limit\";\n /** Retry attempt number (1-based) about to be delayed. */\n readonly attempt: number;\n /** Delay in ms before the retry, when the provider/policy supplied one. */\n readonly retryAfterMs?: number;\n}\n\n/**\n * A tool call was DENIED before dispatch — by the permission gate/plugin (SE1),\n * an operator file-hook `preToolUse`, or the fork tool-whitelist. `source`\n * discriminates which. `toolCallId` joins the event to the tool-call log.\n */\nexport interface RunPermissionDeniedEvent {\n readonly type: \"permission_denied\";\n readonly toolName: string;\n readonly toolCallId: string;\n /** Which layer blocked the call. */\n readonly source: \"plugin\" | \"file_hook\" | \"fork_whitelist\";\n /** The rejection message surfaced to the model. */\n readonly message: string;\n}\n\n/** A background task/subagent started. */\nexport interface RunTaskStartedEvent {\n readonly type: \"task_started\";\n readonly taskId: string;\n readonly description?: string;\n}\n\n/** A background task/subagent changed state. */\nexport interface RunTaskUpdatedEvent {\n readonly type: \"task_updated\";\n readonly taskId: string;\n readonly status: string;\n}\n\n/** A background task/subagent finished. */\nexport interface RunTaskCompletedEvent {\n readonly type: \"task_completed\";\n readonly taskId: string;\n readonly status: \"completed\" | \"failed\" | \"stopped\";\n}\n\n/**\n * SE34 — the per-send completion check (`isTaskComplete`) produced a verdict.\n * Emitted once, after a finished run's reply is judged against\n * {@link SendOptions.completionCheck}. Distinct from `task_completed` (which is\n * background-task/subagent lifecycle). Mirrors {@link RunResult.completionCheck}.\n */\nexport interface RunCompletionCheckEvent {\n readonly type: \"completion_check\";\n readonly complete: boolean;\n readonly reason: string;\n}\n\n/** The conversation crossed a compaction boundary (history was summarized). */\nexport interface RunCompactBoundaryEvent {\n readonly type: \"compact_boundary\";\n readonly trigger: \"manual\" | \"auto\";\n /** Token count before compaction, when known. */\n readonly preTokens?: number;\n}\n\n/**\n * M77 — auto-compaction is budgeting against a FLOOR, because neither the catalog nor the caller\n * supplied a context window for this model.\n *\n * The prior behaviour was to disable auto-compaction entirely and write one line to stderr per\n * process. That is fail-OPEN: the conversation grows until the provider rejects it. This event exists\n * so a surface can say \"I am running without a real budget\" instead of the user discovering it at the\n * moment of failure.\n *\n * Not emitted when the window came from the catalog (the normal path) or from an explicit caller\n * override (the caller already knows).\n */\nexport interface RunCompactionFallbackEvent {\n readonly type: \"compaction_fallback\";\n /** The model whose window is unknown — what the user needs to fix in configuration. */\n readonly model: string;\n /** The floor being budgeted against, after the safety margin. */\n readonly window: number;\n}\n\n/**\n * SE2 — the opt-in sink for {@link RunEvent}s. Supplied via `SendOptions.onRunEvent`.\n * Synchronous + best-effort: a throwing sink must never break the run (the emitter\n * try-catches it), so keep it fast (push to a queue, don't await).\n */\nexport type RunEventSink = (event: RunEvent) => void;\n\n/**\n * SE2 — emit a {@link RunEvent} to an optional sink, swallowing any sink error so\n * observability can never break the run (fail-safe, mirrors the EventBus EC-2\n * contract). No-op when the sink is absent.\n */\nexport function emitRunEvent(sink: RunEventSink | undefined, event: RunEvent): void {\n if (sink === undefined) return;\n try {\n sink(event);\n } catch {\n // best-effort: an observability sink must never break the run.\n }\n}\n","/**\n * Bounded FIFO ring buffer for late-attach replay (ADR D372).\n *\n * Push always succeeds; when the buffer is at capacity the oldest\n * entry is dropped and the `truncated` flag flips to `true`. Drain\n * returns a snapshot + the current truncated flag.\n *\n * @internal\n */\n\nexport class RingBuffer<T> {\n private readonly buf: T[] = [];\n private truncated = false;\n\n constructor(private readonly cap: number) {\n if (!Number.isInteger(cap) || cap < 1) {\n throw new Error(`RingBuffer capacity must be a positive integer, got ${cap}`);\n }\n }\n\n push(item: T): void {\n if (this.buf.length >= this.cap) {\n this.buf.shift();\n this.truncated = true;\n }\n this.buf.push(item);\n }\n\n drain(): { readonly items: readonly T[]; readonly truncated: boolean } {\n return { items: this.buf.slice(), truncated: this.truncated };\n }\n\n size(): number {\n return this.buf.length;\n }\n\n wasTruncated(): boolean {\n return this.truncated;\n }\n}\n","/**\n * `subscribe(id)` — emits the per-task event stream (D372 ring buffer\n * + live tail). The returned AsyncIterable implements `return()` for\n * leak-free cleanup (EC-10).\n *\n * @internal\n */\n\nimport { TaskNotFoundError } from \"../../errors.js\";\nimport { isValidTaskId, type TaskEvent } from \"../../types/task.js\";\nimport type { RingBuffer } from \"./ring-buffer.js\";\n\nexport interface SubscribeDeps {\n getBuffer(id: string): RingBuffer<TaskEvent> | undefined;\n getOrCreateSubscriberSet(id: string): Set<(e: TaskEvent) => void>;\n removeSubscriber(id: string, cb: (e: TaskEvent) => void): void;\n}\n\nfunction isTerminalEvent(event: TaskEvent): boolean {\n return event.type === \"finished\" || event.type === \"errored\" || event.type === \"cancelled\";\n}\n\nfunction drainBuffered(buffer: RingBuffer<TaskEvent>): TaskEvent[] {\n const { items, truncated } = buffer.drain();\n const queue = items.slice();\n if (truncated && queue.length > 0) {\n const first = queue[0];\n if (first !== undefined && first.type === \"submitted\") {\n queue[0] = { ...first, truncated: true } satisfies TaskEvent;\n }\n }\n return queue;\n}\n\nclass TaskIterator implements AsyncIterator<TaskEvent> {\n private readonly queue: TaskEvent[];\n private pendingResolve?: (v: IteratorResult<TaskEvent>) => void;\n private done = false;\n private readonly callback: (e: TaskEvent) => void;\n\n constructor(\n buffer: RingBuffer<TaskEvent>,\n private readonly id: string,\n private readonly deps: SubscribeDeps,\n ) {\n this.queue = drainBuffered(buffer);\n this.callback = (e) => this.deliver(e);\n deps.getOrCreateSubscriberSet(id).add(this.callback);\n }\n\n private deliver(e: TaskEvent): void {\n if (this.done) return;\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: e, done: false });\n } else {\n this.queue.push(e);\n }\n }\n\n private cleanup(): void {\n if (this.done) return;\n this.done = true;\n this.deps.removeSubscriber(this.id, this.callback);\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: undefined, done: true });\n }\n }\n\n private dequeue(): IteratorResult<TaskEvent> | undefined {\n const event = this.queue.shift();\n if (event === undefined) return undefined;\n if (isTerminalEvent(event)) queueMicrotask(() => this.cleanup());\n return { value: event, done: false };\n }\n\n next(): Promise<IteratorResult<TaskEvent>> {\n if (this.done) return Promise.resolve({ value: undefined, done: true });\n const queued = this.dequeue();\n if (queued !== undefined) return Promise.resolve(queued);\n return new Promise((resolve) => {\n this.pendingResolve = resolve;\n });\n }\n\n return(): Promise<IteratorResult<TaskEvent>> {\n this.cleanup();\n return Promise.resolve({ value: undefined, done: true });\n }\n}\n\nexport function buildSubscribe(deps: SubscribeDeps) {\n return function subscribe(id: string): AsyncIterable<TaskEvent> {\n if (!isValidTaskId(id, true)) throw new TaskNotFoundError(id);\n const buffer = deps.getBuffer(id);\n if (buffer === undefined) throw new TaskNotFoundError(id);\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<TaskEvent> {\n return new TaskIterator(buffer, id, deps);\n },\n };\n };\n}\n","/**\n * SE2 — the `TaskEvent` → `task_*` RunEvent bridge for the opt-in `onRunEvent`\n * sink. Extracted from `registry.ts` (a pure, self-contained mapping) to keep\n * the registry within the G8 LoC budget and give the bridge one home.\n *\n * @internal\n */\n\nimport type { RunEvent } from \"../../types/run-events.js\";\nimport type { TaskEvent, TaskKind } from \"../../types/task.js\";\n\n/** Map a `TaskEvent` to a `task_*` RunEvent, or `undefined` when it has no counterpart. */\nexport function taskEventToRunEvent(\n event: TaskEvent,\n taskId: string,\n kind: TaskKind,\n): RunEvent | undefined {\n switch (event.type) {\n case \"started\":\n return { type: \"task_started\", taskId, description: kind };\n case \"progress\":\n return { type: \"task_updated\", taskId, status: \"progress\" };\n case \"finished\":\n return { type: \"task_completed\", taskId, status: \"completed\" };\n case \"errored\":\n return { type: \"task_completed\", taskId, status: \"failed\" };\n case \"cancelled\":\n return { type: \"task_completed\", taskId, status: \"stopped\" };\n default:\n return undefined; // `submitted` (queued) has no RunEvent counterpart\n }\n}\n","/**\n * OTel telemetry for the Task registry (ADR D371).\n *\n * Spans:\n * - `task.submit` — short-lived span around the submit + insert.\n * - `task.transition` — per state transition (attrs: from / to).\n * - `task.cancel` — invoked from `Task.cancel` or via cancelRequested honor.\n *\n * Uses the existing tracer seam (D34); when OTel is absent, every helper\n * returns the shared no-op span. No new peer deps.\n *\n * @internal\n */\n\nimport { getTracer, noopSpan, type SpanLike } from \"../telemetry/tracer-loader.js\";\n\nconst TRACER_NAME = \"@theokit/sdk/task\";\n\nexport function startTaskSubmitSpan(info: { taskId: string; kind: string }): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.submit\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.kind\": info.kind,\n },\n });\n}\n\nexport function startTaskTransitionSpan(info: {\n taskId: string;\n from: string;\n to: string;\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.transition\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.state.from\": info.from,\n \"task.state.to\": info.to,\n },\n });\n}\n\nexport function startTaskCancelSpan(info: {\n taskId: string;\n reason?: string;\n via: \"api\" | \"cancelRequested\";\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.cancel\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.cancel.via\": info.via,\n ...(info.reason !== undefined ? { \"task.cancel.reason\": info.reason } : {}),\n },\n });\n}\n","/**\n * `TaskRegistry` — the singleton coordinating Task submit/list/get/cancel/\n * subscribe. Wraps the pluggable `TaskStore` (D364), the `AsyncSemaphore`\n * (D135 / D369) and a per-task `RingBuffer<TaskEvent>` (D372) for\n * late-attach replay.\n *\n * Edge cases absorbed:\n * - EC-3: work-fn invocation goes through `Promise.resolve().then(...)`\n * so synchronous throws become rejected promises.\n * - EC-4: pre-aborted signal short-circuits to `cancelled` without\n * acquiring a semaphore slot.\n * - EC-7: cross-process cancel via the `cancelRequested` flag on\n * `TaskHandle`. Registry polls at start + each progress event.\n * - EC-9: store-update failures are caught + logged; the event is\n * still emitted so subscribers always observe a terminal event.\n * - EC-10: subscribe iterator implements `return()` for leak-free\n * cleanup.\n * - EC-11: reentrant submit (work-fn calling `Task.submit`) uses an\n * ALS marker to bypass the semaphore queue, avoiding deadlock under\n * low concurrency caps.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport { emitRunEvent } from \"../../types/run-events.js\";\nimport {\n isValidTaskId,\n type TaskCancelResult,\n type TaskEvent,\n type TaskFilter,\n type TaskHandle,\n type TaskKind,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { type AsyncSemaphore, createSemaphore } from \"../runtime/concurrency/async-semaphore.js\";\nimport { RingBuffer } from \"./ring-buffer.js\";\nimport { getTaskStoreFor, InMemoryTaskStore, type TaskStore } from \"./store.js\";\nimport { buildSubscribe } from \"./subscribe.js\";\nimport { taskEventToRunEvent } from \"./task-run-event-bridge.js\";\nimport { startTaskCancelSpan, startTaskSubmitSpan, startTaskTransitionSpan } from \"./telemetry.js\";\n\nconst DEFAULT_CONCURRENCY = 8;\nconst DEFAULT_RETENTION_MS = 60 * 60 * 1000;\nconst EVICTION_INTERVAL_MS = 5 * 60 * 1000;\nconst RING_CAP = 64;\n\n/** EC-11 — ALS flag indicating we are inside a task work-fn. Reentrant submits bypass the semaphore. */\nconst reentryAls = new AsyncLocalStorage<boolean>();\n\nexport interface TaskRegistryOptions {\n readonly store?: TaskStoreOptions;\n readonly maxConcurrent?: number;\n readonly retentionMs?: number;\n}\n\nexport interface TaskWorkContext {\n readonly signal: AbortSignal;\n emit(payload: unknown): void;\n}\n\ntype WorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;\n\ninterface InternalState {\n readonly store: TaskStore;\n readonly semaphore: AsyncSemaphore;\n readonly aborters: Map<string, AbortController>;\n readonly buffers: Map<string, RingBuffer<TaskEvent>>;\n readonly subscribers: Map<string, Set<(e: TaskEvent) => void>>;\n retentionMs: number;\n evictTimer?: NodeJS.Timeout;\n firstSubmitSeen: boolean;\n}\n\nfunction buildState(opts: TaskRegistryOptions): InternalState {\n const store = opts.store === undefined ? new InMemoryTaskStore() : getTaskStoreFor(opts.store);\n return {\n store,\n semaphore: createSemaphore(opts.maxConcurrent ?? DEFAULT_CONCURRENCY),\n aborters: new Map(),\n buffers: new Map(),\n subscribers: new Map(),\n retentionMs: opts.retentionMs ?? DEFAULT_RETENTION_MS,\n firstSubmitSeen: false,\n };\n}\n\nlet state: InternalState = buildState({});\n\nexport function __resetTaskRegistryForTests(): void {\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState({});\n}\n\nexport function __getSubscribersCountForTests(taskId: string): number {\n return state.subscribers.get(taskId)?.size ?? 0;\n}\n\nexport function configure(opts: TaskRegistryOptions): void {\n if (state.firstSubmitSeen) {\n diag(\n \"[task] configure() ignored — registry already in use; reset via __resetTaskRegistryForTests()\\n\",\n );\n return;\n }\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState(opts);\n}\n\nfunction emitToSubscribers(taskId: string, event: TaskEvent): void {\n const buffer = state.buffers.get(taskId);\n if (buffer !== undefined) buffer.push(event);\n const subs = state.subscribers.get(taskId);\n if (subs === undefined) return;\n for (const cb of subs) {\n try {\n cb(event);\n } catch (err) {\n diag(`[task] subscriber threw: ${(err as Error).message}\\n`);\n }\n }\n}\n\nasync function safeUpdate(\n taskId: string,\n mutate: (h: TaskHandle) => TaskHandle,\n): Promise<TaskHandle | undefined> {\n try {\n return await state.store.update(taskId, mutate);\n } catch (err) {\n // EC-9: store failure should not swallow the event.\n diag(`[task] store.update failed for ${taskId}: ${(err as Error).message}\\n`);\n return undefined;\n }\n}\n\nfunction startEvictTimerIfNeeded(): void {\n if (state.evictTimer !== undefined) return;\n state.evictTimer = setInterval(() => {\n const cutoff = Date.now() - state.retentionMs;\n void state.store\n .evictTerminalOlderThan(cutoff)\n .then((count) => {\n if (count === 0) return;\n // Also drop buffers + subscribers for evicted tasks. We don't\n // know which ones were dropped — clean up any task whose store\n // entry is gone.\n for (const id of state.buffers.keys()) {\n void state.store.get(id).then((h) => {\n if (h === undefined) {\n state.buffers.delete(id);\n state.subscribers.delete(id);\n state.aborters.delete(id);\n }\n });\n }\n })\n .catch(() => {\n /* swallow timer errors */\n });\n }, EVICTION_INTERVAL_MS).unref();\n}\n\nfunction buildSubmittedEvent(handle: TaskHandle): TaskEvent {\n return {\n type: \"submitted\",\n taskId: handle.id,\n kind: handle.kind,\n submittedAt: handle.submittedAt,\n ...(handle.meta !== undefined ? { meta: handle.meta } : {}),\n };\n}\n\nasync function shortCircuitAborted(handle: TaskHandle, signal: AbortSignal): Promise<TaskHandle> {\n // EC-4: pre-aborted signal — skip queue/semaphore.\n const cancelled: TaskHandle = {\n ...handle,\n state: \"cancelled\",\n cancelledAt: Date.now(),\n };\n await state.store.insert(cancelled);\n state.buffers.set(handle.id, new RingBuffer(RING_CAP));\n emitToSubscribers(handle.id, buildSubmittedEvent(cancelled));\n emitToSubscribers(handle.id, {\n type: \"cancelled\",\n taskId: handle.id,\n cancelledAt: cancelled.cancelledAt ?? Date.now(),\n reason: signal.reason instanceof Error ? signal.reason.message : \"pre-aborted\",\n });\n return cancelled;\n}\n\nasync function transition<T extends TaskState>(\n taskId: string,\n next: T,\n patch: Partial<TaskHandle>,\n): Promise<void> {\n const before = await state.store.get(taskId);\n const span = startTaskTransitionSpan({\n taskId,\n from: before?.state ?? \"unknown\",\n to: next,\n });\n try {\n await safeUpdate(taskId, (h) => ({ ...h, state: next, ...patch }));\n } finally {\n span.end();\n }\n}\n\ninterface SubmitInternal<T> {\n readonly kind: TaskKind;\n readonly work: WorkFn<T>;\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n readonly signal?: AbortSignal;\n /** When true (adapter-internal), the validator allows reserved prefixes. */\n readonly allowReservedPrefix?: boolean;\n /** SE2 — forward this task's lifecycle to the run-event sink as `task_*` RunEvents. */\n readonly onRunEvent?: import(\"../../types/run-events.js\").RunEventSink;\n}\n\nasync function buildAndInsertQueued(\n internal: SubmitInternal<unknown>,\n resolvedId: string,\n): Promise<TaskHandle> {\n const submittedAt = Date.now();\n const handle: TaskHandle = {\n id: resolvedId,\n kind: internal.kind,\n state: \"queued\",\n submittedAt,\n ...(internal.meta !== undefined ? { meta: internal.meta } : {}),\n };\n await state.store.insert(handle);\n state.buffers.set(resolvedId, new RingBuffer(RING_CAP));\n emitToSubscribers(resolvedId, buildSubmittedEvent(handle));\n return handle;\n}\n\nfunction resolveIdInternal(internal: SubmitInternal<unknown>): string {\n if (internal.id === undefined) return randomUUID();\n if (!isValidTaskId(internal.id, internal.allowReservedPrefix ?? false)) {\n throw new InvalidTaskIdError(`invalid task id: ${internal.id}`, internal.id);\n }\n return internal.id;\n}\n\nasync function runWorkAndFinalize<T>(\n taskId: string,\n aborter: AbortController,\n work: WorkFn<T>,\n): Promise<void> {\n const ctx: TaskWorkContext = {\n signal: aborter.signal,\n emit(payload) {\n // EC-7: check cancelRequested at every progress checkpoint.\n void checkCancelRequestedAt(taskId, aborter);\n emitToSubscribers(taskId, {\n type: \"progress\",\n taskId,\n at: Date.now(),\n payload,\n });\n },\n };\n\n try {\n const result = await reentryAls.run(true, () => Promise.resolve().then(() => work(ctx)));\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const finishedAt = Date.now();\n await transition(taskId, \"finished\", { finishedAt, result });\n emitToSubscribers(taskId, { type: \"finished\", taskId, finishedAt, result });\n } catch (err) {\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const erroredAt = Date.now();\n const error =\n err instanceof Error\n ? { code: (err as { code?: string }).code ?? \"work_threw\", message: err.message }\n : { code: \"work_threw\", message: String(err) };\n await transition(taskId, \"error\", { erroredAt, error });\n emitToSubscribers(taskId, { type: \"errored\", taskId, erroredAt, error });\n }\n}\n\nasync function checkCancelRequestedAt(taskId: string, aborter: AbortController): Promise<void> {\n if (aborter.signal.aborted) return;\n try {\n const handle = await state.store.get(taskId);\n if (handle?.cancelRequested === true) {\n aborter.abort(\"cancelRequested\");\n }\n } catch {\n /* ignore — best-effort poll */\n }\n}\n\nasync function acquireSlot(): Promise<() => void> {\n if (reentryAls.getStore() === true) {\n // EC-11: reentrant submit bypasses the queue.\n return () => {\n /* no-op */\n };\n }\n return state.semaphore.acquire();\n}\n\n/**\n * Submit a task. Validates id (D368, EC-5 via allowReservedPrefix),\n * handles pre-aborted signals (EC-4), enforces single-flight by id\n * (D367), runs work under semaphore (D369/EC-11 reentrant bypass),\n * and produces the canonical event stream (D366).\n */\nexport async function submit<T>(internal: SubmitInternal<T>): Promise<TaskHandle> {\n state.firstSubmitSeen = true;\n startEvictTimerIfNeeded();\n\n const resolvedId = resolveIdInternal(internal);\n // SE2 — bridge the task lifecycle to the caller's run-event sink (opt-in).\n if (internal.onRunEvent !== undefined) {\n const sink = internal.onRunEvent;\n const kind = internal.kind;\n const subs = state.subscribers.get(resolvedId) ?? new Set();\n subs.add((e: TaskEvent) => {\n const runEvent = taskEventToRunEvent(e, resolvedId, kind);\n if (runEvent !== undefined) emitRunEvent(sink, runEvent);\n });\n state.subscribers.set(resolvedId, subs);\n }\n const submitSpan = startTaskSubmitSpan({ taskId: resolvedId, kind: internal.kind });\n\n // D367 single-flight.\n const existing = await state.store.get(resolvedId);\n if (existing !== undefined) {\n submitSpan.end();\n return existing;\n }\n\n const queuedHandle = await buildAndInsertQueued(internal, resolvedId);\n submitSpan.end();\n\n // EC-4: pre-aborted signal — short-circuit.\n if (internal.signal?.aborted === true) {\n return shortCircuitAborted(queuedHandle, internal.signal);\n }\n\n const aborter = new AbortController();\n state.aborters.set(resolvedId, aborter);\n if (internal.signal !== undefined) {\n internal.signal.addEventListener(\"abort\", () => aborter.abort(internal.signal?.reason), {\n once: true,\n });\n }\n\n // Fire and forget the actual run; the returned handle is the queued one.\n const release = await acquireSlot();\n void (async () => {\n try {\n // Check cancelRequested before starting (EC-7).\n await checkCancelRequestedAt(resolvedId, aborter);\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(resolvedId, \"cancelled\", { cancelledAt });\n emitToSubscribers(resolvedId, { type: \"cancelled\", taskId: resolvedId, cancelledAt });\n return;\n }\n const startedAt = Date.now();\n await transition(resolvedId, \"running\", { startedAt });\n emitToSubscribers(resolvedId, { type: \"started\", taskId: resolvedId, startedAt });\n await runWorkAndFinalize(resolvedId, aborter, internal.work as WorkFn<unknown>);\n } finally {\n release();\n state.aborters.delete(resolvedId);\n }\n })();\n\n return queuedHandle;\n}\n\nexport async function list(filter: TaskFilter = {}): Promise<TaskHandle[]> {\n return state.store.list(filter);\n}\n\nexport async function get(id: string): Promise<TaskHandle | undefined> {\n if (!isValidTaskId(id, true)) return undefined;\n return state.store.get(id);\n}\n\nexport async function cancel(id: string, reason?: string): Promise<TaskCancelResult> {\n if (!isValidTaskId(id, true)) return { cancelled: false, alreadyTerminal: false };\n const handle = await state.store.get(id);\n if (handle === undefined) return { cancelled: false, alreadyTerminal: false };\n if (handle.state === \"finished\" || handle.state === \"error\" || handle.state === \"cancelled\") {\n return { cancelled: false, alreadyTerminal: true };\n }\n const span = startTaskCancelSpan({\n taskId: id,\n ...(reason !== undefined ? { reason } : {}),\n via: \"api\",\n });\n try {\n return await cancelInternal(id, handle.state, reason);\n } finally {\n span.end();\n }\n}\n\nasync function cancelInternal(\n id: string,\n currentState: TaskState,\n reason?: string,\n): Promise<TaskCancelResult> {\n if (currentState === \"queued\") {\n const cancelledAt = Date.now();\n await transition(id, \"cancelled\", { cancelledAt });\n emitToSubscribers(id, {\n type: \"cancelled\",\n taskId: id,\n cancelledAt,\n ...(reason !== undefined ? { reason } : {}),\n });\n state.aborters.delete(id);\n return { cancelled: true, alreadyTerminal: false };\n }\n // running: trigger AbortController; runWorkAndFinalize handles the transition.\n const aborter = state.aborters.get(id);\n if (aborter !== undefined) aborter.abort(reason ?? \"cancelled\");\n return { cancelled: true, alreadyTerminal: false };\n}\n\nexport const subscribe = buildSubscribe({\n getBuffer: (id) => state.buffers.get(id),\n getOrCreateSubscriberSet: (id) => {\n let subs = state.subscribers.get(id);\n if (subs === undefined) {\n subs = new Set();\n state.subscribers.set(id, subs);\n }\n return subs;\n },\n removeSubscriber: (id, cb) => {\n const set = state.subscribers.get(id);\n set?.delete(cb);\n if (set !== undefined && set.size === 0) state.subscribers.delete(id);\n },\n});\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { TheokitAgentError } from './chunk-
|
|
2
|
-
import { redactSecrets } from './chunk-
|
|
3
|
-
import { diag } from './chunk-
|
|
1
|
+
import { TheokitAgentError } from './chunk-ZZMZWBR6.js';
|
|
2
|
+
import { redactSecrets } from './chunk-D4CUGAKZ.js';
|
|
3
|
+
import { diag } from './chunk-XEQ3TM66.js';
|
|
4
4
|
|
|
5
5
|
// src/internal/runtime/compression/compression-helpers.ts
|
|
6
6
|
function selectCompressionWindow(messages, preserveLast = 6) {
|
|
@@ -154,5 +154,5 @@ function shouldCompact(input) {
|
|
|
154
154
|
}
|
|
155
155
|
|
|
156
156
|
export { ABSOLUTE_CONTEXT_WINDOW_CAP, CHECKPOINT_MARKER, CONTEXT_WINDOW_FLOOR, CONTEXT_WINDOW_MARGIN, ContextWindowMarginError, SUMMARY_TEMPLATE, buildCheckpoint, compactTranscript, estimateTokens, filterFromLatestCheckpoint, isContextOverflowError, resolveEffectiveContextWindow, shouldCompact };
|
|
157
|
-
//# sourceMappingURL=chunk-
|
|
158
|
-
//# sourceMappingURL=chunk-
|
|
157
|
+
//# sourceMappingURL=chunk-A4JVILQU.js.map
|
|
158
|
+
//# sourceMappingURL=chunk-A4JVILQU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/runtime/compression/compression-helpers.ts","../src/compaction.ts"],"names":[],"mappings":";;;;;AA0BO,SAAS,uBAAA,CACd,QAAA,EACA,YAAA,GAAe,CAAA,EACO;AACtB,EAAA,IAAI,QAAA,CAAS,UAAU,YAAA,EAAc;AACnC,IAAA,OAAO,EAAE,YAAY,EAAC,EAAG,YAAY,CAAC,GAAG,QAAQ,CAAA,EAAE;AAAA,EACrD;AACA,EAAA,OAAO;AAAA,IACL,UAAA,EAAY,QAAA,CAAS,KAAA,CAAM,CAAA,EAAG,CAAC,YAAY,CAAA;AAAA,IAC3C,UAAA,EAAY,QAAA,CAAS,KAAA,CAAM,CAAC,YAAY;AAAA,GAC1C;AACF;;;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AAA,CAAM,YAAY,MAAA,EAAW;AAC/B,IAAA,OAAO,EAAE,QAAQ,UAAA,CAAW,KAAA,CAAM,OAAO,CAAA,EAAG,MAAA,EAAQ,SAAA,EAAW,OAAA,EAAS,KAAA,EAAM;AAAA,EAChF;AAEA,EAAA,OAAO,EAAE,MAAA,EAAQ,UAAA,CAAW,KAAA,CAAM,KAAA,IAAS,CAAC,CAAA,EAAG,MAAA,EAAQ,UAAA,EAAY,OAAA,EAAS,KAAA,EAAM;AACpF;AAyBO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,CAAC,CAAA;AAClC;AAUO,SAAS,cAAc,KAAA,EAAoC;AAChE,EAAA,OAAO,MAAM,SAAA,IAAa,KAAA,CAAM,gBAAgB,KAAA,CAAM,MAAA,IAAU,MAAM,SAAA,IAAa,CAAA,CAAA;AACrF","file":"chunk-F7AQV62G.js","sourcesContent":["/**\n * Compression helpers (T2.3, ADR D92).\n *\n * Scaffold for future compression LLM integration:\n * - `selectCompressionWindow` — splits messages into compress/preserve halves\n * - `assertCompressionReduced` — 10% reduction floor to detect \"compression placebo\"\n *\n * The compression LLM call itself is out of scope for this plan (requires\n * an auxiliary-model ADR). These helpers are used by `Agent.send` when a\n * future iteration adds compression.\n *\n * @internal\n */\n\nexport interface CompressionWindow<M> {\n toCompress: M[];\n toPreserve: M[];\n}\n\n/**\n * Split `messages` into the half to compress (older) and the half to\n * preserve verbatim (recent). When `messages.length <= preserveLast`,\n * everything is preserved.\n *\n * @internal\n */\nexport function selectCompressionWindow<M>(\n messages: readonly M[],\n preserveLast = 6,\n): CompressionWindow<M> {\n if (messages.length <= preserveLast) {\n return { toCompress: [], toPreserve: [...messages] };\n }\n return {\n toCompress: messages.slice(0, -preserveLast),\n toPreserve: messages.slice(-preserveLast),\n };\n}\n\nexport interface CompressionCheck {\n reduced: boolean;\n reductionPct: number;\n reason?: string;\n}\n\n/**\n * Check that compression actually reduced token count by at least `minPct`\n * (default 10%). Returns `{ reduced: false }` for spirals-in-formation\n * (compression LLM outputs that grow or barely shrink).\n *\n * @internal\n */\nexport function assertCompressionReduced(\n before: number,\n after: number,\n minPct = 10,\n): CompressionCheck {\n if (before <= 0) {\n return { reduced: false, reductionPct: 0, reason: \"before count was zero\" };\n }\n const reductionPct = ((before - after) / before) * 100;\n if (reductionPct >= minPct) {\n return { reduced: true, reductionPct };\n }\n return {\n reduced: false,\n reductionPct,\n reason: `compression reduced ${reductionPct.toFixed(1)}% (< ${minPct}% min). Spiral likely.`,\n };\n}\n","/**\n * Public compaction / context-management helpers (M2-1, extended V3-3).\n *\n * Promotes the SDK's compaction capability to a public surface so consumers can\n * compact a transcript, mark/filter conversation checkpoints, and detect\n * context-overflow — without reaching into `internal/`.\n *\n * Two recent-window modes (V3-3):\n * - `keepRecent` (turn-count, default) — keeps the last N turns verbatim and\n * always preserves leading system PROMPTS; reuses the internal\n * `selectCompressionWindow` (no second algorithm).\n * - `keepTokens` (token-budget) — keeps the trailing turns whose accumulated\n * `estimateTokens` fits the budget (theocode `splitTranscript` semantics). In\n * this mode leading system prompts are NOT special-cased (D6).\n *\n * Summarization is delegated to a caller-supplied callback (which receives the\n * older window + the summary template). With `failSafe`, a thrown summarizer\n * returns the ORIGINAL transcript + a structured warn (compaction is an\n * optimization, never a cause of data loss); without it, the error propagates.\n *\n * Public from the `@theokit/sdk/compaction` sub-path.\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\nimport { diag } from \"./internal/diagnostics.js\";\nimport { selectCompressionWindow } from \"./internal/runtime/compression/compression-helpers.js\";\nimport { redactSecrets } from \"./internal/security/redact.js\";\n\n/**\n * Minimal message shape for compaction/compression input. THE canonical public origin (leaf type —\n * rollup-plugin-dts cannot re-export types from internal modules into entry bundles; M42 lesson).\n *\n * @public\n */\nexport interface CompressibleMessage {\n role: \"user\" | \"assistant\" | \"system\";\n content: string;\n}\n\n/**\n * Sentinel prefix marking a conversation checkpoint turn. A visible, structured,\n * prose-unlikely token (no invisible/control bytes — safe to persist and to read\n * in source). Only {@link buildCheckpoint} should produce content beginning with it.\n */\nexport const CHECKPOINT_MARKER = \"[[theokit:checkpoint]] \";\n\n/**\n * The 7-section summary template handed to the `summarize` callback (theocode\n * parity shape). Every header is always present so the summarizer cannot silently\n * drop a category; the model is told to preserve file paths, commands, and error\n * text verbatim. Override per-call via {@link CompactTranscriptOptions.summaryTemplate}.\n */\nexport const SUMMARY_TEMPLATE = `Summarize the conversation so far into these sections (keep every header even if empty):\n\n## Goal\nWhat the user is ultimately trying to achieve.\n\n## Constraints\nHard requirements, conventions, and rules stated.\n\n## Progress\nWhat has been done so far.\n\n## Decisions\nChoices made and their rationale.\n\n## Next\nThe immediate next steps.\n\n## Critical\nAnything that MUST NOT be forgotten (preserve verbatim: error messages, exact values).\n\n## Files\nFile paths touched or referenced (verbatim).`;\n\n/** Reject an empty marker — it would match every turn via `startsWith(\"\")` (EC-3). */\nfunction assertMarker(marker: string): void {\n if (marker === \"\") {\n throw new TheokitAgentError(\"compaction marker must be non-empty\", {\n code: \"invalid_argument\",\n });\n }\n}\n\n/** True for a real system prompt — a `system` turn that is NOT a checkpoint marker. */\nfunction isSystemPrompt(message: CompressibleMessage, marker: string): boolean {\n return message.role === \"system\" && !message.content.startsWith(marker);\n}\n\n/** Carried split: leading system prompts (preserved), the older window, the verbatim tail. */\ninterface TranscriptSplit {\n systemPrompts: CompressibleMessage[];\n head: CompressibleMessage[];\n recent: CompressibleMessage[];\n}\n\n/**\n * Token-budget split (theocode `splitTranscript`): walk from the END accumulating\n * `estimateTokens` until `keepTokens` is exceeded; everything older is the head.\n * Always keeps ≥ 1 recent turn. No system-prompt special-casing (D6).\n */\nfunction selectByTokenBudget(\n messages: CompressibleMessage[],\n keepTokens: number,\n): { head: CompressibleMessage[]; recent: CompressibleMessage[] } {\n let acc = 0;\n let splitIndex = messages.length;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n acc += estimateTokens(messages[i]?.content ?? \"\");\n if (acc > keepTokens && i < messages.length - 1) {\n splitIndex = i + 1;\n break;\n }\n splitIndex = i;\n }\n return { head: messages.slice(0, splitIndex), recent: messages.slice(splitIndex) };\n}\n\n/** Turn-count split (M2): preserve leading system prompts; window the rest by `keepRecent`. */\nfunction splitByRecent(\n messages: CompressibleMessage[],\n keepRecent: number,\n marker: string,\n): TranscriptSplit {\n const systemPrompts = messages.filter((m) => isSystemPrompt(m, marker));\n const rest = messages.filter((m) => !isSystemPrompt(m, marker));\n const { toCompress, toPreserve } = selectCompressionWindow(rest, keepRecent);\n return { systemPrompts, head: toCompress, recent: toPreserve };\n}\n\n/** Options for {@link compactTranscript}. */\nexport interface CompactTranscriptOptions {\n /** Trailing turns preserved verbatim by COUNT (default 6). Ignored when `keepTokens` is set. */\n keepRecent?: number;\n /**\n * Trailing turns preserved verbatim by TOKEN BUDGET (theocode mode). When set,\n * takes precedence over `keepRecent` and disables system-prompt preservation (D6).\n */\n keepTokens?: number;\n /** Checkpoint marker (default {@link CHECKPOINT_MARKER}). Must be non-empty. */\n marker?: string;\n /** Summary template passed to `summarize` (default {@link SUMMARY_TEMPLATE}). */\n summaryTemplate?: string;\n /** Summarize the older window into one turn; if omitted, the older window is dropped. */\n summarize?: (older: CompressibleMessage[], template: string) => Promise<CompressibleMessage>;\n /**\n * When true, a thrown `summarize` returns the ORIGINAL transcript + a structured\n * warn (compaction never loses data). Default false: the error propagates.\n */\n failSafe?: boolean;\n}\n\n/** Sentinel returned by {@link runSummarize} when fail-safe swallowed a throw. */\nconst FAILSAFE_ABORT = Symbol(\"failsafe-abort\");\n\n/** Run the summarizer; on throw, either propagate or (fail-safe) warn + signal abort. */\nasync function runSummarize(\n summarize: NonNullable<CompactTranscriptOptions[\"summarize\"]>,\n head: CompressibleMessage[],\n template: string,\n failSafe: boolean,\n): Promise<CompressibleMessage | typeof FAILSAFE_ABORT> {\n try {\n return await summarize(head, template);\n } catch (err) {\n if (!failSafe) throw err;\n // Unbreakable Rule 8 — never fail silently. The breadcrumb points at the root\n // cause when a summarizer fails every turn and context grows unchecked. The\n // summarizer is caller-supplied, so its error text is routed through\n // `redactSecrets` (ADR D68 — no unredacted output sink in src/).\n // theokit#147 — through the interceptable channel. A summarizer failing every turn is exactly\n // the breadcrumb a TUI host wants in its own panel, not smeared across its alternate screen.\n diag(\n `[compaction] summarizer failed — proceeding uncompacted: ${redactSecrets(err instanceof Error ? err.message : String(err))}\\n`,\n );\n return FAILSAFE_ABORT;\n }\n}\n\n/**\n * Compact a transcript. In `keepRecent` mode (default) the last `keepRecent` turns\n * are kept verbatim and leading system PROMPTS preserved; in `keepTokens` mode the\n * trailing turns within the token budget are kept (no system special-casing, D6).\n * The older window is summarized (via `summarize`, receiving the template) or\n * dropped. Never mutates the input.\n */\nexport async function compactTranscript(\n messages: CompressibleMessage[],\n options: CompactTranscriptOptions = {},\n): Promise<CompressibleMessage[]> {\n const marker = options.marker ?? CHECKPOINT_MARKER;\n assertMarker(marker);\n const split =\n options.keepTokens != null\n ? { systemPrompts: [], ...selectByTokenBudget(messages, options.keepTokens) }\n : splitByRecent(messages, options.keepRecent ?? 6, marker);\n if (split.head.length === 0) {\n return [...messages];\n }\n if (!options.summarize) {\n return [...split.systemPrompts, ...split.recent];\n }\n const template = options.summaryTemplate ?? SUMMARY_TEMPLATE;\n const summary = await runSummarize(\n options.summarize,\n split.head,\n template,\n options.failSafe ?? false,\n );\n if (summary === FAILSAFE_ABORT) {\n return [...messages];\n }\n return [...split.systemPrompts, summary, ...split.recent];\n}\n\n/**\n * Build a checkpoint marker turn (a `system` turn whose content starts with\n * `marker`, default {@link CHECKPOINT_MARKER}). `marker` must be non-empty.\n */\nexport function buildCheckpoint(\n label?: string,\n marker: string = CHECKPOINT_MARKER,\n): CompressibleMessage {\n assertMarker(marker);\n return { role: \"system\", content: marker + (label ?? \"\") };\n}\n\n/** Options for {@link filterFromLatestCheckpoint}. */\nexport interface FilterCheckpointOptions {\n /** Marker to scan for (default {@link CHECKPOINT_MARKER}). */\n marker?: string;\n /**\n * `'after'` (default, M2) returns turns AFTER the latest marker (exclusive);\n * `'from'` (theocode) returns turns FROM the latest marker (inclusive).\n */\n include?: \"after\" | \"from\";\n}\n\n/**\n * Return the turns relative to the most recent checkpoint marker (all turns if\n * none). `include: 'after'` (default) excludes the checkpoint; `'from'` includes\n * it (the summary stands in for the pruned head). Never mutates the input.\n */\nexport function filterFromLatestCheckpoint(\n messages: CompressibleMessage[],\n options: FilterCheckpointOptions = {},\n): CompressibleMessage[] {\n const marker = options.marker ?? CHECKPOINT_MARKER;\n const offset = options.include === \"from\" ? 0 : 1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if (messages[i]?.content.startsWith(marker)) {\n return messages.slice(i + offset);\n }\n }\n return [...messages];\n}\n\n/**\n * True iff `err` is a {@link TheokitAgentError} (or subclass) reporting a\n * context-window-exceeded condition (the typed `context_too_long` code). Reads\n * both `code` (set by provider mappers) and `metadata.code` (the preferred field)\n * — never a brittle message regex.\n */\nexport function isContextOverflowError(err: unknown): boolean {\n return (\n err instanceof TheokitAgentError &&\n (err.code === \"context_too_long\" || err.metadata?.code === \"context_too_long\")\n );\n}\n\n/**\n * M77 — the margin is outside `(0, 1]`. Typed, because a margin > 1 would GROW the assumed window,\n * which is the unsafe direction: `shouldCompact` is monotonically decreasing in `contextWindow`, so\n * overestimating it makes the trigger fire too late and the context overflow.\n */\nexport class ContextWindowMarginError extends TheokitAgentError {\n constructor(readonly margin: number) {\n super(\n `context-window margin must be in (0, 1], got ${String(margin)}. ` +\n `A margin above 1 grows the assumed window and delays compaction past the real limit.`,\n { code: \"invalid_context_window_margin\" },\n );\n }\n}\n\n/**\n * M77 — default safety margin on the context window.\n *\n * `0.95` is not a guess: it is the single reference's value. Codex ships\n * `effective_context_window_percent: 95` (`models-manager/src/model_info.rs:158`) and never budgets\n * against 100% of a window. Being MULTIPLICATIVE, it stays conservative at any window size, which a\n * fixed subtraction would not.\n */\nexport const CONTEXT_WINDOW_MARGIN = 0.95;\n\n/**\n * M77 — the floor used ONLY when neither the catalog nor the caller knows the window.\n *\n * Honest about its own weakness. This number has **one** source (the M77 milestone text); the search\n * for a second one failed, because the reference has no fallback at all — Codex returns `Option` and\n * its callers early-return (`core/src/session/turn_context.rs:213`, `core/src/compact_remote.rs:374`).\n *\n * It is conservative only UPWARD. For a model whose real window is larger, budgeting against 128k\n * compacts early — wasteful but safe. For a model whose real window is SMALLER (an 8k or 32k model\n * absent from the catalog), it compacts too late and the context still overflows. That residual risk\n * is real and is why {@link resolveEffectiveContextWindow} never lets this floor compete with a known\n * catalog value, and why the `compaction_fallback` event exists: a surface can show that the budget is\n * a guess instead of the user finding out when the provider rejects the request.\n */\nexport const CONTEXT_WINDOW_FLOOR = 128_000;\n\n/** Where the effective window came from — carried into the M77 structured event. */\nexport type ContextWindowSource = \"override\" | \"catalog\" | \"fallback\";\n\n/** Input to {@link resolveEffectiveContextWindow}. */\nexport interface EffectiveContextWindowInput {\n /** Caller-supplied window, in tokens. Clamped by `catalog` when both are present. */\n readonly override?: number | undefined;\n /** The model's window from the catalog, in tokens. Absent when the model is unknown. */\n readonly catalog?: number | undefined;\n /** Safety margin in `(0, 1]`. Codex uses 0.95 (`model_info.rs:158`). */\n readonly margin: number;\n /** Conservative floor used ONLY when neither `override` nor `catalog` is available. */\n readonly floor?: number | undefined;\n}\n\n/** Result of {@link resolveEffectiveContextWindow}. */\nexport interface EffectiveContextWindow {\n /** The window to budget against, after clamp and margin. */\n readonly window: number;\n /** Which input won — `\"fallback\"` means neither override nor catalog was available. */\n readonly source: ContextWindowSource;\n /** `true` when an `override` above the catalog window was clamped down to it. */\n readonly clamped: boolean;\n}\n\n/**\n * Absolute cap on a declared context window, applied when no catalog entry exists to compare against.\n *\n * **10M**, not 2M. The first version used 2M on the rationale that it sat \"comfortably above the\n * largest published window\" — adversarial review measured the opposite: Llama 4 Scout publishes\n * **10M**, and it arrives precisely via OpenRouter, the provider **without** a catalog, which is the\n * case this cap exists to cover. The user would have silently lost 80% of the declared window.\n *\n * The cap still serves what motivates it — one extra zero on 400k gives 4M, which passes; two zeros\n * give 40M, which does not. A limit that rejects legitimate configuration is worse than no limit,\n * because failing OPEN is visible when it happens and silently losing 80% is not.\n */\nexport const ABSOLUTE_CONTEXT_WINDOW_CAP = 10_000_000;\n\n/**\n * Resolve the window to budget against — the fail-SAFE replacement for reading the catalog directly.\n *\n * Today `post-run-lifecycle.ts` reads `getCatalogModelInfo(model)?.limit?.context` and, when that is\n * `undefined`, auto-compaction simply never fires. That is fail-OPEN: the context grows until the\n * provider rejects the request. (The comment there calls it \"fail-safe\" — M77 corrects it.)\n *\n * Three techniques, two of them borrowed from the single reference:\n *\n * 1. **Override, CLAMPED by the catalog** — Codex `models-manager/src/model_info.rs:26-31` lets\n * config override the window but limits it with `context_window.min(max_context_window)`.\n * Without the clamp, declaring 999k on a 200k model reopens the overflow through another door.\n * 2. **Multiplicative margin** — Codex `model_info.rs:158` (`effective_context_window_percent: 95`)\n * never budgets against 100% of the window. Being multiplicative, it is conservative for ANY\n * window size.\n * 3. **Floor, only when nothing is known** — deliberately NOT a blanket default. A fixed floor is\n * conservative only upward: applied to a small model it would inflate the assumed window and\n * reproduce the very fail-open this function exists to close. Hence the floor never competes\n * with a known catalog value.\n *\n * Pure — no catalog lookup, no I/O. The caller supplies the numbers, mirroring `shouldCompact`.\n */\nexport function resolveEffectiveContextWindow(\n input: EffectiveContextWindowInput,\n): EffectiveContextWindow {\n if (!(input.margin > 0) || input.margin > 1) {\n throw new ContextWindowMarginError(input.margin);\n }\n\n const withMargin = (raw: number): number => Math.floor(raw * input.margin);\n\n if (input.override !== undefined) {\n // The catalog is the preferred cap; without it the ABSOLUTE cap applies.\n //\n // M95 (adversarial review of M94) — the previous version clamped **only** when a catalog entry\n // existed, and the whole reason the `contextWindow` key exists is the model that has NO entry\n // (OpenRouter has zero). So the clamp was missing in exactly the case that justifies the\n // feature, while the documentation — including an already-published CHANGELOG — stated without\n // qualification that \"declaring 10M does not blow past the provider\".\n //\n // The concrete scenario is one extra zero: `context_window = 4000000`. The only guard was a\n // `.positive().int()`, which sets no upper bound. The agent would never compact until the\n // provider refused the turn — the silent fail-OPEN that M77 exists to prevent.\n const cap = input.catalog ?? ABSOLUTE_CONTEXT_WINDOW_CAP;\n const clamped = input.override > cap;\n return { window: withMargin(clamped ? cap : input.override), source: \"override\", clamped };\n }\n\n if (input.catalog !== undefined) {\n return { window: withMargin(input.catalog), source: \"catalog\", clamped: false };\n }\n\n return { window: withMargin(input.floor ?? 0), source: \"fallback\", clamped: false };\n}\n\n/** Input to {@link shouldCompact}: an estimate, the model's window, and reserved headroom. */\nexport interface ShouldCompactInput {\n /** Estimated token count of the next request (e.g. from {@link estimateTokens}). */\n readonly estimated: number;\n /** The model's total context window, in tokens. */\n readonly contextWindow: number;\n /** Tokens to reserve as headroom (output + safety margin). */\n readonly buffer: number;\n /**\n * Tokens reserved for the model's response generation, SEPARATE from `buffer`.\n * Default 0 — omitting it preserves the legacy\n * `estimated >= contextWindow - buffer` result.\n */\n readonly maxOutput?: number;\n}\n\n/**\n * Tokenizer-free token estimate via the conventional ~4-chars-per-token\n * heuristic: `ceil(text.length / 4)`. `\"\"` → 0; any non-empty text → ≥ 1.\n * A cheap PRE-CALL gate for {@link shouldCompact} — NOT exact tokenization\n * (a consumer needing exactness supplies their own tokenizer). Uses UTF-16\n * `.length` (code units), so multibyte text is approximate.\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Decide BEFORE sending whether to compact: `true` when the `estimated` token\n * count leaves less than `buffer` headroom in the `contextWindow`\n * (`estimated >= contextWindow - buffer`). A `buffer >= contextWindow`\n * (non-positive threshold) always returns `true`. Pure — the caller supplies\n * the window (e.g. from `resolveModelCapabilities`), keeping this decoupled\n * from the per-model catalog.\n */\nexport function shouldCompact(input: ShouldCompactInput): boolean {\n return input.estimated >= input.contextWindow - input.buffer - (input.maxOutput ?? 0);\n}\n"]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B,KAAA,CAAM,MAAM,CAAA;AAAA,EACjD;AAEA,EAAA,MAAM,aAAa,CAAC,GAAA,KAAwB,KAAK,KAAA,CAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AAEzE,EAAA,IAAI,KAAA,CAAM,aAAa,MAAA,EAAW;AAYhC,IAAA,MAAM,GAAA,GAAM,MAAM,OAAA,IAAW,2BAAA;AAC7B,IAAA,MAAM,OAAA,GAAU,MAAM,QAAA,GAAW,GAAA;AACjC,IAAA,OAAO,EAAE,MAAA,EAAQ,UAAA,CAAW,OAAA,GAAU,GAAA,GAAM,MAAM,QAAQ,CAAA,EAAG,MAAA,EAAQ,UAAA,EAAY,OAAA,EAAQ;AAAA,EAC3F;AAEA,EAAA,IAAI,KAAA,CAAM,YAAY,MAAA,EAAW;AAC/B,IAAA,OAAO,EAAE,QAAQ,UAAA,CAAW,KAAA,CAAM,OAAO,CAAA,EAAG,MAAA,EAAQ,SAAA,EAAW,OAAA,EAAS,KAAA,EAAM;AAAA,EAChF;AAEA,EAAA,OAAO,EAAE,MAAA,EAAQ,UAAA,CAAW,KAAA,CAAM,KAAA,IAAS,CAAC,CAAA,EAAG,MAAA,EAAQ,UAAA,EAAY,OAAA,EAAS,KAAA,EAAM;AACpF;AAyBO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,CAAC,CAAA;AAClC;AAUO,SAAS,cAAc,KAAA,EAAoC;AAChE,EAAA,OAAO,MAAM,SAAA,IAAa,KAAA,CAAM,gBAAgB,KAAA,CAAM,MAAA,IAAU,MAAM,SAAA,IAAa,CAAA,CAAA;AACrF","file":"chunk-A4JVILQU.js","sourcesContent":["/**\n * Compression helpers (T2.3, ADR D92).\n *\n * Scaffold for future compression LLM integration:\n * - `selectCompressionWindow` — splits messages into compress/preserve halves\n * - `assertCompressionReduced` — 10% reduction floor to detect \"compression placebo\"\n *\n * The compression LLM call itself is out of scope for this plan (requires\n * an auxiliary-model ADR). These helpers are used by `Agent.send` when a\n * future iteration adds compression.\n *\n * @internal\n */\n\nexport interface CompressionWindow<M> {\n toCompress: M[];\n toPreserve: M[];\n}\n\n/**\n * Split `messages` into the half to compress (older) and the half to\n * preserve verbatim (recent). When `messages.length <= preserveLast`,\n * everything is preserved.\n *\n * @internal\n */\nexport function selectCompressionWindow<M>(\n messages: readonly M[],\n preserveLast = 6,\n): CompressionWindow<M> {\n if (messages.length <= preserveLast) {\n return { toCompress: [], toPreserve: [...messages] };\n }\n return {\n toCompress: messages.slice(0, -preserveLast),\n toPreserve: messages.slice(-preserveLast),\n };\n}\n\nexport interface CompressionCheck {\n reduced: boolean;\n reductionPct: number;\n reason?: string;\n}\n\n/**\n * Check that compression actually reduced token count by at least `minPct`\n * (default 10%). Returns `{ reduced: false }` for spirals-in-formation\n * (compression LLM outputs that grow or barely shrink).\n *\n * @internal\n */\nexport function assertCompressionReduced(\n before: number,\n after: number,\n minPct = 10,\n): CompressionCheck {\n if (before <= 0) {\n return { reduced: false, reductionPct: 0, reason: \"before count was zero\" };\n }\n const reductionPct = ((before - after) / before) * 100;\n if (reductionPct >= minPct) {\n return { reduced: true, reductionPct };\n }\n return {\n reduced: false,\n reductionPct,\n reason: `compression reduced ${reductionPct.toFixed(1)}% (< ${minPct}% min). Spiral likely.`,\n };\n}\n","/**\n * Public compaction / context-management helpers (M2-1, extended V3-3).\n *\n * Promotes the SDK's compaction capability to a public surface so consumers can\n * compact a transcript, mark/filter conversation checkpoints, and detect\n * context-overflow — without reaching into `internal/`.\n *\n * Two recent-window modes (V3-3):\n * - `keepRecent` (turn-count, default) — keeps the last N turns verbatim and\n * always preserves leading system PROMPTS; reuses the internal\n * `selectCompressionWindow` (no second algorithm).\n * - `keepTokens` (token-budget) — keeps the trailing turns whose accumulated\n * `estimateTokens` fits the budget (theocode `splitTranscript` semantics). In\n * this mode leading system prompts are NOT special-cased (D6).\n *\n * Summarization is delegated to a caller-supplied callback (which receives the\n * older window + the summary template). With `failSafe`, a thrown summarizer\n * returns the ORIGINAL transcript + a structured warn (compaction is an\n * optimization, never a cause of data loss); without it, the error propagates.\n *\n * Public from the `@theokit/sdk/compaction` sub-path.\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\nimport { diag } from \"./internal/diagnostics.js\";\nimport { selectCompressionWindow } from \"./internal/runtime/compression/compression-helpers.js\";\nimport { redactSecrets } from \"./internal/security/redact.js\";\n\n/**\n * Minimal message shape for compaction/compression input. THE canonical public origin (leaf type —\n * rollup-plugin-dts cannot re-export types from internal modules into entry bundles; M42 lesson).\n *\n * @public\n */\nexport interface CompressibleMessage {\n role: \"user\" | \"assistant\" | \"system\";\n content: string;\n}\n\n/**\n * Sentinel prefix marking a conversation checkpoint turn. A visible, structured,\n * prose-unlikely token (no invisible/control bytes — safe to persist and to read\n * in source). Only {@link buildCheckpoint} should produce content beginning with it.\n */\nexport const CHECKPOINT_MARKER = \"[[theokit:checkpoint]] \";\n\n/**\n * The 7-section summary template handed to the `summarize` callback (theocode\n * parity shape). Every header is always present so the summarizer cannot silently\n * drop a category; the model is told to preserve file paths, commands, and error\n * text verbatim. Override per-call via {@link CompactTranscriptOptions.summaryTemplate}.\n */\nexport const SUMMARY_TEMPLATE = `Summarize the conversation so far into these sections (keep every header even if empty):\n\n## Goal\nWhat the user is ultimately trying to achieve.\n\n## Constraints\nHard requirements, conventions, and rules stated.\n\n## Progress\nWhat has been done so far.\n\n## Decisions\nChoices made and their rationale.\n\n## Next\nThe immediate next steps.\n\n## Critical\nAnything that MUST NOT be forgotten (preserve verbatim: error messages, exact values).\n\n## Files\nFile paths touched or referenced (verbatim).`;\n\n/** Reject an empty marker — it would match every turn via `startsWith(\"\")` (EC-3). */\nfunction assertMarker(marker: string): void {\n if (marker === \"\") {\n throw new TheokitAgentError(\"compaction marker must be non-empty\", {\n code: \"invalid_argument\",\n });\n }\n}\n\n/** True for a real system prompt — a `system` turn that is NOT a checkpoint marker. */\nfunction isSystemPrompt(message: CompressibleMessage, marker: string): boolean {\n return message.role === \"system\" && !message.content.startsWith(marker);\n}\n\n/** Carried split: leading system prompts (preserved), the older window, the verbatim tail. */\ninterface TranscriptSplit {\n systemPrompts: CompressibleMessage[];\n head: CompressibleMessage[];\n recent: CompressibleMessage[];\n}\n\n/**\n * Token-budget split (theocode `splitTranscript`): walk from the END accumulating\n * `estimateTokens` until `keepTokens` is exceeded; everything older is the head.\n * Always keeps ≥ 1 recent turn. No system-prompt special-casing (D6).\n */\nfunction selectByTokenBudget(\n messages: CompressibleMessage[],\n keepTokens: number,\n): { head: CompressibleMessage[]; recent: CompressibleMessage[] } {\n let acc = 0;\n let splitIndex = messages.length;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n acc += estimateTokens(messages[i]?.content ?? \"\");\n if (acc > keepTokens && i < messages.length - 1) {\n splitIndex = i + 1;\n break;\n }\n splitIndex = i;\n }\n return { head: messages.slice(0, splitIndex), recent: messages.slice(splitIndex) };\n}\n\n/** Turn-count split (M2): preserve leading system prompts; window the rest by `keepRecent`. */\nfunction splitByRecent(\n messages: CompressibleMessage[],\n keepRecent: number,\n marker: string,\n): TranscriptSplit {\n const systemPrompts = messages.filter((m) => isSystemPrompt(m, marker));\n const rest = messages.filter((m) => !isSystemPrompt(m, marker));\n const { toCompress, toPreserve } = selectCompressionWindow(rest, keepRecent);\n return { systemPrompts, head: toCompress, recent: toPreserve };\n}\n\n/** Options for {@link compactTranscript}. */\nexport interface CompactTranscriptOptions {\n /** Trailing turns preserved verbatim by COUNT (default 6). Ignored when `keepTokens` is set. */\n keepRecent?: number;\n /**\n * Trailing turns preserved verbatim by TOKEN BUDGET (theocode mode). When set,\n * takes precedence over `keepRecent` and disables system-prompt preservation (D6).\n */\n keepTokens?: number;\n /** Checkpoint marker (default {@link CHECKPOINT_MARKER}). Must be non-empty. */\n marker?: string;\n /** Summary template passed to `summarize` (default {@link SUMMARY_TEMPLATE}). */\n summaryTemplate?: string;\n /** Summarize the older window into one turn; if omitted, the older window is dropped. */\n summarize?: (older: CompressibleMessage[], template: string) => Promise<CompressibleMessage>;\n /**\n * When true, a thrown `summarize` returns the ORIGINAL transcript + a structured\n * warn (compaction never loses data). Default false: the error propagates.\n */\n failSafe?: boolean;\n}\n\n/** Sentinel returned by {@link runSummarize} when fail-safe swallowed a throw. */\nconst FAILSAFE_ABORT = Symbol(\"failsafe-abort\");\n\n/** Run the summarizer; on throw, either propagate or (fail-safe) warn + signal abort. */\nasync function runSummarize(\n summarize: NonNullable<CompactTranscriptOptions[\"summarize\"]>,\n head: CompressibleMessage[],\n template: string,\n failSafe: boolean,\n): Promise<CompressibleMessage | typeof FAILSAFE_ABORT> {\n try {\n return await summarize(head, template);\n } catch (err) {\n if (!failSafe) throw err;\n // Unbreakable Rule 8 — never fail silently. The breadcrumb points at the root\n // cause when a summarizer fails every turn and context grows unchecked. The\n // summarizer is caller-supplied, so its error text is routed through\n // `redactSecrets` (ADR D68 — no unredacted output sink in src/).\n // theokit#147 — through the interceptable channel. A summarizer failing every turn is exactly\n // the breadcrumb a TUI host wants in its own panel, not smeared across its alternate screen.\n diag(\n `[compaction] summarizer failed — proceeding uncompacted: ${redactSecrets(err instanceof Error ? err.message : String(err))}\\n`,\n );\n return FAILSAFE_ABORT;\n }\n}\n\n/**\n * Compact a transcript. In `keepRecent` mode (default) the last `keepRecent` turns\n * are kept verbatim and leading system PROMPTS preserved; in `keepTokens` mode the\n * trailing turns within the token budget are kept (no system special-casing, D6).\n * The older window is summarized (via `summarize`, receiving the template) or\n * dropped. Never mutates the input.\n */\nexport async function compactTranscript(\n messages: CompressibleMessage[],\n options: CompactTranscriptOptions = {},\n): Promise<CompressibleMessage[]> {\n const marker = options.marker ?? CHECKPOINT_MARKER;\n assertMarker(marker);\n const split =\n options.keepTokens != null\n ? { systemPrompts: [], ...selectByTokenBudget(messages, options.keepTokens) }\n : splitByRecent(messages, options.keepRecent ?? 6, marker);\n if (split.head.length === 0) {\n return [...messages];\n }\n if (!options.summarize) {\n return [...split.systemPrompts, ...split.recent];\n }\n const template = options.summaryTemplate ?? SUMMARY_TEMPLATE;\n const summary = await runSummarize(\n options.summarize,\n split.head,\n template,\n options.failSafe ?? false,\n );\n if (summary === FAILSAFE_ABORT) {\n return [...messages];\n }\n return [...split.systemPrompts, summary, ...split.recent];\n}\n\n/**\n * Build a checkpoint marker turn (a `system` turn whose content starts with\n * `marker`, default {@link CHECKPOINT_MARKER}). `marker` must be non-empty.\n */\nexport function buildCheckpoint(\n label?: string,\n marker: string = CHECKPOINT_MARKER,\n): CompressibleMessage {\n assertMarker(marker);\n return { role: \"system\", content: marker + (label ?? \"\") };\n}\n\n/** Options for {@link filterFromLatestCheckpoint}. */\nexport interface FilterCheckpointOptions {\n /** Marker to scan for (default {@link CHECKPOINT_MARKER}). */\n marker?: string;\n /**\n * `'after'` (default, M2) returns turns AFTER the latest marker (exclusive);\n * `'from'` (theocode) returns turns FROM the latest marker (inclusive).\n */\n include?: \"after\" | \"from\";\n}\n\n/**\n * Return the turns relative to the most recent checkpoint marker (all turns if\n * none). `include: 'after'` (default) excludes the checkpoint; `'from'` includes\n * it (the summary stands in for the pruned head). Never mutates the input.\n */\nexport function filterFromLatestCheckpoint(\n messages: CompressibleMessage[],\n options: FilterCheckpointOptions = {},\n): CompressibleMessage[] {\n const marker = options.marker ?? CHECKPOINT_MARKER;\n const offset = options.include === \"from\" ? 0 : 1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if (messages[i]?.content.startsWith(marker)) {\n return messages.slice(i + offset);\n }\n }\n return [...messages];\n}\n\n/**\n * True iff `err` is a {@link TheokitAgentError} (or subclass) reporting a\n * context-window-exceeded condition (the typed `context_too_long` code). Reads\n * both `code` (set by provider mappers) and `metadata.code` (the preferred field)\n * — never a brittle message regex.\n */\nexport function isContextOverflowError(err: unknown): boolean {\n return (\n err instanceof TheokitAgentError &&\n (err.code === \"context_too_long\" || err.metadata?.code === \"context_too_long\")\n );\n}\n\n/**\n * M77 — the margin is outside `(0, 1]`. Typed, because a margin > 1 would GROW the assumed window,\n * which is the unsafe direction: `shouldCompact` is monotonically decreasing in `contextWindow`, so\n * overestimating it makes the trigger fire too late and the context overflow.\n */\nexport class ContextWindowMarginError extends TheokitAgentError {\n constructor(readonly margin: number) {\n super(\n `context-window margin must be in (0, 1], got ${String(margin)}. ` +\n `A margin above 1 grows the assumed window and delays compaction past the real limit.`,\n { code: \"invalid_context_window_margin\" },\n );\n }\n}\n\n/**\n * M77 — default safety margin on the context window.\n *\n * `0.95` is not a guess: it is the single reference's value. Codex ships\n * `effective_context_window_percent: 95` (`models-manager/src/model_info.rs:158`) and never budgets\n * against 100% of a window. Being MULTIPLICATIVE, it stays conservative at any window size, which a\n * fixed subtraction would not.\n */\nexport const CONTEXT_WINDOW_MARGIN = 0.95;\n\n/**\n * M77 — the floor used ONLY when neither the catalog nor the caller knows the window.\n *\n * Honest about its own weakness. This number has **one** source (the M77 milestone text); the search\n * for a second one failed, because the reference has no fallback at all — Codex returns `Option` and\n * its callers early-return (`core/src/session/turn_context.rs:213`, `core/src/compact_remote.rs:374`).\n *\n * It is conservative only UPWARD. For a model whose real window is larger, budgeting against 128k\n * compacts early — wasteful but safe. For a model whose real window is SMALLER (an 8k or 32k model\n * absent from the catalog), it compacts too late and the context still overflows. That residual risk\n * is real and is why {@link resolveEffectiveContextWindow} never lets this floor compete with a known\n * catalog value, and why the `compaction_fallback` event exists: a surface can show that the budget is\n * a guess instead of the user finding out when the provider rejects the request.\n */\nexport const CONTEXT_WINDOW_FLOOR = 128_000;\n\n/** Where the effective window came from — carried into the M77 structured event. */\nexport type ContextWindowSource = \"override\" | \"catalog\" | \"fallback\";\n\n/** Input to {@link resolveEffectiveContextWindow}. */\nexport interface EffectiveContextWindowInput {\n /** Caller-supplied window, in tokens. Clamped by `catalog` when both are present. */\n readonly override?: number | undefined;\n /** The model's window from the catalog, in tokens. Absent when the model is unknown. */\n readonly catalog?: number | undefined;\n /** Safety margin in `(0, 1]`. Codex uses 0.95 (`model_info.rs:158`). */\n readonly margin: number;\n /** Conservative floor used ONLY when neither `override` nor `catalog` is available. */\n readonly floor?: number | undefined;\n}\n\n/** Result of {@link resolveEffectiveContextWindow}. */\nexport interface EffectiveContextWindow {\n /** The window to budget against, after clamp and margin. */\n readonly window: number;\n /** Which input won — `\"fallback\"` means neither override nor catalog was available. */\n readonly source: ContextWindowSource;\n /** `true` when an `override` above the catalog window was clamped down to it. */\n readonly clamped: boolean;\n}\n\n/**\n * Absolute cap on a declared context window, applied when no catalog entry exists to compare against.\n *\n * **10M**, not 2M. The first version used 2M on the rationale that it sat \"comfortably above the\n * largest published window\" — adversarial review measured the opposite: Llama 4 Scout publishes\n * **10M**, and it arrives precisely via OpenRouter, the provider **without** a catalog, which is the\n * case this cap exists to cover. The user would have silently lost 80% of the declared window.\n *\n * The cap still serves what motivates it — one extra zero on 400k gives 4M, which passes; two zeros\n * give 40M, which does not. A limit that rejects legitimate configuration is worse than no limit,\n * because failing OPEN is visible when it happens and silently losing 80% is not.\n */\nexport const ABSOLUTE_CONTEXT_WINDOW_CAP = 10_000_000;\n\n/**\n * Resolve the window to budget against — the fail-SAFE replacement for reading the catalog directly.\n *\n * Today `post-run-lifecycle.ts` reads `getCatalogModelInfo(model)?.limit?.context` and, when that is\n * `undefined`, auto-compaction simply never fires. That is fail-OPEN: the context grows until the\n * provider rejects the request. (The comment there calls it \"fail-safe\" — M77 corrects it.)\n *\n * Three techniques, two of them borrowed from the single reference:\n *\n * 1. **Override, CLAMPED by the catalog** — Codex `models-manager/src/model_info.rs:26-31` lets\n * config override the window but limits it with `context_window.min(max_context_window)`.\n * Without the clamp, declaring 999k on a 200k model reopens the overflow through another door.\n * 2. **Multiplicative margin** — Codex `model_info.rs:158` (`effective_context_window_percent: 95`)\n * never budgets against 100% of the window. Being multiplicative, it is conservative for ANY\n * window size.\n * 3. **Floor, only when nothing is known** — deliberately NOT a blanket default. A fixed floor is\n * conservative only upward: applied to a small model it would inflate the assumed window and\n * reproduce the very fail-open this function exists to close. Hence the floor never competes\n * with a known catalog value.\n *\n * Pure — no catalog lookup, no I/O. The caller supplies the numbers, mirroring `shouldCompact`.\n */\nexport function resolveEffectiveContextWindow(\n input: EffectiveContextWindowInput,\n): EffectiveContextWindow {\n if (!(input.margin > 0) || input.margin > 1) {\n throw new ContextWindowMarginError(input.margin);\n }\n\n const withMargin = (raw: number): number => Math.floor(raw * input.margin);\n\n if (input.override !== undefined) {\n // The catalog is the preferred cap; without it the ABSOLUTE cap applies.\n //\n // M95 (adversarial review of M94) — the previous version clamped **only** when a catalog entry\n // existed, and the whole reason the `contextWindow` key exists is the model that has NO entry\n // (OpenRouter has zero). So the clamp was missing in exactly the case that justifies the\n // feature, while the documentation — including an already-published CHANGELOG — stated without\n // qualification that \"declaring 10M does not blow past the provider\".\n //\n // The concrete scenario is one extra zero: `context_window = 4000000`. The only guard was a\n // `.positive().int()`, which sets no upper bound. The agent would never compact until the\n // provider refused the turn — the silent fail-OPEN that M77 exists to prevent.\n const cap = input.catalog ?? ABSOLUTE_CONTEXT_WINDOW_CAP;\n const clamped = input.override > cap;\n return { window: withMargin(clamped ? cap : input.override), source: \"override\", clamped };\n }\n\n if (input.catalog !== undefined) {\n return { window: withMargin(input.catalog), source: \"catalog\", clamped: false };\n }\n\n return { window: withMargin(input.floor ?? 0), source: \"fallback\", clamped: false };\n}\n\n/** Input to {@link shouldCompact}: an estimate, the model's window, and reserved headroom. */\nexport interface ShouldCompactInput {\n /** Estimated token count of the next request (e.g. from {@link estimateTokens}). */\n readonly estimated: number;\n /** The model's total context window, in tokens. */\n readonly contextWindow: number;\n /** Tokens to reserve as headroom (output + safety margin). */\n readonly buffer: number;\n /**\n * Tokens reserved for the model's response generation, SEPARATE from `buffer`.\n * Default 0 — omitting it preserves the legacy\n * `estimated >= contextWindow - buffer` result.\n */\n readonly maxOutput?: number;\n}\n\n/**\n * Tokenizer-free token estimate via the conventional ~4-chars-per-token\n * heuristic: `ceil(text.length / 4)`. `\"\"` → 0; any non-empty text → ≥ 1.\n * A cheap PRE-CALL gate for {@link shouldCompact} — NOT exact tokenization\n * (a consumer needing exactness supplies their own tokenizer). Uses UTF-16\n * `.length` (code units), so multibyte text is approximate.\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\n/**\n * Decide BEFORE sending whether to compact: `true` when the `estimated` token\n * count leaves less than `buffer` headroom in the `contextWindow`\n * (`estimated >= contextWindow - buffer`). A `buffer >= contextWindow`\n * (non-positive threshold) always returns `true`. Pure — the caller supplies\n * the window (e.g. from `resolveModelCapabilities`), keeping this decoupled\n * from the per-model catalog.\n */\nexport function shouldCompact(input: ShouldCompactInput): boolean {\n return input.estimated >= input.contextWindow - input.buffer - (input.maxOutput ?? 0);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TheokitAgentError } from './chunk-
|
|
1
|
+
import { TheokitAgentError } from './chunk-ZZMZWBR6.js';
|
|
2
2
|
import { existsSync, openSync, closeSync, rmSync, readFileSync, writeSync, fchmodSync } from 'fs';
|
|
3
3
|
import { hostname } from 'os';
|
|
4
4
|
|
|
@@ -103,5 +103,5 @@ function createLease(sessionPath, lockPath) {
|
|
|
103
103
|
}
|
|
104
104
|
|
|
105
105
|
export { SessionBusyError, acquireSessionWriter, sessionHasWriter };
|
|
106
|
-
//# sourceMappingURL=chunk-
|
|
107
|
-
//# sourceMappingURL=chunk-
|
|
106
|
+
//# sourceMappingURL=chunk-B3IMEBOA.js.map
|
|
107
|
+
//# sourceMappingURL=chunk-B3IMEBOA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":[],"mappings":";;;;AAmDO,IAAM,gBAAA,GAAN,cAA+B,iBAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WA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AAA,CAAA;AAC/B,EAAA,MAAM,OAAkB,QAAA,EAAS;AACjC,EAAA,IAAI,EAAA;AACJ,EAAA,IAAI;AAEF,IAAA,EAAA,GAAK,QAAA,CAAS,QAAA,EAAU,IAAA,EAAM,GAAK,CAAA;AAAA,EACrC,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,IAAA,KAAS,QAAA,EAAU,MAAM,GAAA;AAI5D,IAAA,IAAI,CAAC,YAAY,SAAA,CAAU,QAAQ,CAAC,CAAA,EAAG,MAAM,IAAI,gBAAA,CAAiB,WAAW,CAAA;AAC7E,IAAA,UAAA,CAAW,UAAU,IAAI,CAAA;AACzB,IAAA,OAAO,WAAA,CAAY,aAAa,QAAQ,CAAA;AAAA,EAC1C;AACA,EAAA,SAAA,CAAU,EAAE,CAAA;AACZ,EAAA,UAAA,CAAW,UAAU,IAAI,CAAA;AAEzB,EAAA,OAAO,WAAA,CAAY,aAAa,QAAQ,CAAA;AAC1C;AAGA,SAAS,WAAA,CAAY,aAAqB,QAAA,EAAsC;AAC9E,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC,CAAA;AAAA,IACA,OAAO,MAAY;AAIjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,UAAA,CAAW,QAAA,EAAU,UAAU,CAAA;AAAA,IACjC;AAAA,GACF;AACF","file":"chunk-44JAAH4X.js","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":[],"mappings":";;;;AAmDO,IAAM,gBAAA,GAAN,cAA+B,iBAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AA0CO,IAAM,mBAAA,GAAsB,GAAA;AAUnC,SAAS,QAAA,GAAsB;AAC7B,EAAA,OAAO,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAK,QAAA,EAAU,UAAS,EAAG,KAAA,EAAO,IAAA,CAAK,GAAA,EAAI,EAAE;AACrE;AAWA,SAAS,UAAA,CAAW,UAAkB,KAAA,EAAwB;AAC5D,EAAA,MAAM,EAAA,GAAK,QAAA,CAAS,QAAA,EAAU,GAAA,EAAK,GAAK,CAAA;AACxC,EAAA,IAAI;AACF,IAAA,SAAA,CAAU,EAAA,EAAI,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAInC,IAAA,UAAA,CAAW,IAAI,GAAK,CAAA;AAAA,EACtB,CAAA,SAAE;AACA,IAAA,SAAA,CAAU,EAAE,CAAA;AAAA,EACd;AACF;AAGA,SAAS,UAAU,QAAA,EAAyC;AAC1D,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,YAAA,CAAa,UAAU,MAAM,CAAA;AAAA,EACrC,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,OAAQ,GAAA,CAA8B,IAAA;AAE5C,IAAA,IAAI,IAAA,KAAS,UAAU,OAAO,M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AAIjB,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,UAAA,CAAW,QAAA,EAAU,UAAU,CAAA;AAAA,IACjC;AAAA,GACF;AACF","file":"chunk-B3IMEBOA.js","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport {\n closeSync,\n existsSync,\n fchmodSync,\n openSync,\n readFileSync,\n rmSync,\n writeSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n /**\n * Re-stamp the ownership record, so a **live** owner never crosses the staleness window.\n *\n * Idempotent and cheap: one `write` of a ~80-byte JSON. Call it on the path that already writes to\n * the session — appending a turn — and the cross-host window stops being a lie about liveness.\n *\n * A no-op after `release()`: renewing a lease you no longer hold would re-create the lock file and\n * hand this process ownership it gave up. That is the one direction of this API that could\n * *create* the double-writer it exists to prevent.\n */\n renew(): void;\n}\n\n/**\n * Staleness window **between machines** — and only between them.\n *\n * 30 s from ACQUISITION. Calling it a \"heartbeat\" would be a lie: the record is written once, when\n * the lease is taken, and is **not** renewed on every write. An earlier version of this comment\n * claimed \"the owner touches the file on every acquisition, so a live process never crosses the\n * window\" — false twice over, and adversarial review measured both.\n *\n * On the **same host** this does not matter: `reclaimable` decides by `pid`, which is exact, and age\n * never enters the calculation. Across hosts it does matter, and it is a real limit: a **live**\n * remote owner loses the lease after 30 s, because there is no way to ask another machine whether\n * its process still exists.\n *\n * **The residue is now closable by the caller** (`agent-builder#118`). `SessionWriterLease.renew()`\n * re-stamps the record; calling it on the path that already writes to the session — appending a turn\n * — keeps a live owner from ever crossing the window. It costs one `write` of ~80 bytes on a file\n * that was previously written once per session.\n *\n * It is `renew()` and not an internal timer on purpose. A timer inside the lease would keep the event\n * loop alive (or need `unref` plus its own teardown), and it would renew a lease belonging to a\n * process that is hung rather than working — which is precisely the state the window exists to\n * detect. Tying the renewal to a real write means the record tracks **progress**, not mere existence.\n */\nexport const HEARTBEAT_WINDOW_MS = 30_000;\n\n/** Who holds the lock. Written as JSON into `.writer.lock`. */\ninterface LockOwner {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/** The ownership record for THIS process, stamped now. One place, so acquire and renew cannot drift. */\nfunction ownerNow(): LockOwner {\n return { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n}\n\n/**\n * Writes the owner with user-only permissions.\n *\n * `0600` because the lock is an assertion of OWNERSHIP: with the `0664` the usual umask produces,\n * another user in the same group can overwrite the file and forge ownership of the session — and\n * from then on it is the legitimate owner who starts receiving `SessionBusyError`. The content\n * (`pid`, `hostname`) is low-sensitivity; what the permission protects is the signal's\n * **integrity**, not its secrecy.\n */\nfunction writeOwner(lockPath: string, owner: LockOwner): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(owner));\n // `open`'s `mode` only applies on CREATION. A `.writer.lock` inherited from an earlier version —\n // or left behind by a process with a different umask — would stay `0664` after being reclaimed,\n // and the forgery window the mode closes for new locks would remain open for old ones.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Reads the lock's owner. `undefined` when the file vanished or the content is unreadable. */\nfunction readOwner(lockPath: string): LockOwner | undefined {\n let raw: string;\n try {\n raw = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — vanished between the `EEXIST` and the read. Benign race: the lock is gone.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — the lock path is a DIRECTORY. No process in this library creates one; it is debris\n // from something else, and it will never become a readable lock. Failing closed here would lock\n // the session out forever. Treated as owner-less: acquisition proceeds and fails with the real\n // FS error, which says what is wrong — instead of a permanent SessionBusyError that says\n // nothing. It is NOT \"reclaimable\": the lock is not removed, and the caller proceeds without a\n // lease.\n if (code === \"EISDIR\") return undefined;\n // Any other read failure (`EACCES` in a shared directory, `EIO`) differs in kind: the lock\n // **exists** and it is we who cannot read the owner. Treating it as free would let two writers\n // coexist — precisely what the lease exists to prevent — and the `0600` that protects the lock\n // against forgery WIDENS that surface: in a shared directory, another user's lock is unreadable\n // by design.\n //\n // Not knowing who the owner is differs from there being no owner. Fail closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(raw) as Partial<LockOwner>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // Unreadable JSON: a lock nobody can interpret must not lock the session out forever. Treating\n // it as stale is the recoverable choice; the cost is the same as that of an old lock.\n return undefined;\n }\n}\n\n/** Does the process exist? `signal 0` sends nothing — it only queries permission/existence. */\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM means it EXISTS and belongs to another user.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Can the lock be taken from whoever holds it?\n *\n * ADR-2 of the plan: reclaiming by `pid` alone has a false positive across machines — the same\n * number exists on another host, pointing at an unrelated process. So:\n *\n * - **same host:** the `pid` is authoritative, and it **alone**. Dead process => reclaimable at\n * once; live process => never, however old the lock is.\n * - **other host:** the `pid` says nothing here. Only the heartbeat window counts, because it is\n * the one signal that does not lie across machines.\n *\n * ## Why age does NOT count on the same host\n *\n * The first version did `stale || !processAlive(pid)`, and that was a serious defect: `mtime` is\n * written at **acquisition** and is not touched on each append, so any session lasting longer than\n * the window — that is, **every real session** — became stealable by another process. Two writers\n * on the same transcript is exactly what the lease exists to prevent.\n *\n * On the same host the question \"does the owner still exist?\" has an exact answer, and age adds no\n * information to it — only a way to be wrong. Keeping the window there would be heuristic layered\n * on top of a fact.\n */\nfunction reclaimable(owner: LockOwner | undefined): boolean {\n if (owner === undefined) return true; // unreadable or vanished\n if (owner.hostname !== hostname()) {\n return Date.now() - owner.mtime > HEARTBEAT_WINDOW_MS;\n }\n return !processAlive(owner.pid);\n}\n\n/**\n * Does the session have a writer **right now**? A query that does NOT take the lease.\n *\n * M95 — it exists because asking by taking creates the very contention it meant to detect: two\n * processes querying a **free** session at the same time made one of them lose, and the consumer\n * forked for no reason. Measured in adversarial review: `RACE: spurious forks = 1`.\n *\n * It is a snapshot, not a guarantee: between the query and the real acquisition someone may take\n * the session. Callers needing the guarantee use {@link acquireSessionWriter}; callers needing to\n * **decide an id before opening anything** use this, and handle the race where it shows up.\n *\n */\nexport function sessionHasWriter(sessionPath: string): boolean {\n const lockPath = `${sessionPath}.writer.lock`;\n if (!existsSync(lockPath)) return false;\n try {\n return !reclaimable(readOwner(lockPath));\n } catch {\n // `readOwner` throws when the lock exists and cannot be read — fail closed, for the same reason\n // as there: not knowing who the owner is differs from there being no owner.\n return true;\n }\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NOT `.lock`.\n //\n // `withFileLock(path, fn)` already uses `<path>.lock` as its companion. While the lease was called\n // from nowhere (the defect this milestone fixes) the collision was theoretical; wiring it to the\n // same file would make the long-lived lease block every short critical section on the same path.\n //\n // Two files because they are two things: `withFileLock` protects a section with a start and an\n // end; the lease is OWNERSHIP, held across turns, with an explicit `release()` — the distinction\n // the M81 docstring above already explains.\n const lockPath = `${sessionPath}.writer.lock`;\n const mine: LockOwner = ownerNow();\n let fd: number;\n try {\n // The mode applies on CREATION — the `w` in `writeOwner` does not alter an existing file.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — the lock exists. Until now that alone was enough to refuse, and that was the defect: a\n // TUI killed by SIGKILL locked the user out of their own session PERMANENTLY, with no documented\n // recovery path. Now the lock says who the owner is, and a dead owner yields its place.\n if (!reclaimable(readOwner(lockPath))) throw new SessionBusyError(sessionPath);\n writeOwner(lockPath, mine);\n return createLease(sessionPath, lockPath);\n }\n closeSync(fd);\n writeOwner(lockPath, mine);\n\n return createLease(sessionPath, lockPath);\n}\n\n/** The lease itself — idempotent `release()`. Extracted because acquisition has two exit paths. */\nfunction createLease(sessionPath: string, lockPath: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n renew: (): void => {\n // A released lease does not own the lock. Re-stamping here would RE-CREATE the file and give\n // this process ownership it explicitly gave up — the one way this method could manufacture the\n // double-writer the lease exists to prevent.\n if (released) return;\n writeOwner(lockPath, ownerNow());\n },\n };\n}\n"]}
|