@theokit/sdk 4.53.1 → 4.55.0
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 +1184 -0
- package/README.md +9 -4
- package/dist/a2a/agent-mailbox.d.cts +27 -0
- package/dist/a2a/agent-mailbox.d.ts +27 -0
- package/dist/a2a/index.cjs +9 -4
- package/dist/a2a/index.cjs.map +1 -1
- package/dist/a2a/index.js +7 -2
- package/dist/a2a/index.js.map +1 -1
- package/dist/a2a/message-bus.d.cts +39 -0
- package/dist/a2a/message-bus.d.ts +39 -0
- package/dist/a2a/subagent.d.cts +68 -7
- package/dist/a2a/subagent.d.ts +68 -7
- package/dist/a2a/types.d.cts +26 -0
- package/dist/a2a/types.d.ts +26 -0
- package/dist/{agent-B9HXlwID.d.ts → agent-D3Xr_-6Z.d.cts} +245 -850
- package/dist/{agent-nLqeXKIX.d.cts → agent-DIu6FooJ.d.ts} +245 -850
- package/dist/agent-HDEVVUBS.js +52 -0
- package/dist/{agent-FFVV4U5N.js.map → agent-HDEVVUBS.js.map} +1 -1
- package/dist/agent-R2HOJFZJ.cjs +61 -0
- package/dist/{agent-YLAHVHEH.cjs.map → agent-R2HOJFZJ.cjs.map} +1 -1
- package/dist/agent-builder.d.ts +19 -0
- package/dist/agent-session-store-P6V3FINW.js +7 -0
- package/dist/{agent-session-store-TNCGL5RN.js.map → agent-session-store-P6V3FINW.js.map} +1 -1
- package/dist/agent-session-store-ZJ3JSRS4.cjs +24 -0
- package/dist/{agent-session-store-DUGBAX5V.cjs.map → agent-session-store-ZJ3JSRS4.cjs.map} +1 -1
- package/dist/agent.d.ts +9 -6
- package/dist/auth/index.cjs +52 -35
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.js +26 -9
- package/dist/auth/index.js.map +1 -1
- package/dist/{batch-UPKN4SG6.js → batch-2TGJMNCJ.js} +14 -13
- package/dist/batch-2TGJMNCJ.js.map +1 -0
- package/dist/{batch-ZEFN5SO7.cjs → batch-ND32UKZS.cjs} +31 -30
- package/dist/batch-ND32UKZS.cjs.map +1 -0
- package/dist/{chunk-TTJ54H3E.cjs → chunk-2ADR2GSO.cjs} +8 -8
- package/dist/chunk-2ADR2GSO.cjs.map +1 -0
- package/dist/chunk-2BDH744Z.js +15 -0
- package/dist/chunk-2BDH744Z.js.map +1 -0
- package/dist/{chunk-VGPXHHF3.cjs → chunk-2C72DXQF.cjs} +63 -27
- package/dist/chunk-2C72DXQF.cjs.map +1 -0
- package/dist/{chunk-4Q4K4WB5.js → chunk-2D34UTDC.js} +20 -4
- package/dist/chunk-2D34UTDC.js.map +1 -0
- package/dist/{chunk-UFIXH26P.js → chunk-2QKTVKH3.js} +4 -4
- package/dist/{chunk-UFIXH26P.js.map → chunk-2QKTVKH3.js.map} +1 -1
- package/dist/{chunk-GBBDINFK.js → chunk-3E77SX4H.js} +4 -4
- package/dist/{chunk-GBBDINFK.js.map → chunk-3E77SX4H.js.map} +1 -1
- package/dist/{chunk-VYHJZVL5.cjs → chunk-3EE6LVWT.cjs} +2 -2
- package/dist/chunk-3EE6LVWT.cjs.map +1 -0
- package/dist/{chunk-5NBUH3NO.js → chunk-3OR54XG4.js} +2 -2
- package/dist/{chunk-C6Y6CWYD.cjs.map → chunk-3OR54XG4.js.map} +1 -1
- package/dist/{chunk-ZN2DGEY3.cjs → chunk-3YJNUKYN.cjs} +15 -15
- package/dist/{chunk-ZN2DGEY3.cjs.map → chunk-3YJNUKYN.cjs.map} +1 -1
- package/dist/{chunk-POWRZSK4.js → chunk-44JAAH4X.js} +3 -3
- package/dist/{chunk-POWRZSK4.js.map → chunk-44JAAH4X.js.map} +1 -1
- package/dist/{chunk-SSDD676S.js → chunk-44MBDIHG.js} +4 -4
- package/dist/{chunk-SSDD676S.js.map → chunk-44MBDIHG.js.map} +1 -1
- package/dist/{chunk-OY7O3Q6R.js → chunk-4ERPXIVB.js} +5 -5
- package/dist/{chunk-OY7O3Q6R.js.map → chunk-4ERPXIVB.js.map} +1 -1
- package/dist/{chunk-3BK6YR5P.cjs → chunk-4I55V454.cjs} +4 -4
- package/dist/{chunk-3BK6YR5P.cjs.map → chunk-4I55V454.cjs.map} +1 -1
- package/dist/{chunk-B4YA6BRS.cjs → chunk-4O5TGQBW.cjs} +30 -7
- package/dist/chunk-4O5TGQBW.cjs.map +1 -0
- package/dist/{chunk-4JBHSLQO.cjs → chunk-4OTIXDMU.cjs} +2 -2
- package/dist/{chunk-4JBHSLQO.cjs.map → chunk-4OTIXDMU.cjs.map} +1 -1
- package/dist/{chunk-C6Y6CWYD.cjs → chunk-52NKC5HT.cjs} +2 -2
- package/dist/chunk-52NKC5HT.cjs.map +1 -0
- package/dist/{chunk-665SFFFR.cjs → chunk-53CBTBWO.cjs} +11 -11
- package/dist/{chunk-665SFFFR.cjs.map → chunk-53CBTBWO.cjs.map} +1 -1
- package/dist/{chunk-FFM3SJTQ.js → chunk-5JLFFPCH.js} +4 -4
- package/dist/{chunk-FFM3SJTQ.js.map → chunk-5JLFFPCH.js.map} +1 -1
- package/dist/{chunk-34XOCZJO.js → chunk-5PHVENFV.js} +3 -3
- package/dist/chunk-5PHVENFV.js.map +1 -0
- package/dist/{chunk-BDTVFIPB.cjs → chunk-5UOVYM3P.cjs} +36 -31
- package/dist/chunk-5UOVYM3P.cjs.map +1 -0
- package/dist/{chunk-VF7X6HDR.cjs → chunk-5USCYPPI.cjs} +15 -15
- package/dist/{chunk-VF7X6HDR.cjs.map → chunk-5USCYPPI.cjs.map} +1 -1
- package/dist/chunk-6HTXPPHK.cjs +18 -0
- package/dist/chunk-6HTXPPHK.cjs.map +1 -0
- package/dist/{chunk-D24WJWN2.js → chunk-AEOZTXVW.js} +3 -3
- package/dist/{chunk-D24WJWN2.js.map → chunk-AEOZTXVW.js.map} +1 -1
- package/dist/{chunk-DGOG5NXR.js → chunk-AG5JPQIY.js} +3 -3
- package/dist/{chunk-DGOG5NXR.js.map → chunk-AG5JPQIY.js.map} +1 -1
- package/dist/{chunk-BFYGJGC5.js → chunk-AQLGBKNT.js} +3 -3
- package/dist/chunk-AQLGBKNT.js.map +1 -0
- package/dist/{chunk-7W7ZWMLQ.js → chunk-AWO27VRZ.js} +3 -3
- package/dist/chunk-AWO27VRZ.js.map +1 -0
- package/dist/{chunk-VYCKUKPA.cjs → chunk-B2J4ZMZL.cjs} +3 -2
- package/dist/chunk-B2J4ZMZL.cjs.map +1 -0
- package/dist/{chunk-BERBYXFH.js → chunk-BMAZLQQ4.js} +3 -3
- package/dist/{chunk-BERBYXFH.js.map → chunk-BMAZLQQ4.js.map} +1 -1
- package/dist/{chunk-5YKNEMXR.cjs → chunk-BVZW2B5V.cjs} +4 -4
- package/dist/chunk-BVZW2B5V.cjs.map +1 -0
- package/dist/{chunk-MSFLYJDY.js → chunk-CQ2TQ32Y.js} +4 -4
- package/dist/chunk-CQ2TQ32Y.js.map +1 -0
- package/dist/{chunk-C5DEO6OI.cjs → chunk-CQGYNZ3K.cjs} +4 -4
- package/dist/{chunk-C5DEO6OI.cjs.map → chunk-CQGYNZ3K.cjs.map} +1 -1
- package/dist/{chunk-D75S2X6I.cjs → chunk-CTCGWIUD.cjs} +5 -5
- package/dist/{chunk-D75S2X6I.cjs.map → chunk-CTCGWIUD.cjs.map} +1 -1
- package/dist/{chunk-NZL4BNFQ.js → chunk-CV7XMBHP.js} +4 -4
- package/dist/chunk-CV7XMBHP.js.map +1 -0
- package/dist/{chunk-SEL2ZQMT.js → chunk-DAPSQZT4.js} +15 -10
- package/dist/chunk-DAPSQZT4.js.map +1 -0
- package/dist/{chunk-SVO5WPZX.cjs → chunk-DQKERTND.cjs} +11 -11
- package/dist/{chunk-SVO5WPZX.cjs.map → chunk-DQKERTND.cjs.map} +1 -1
- package/dist/{chunk-N5CR3TJZ.js → chunk-DZBSJX6J.js} +4 -4
- package/dist/{chunk-N5CR3TJZ.js.map → chunk-DZBSJX6J.js.map} +1 -1
- package/dist/{chunk-RAHSWE5C.cjs → chunk-EI2Q7SJ5.cjs} +12 -12
- package/dist/chunk-EI2Q7SJ5.cjs.map +1 -0
- package/dist/{chunk-UCFONJBG.js → chunk-EPSICJLZ.js} +2 -2
- package/dist/{chunk-UCFONJBG.js.map → chunk-EPSICJLZ.js.map} +1 -1
- package/dist/{chunk-3X6PM7DU.cjs → chunk-F3YZMOAU.cjs} +8 -8
- package/dist/{chunk-3X6PM7DU.cjs.map → chunk-F3YZMOAU.cjs.map} +1 -1
- package/dist/{chunk-F77UENR6.cjs → chunk-F5WMX4EA.cjs} +586 -398
- package/dist/chunk-F5WMX4EA.cjs.map +1 -0
- package/dist/{chunk-HE4BIAOS.js → chunk-F7AQV62G.js} +5 -4
- package/dist/chunk-F7AQV62G.js.map +1 -0
- package/dist/{chunk-2RW7K6FN.cjs → chunk-GHX4P3V2.cjs} +2 -2
- package/dist/chunk-GHX4P3V2.cjs.map +1 -0
- package/dist/{chunk-B6HOIWQ6.js → chunk-GJ6RK75E.js} +5 -5
- package/dist/chunk-GJ6RK75E.js.map +1 -0
- package/dist/{chunk-FOXKFTVZ.cjs → chunk-GNT35C5U.cjs} +13 -13
- package/dist/chunk-GNT35C5U.cjs.map +1 -0
- package/dist/{chunk-4NAKHID5.js → chunk-GTKFV7O5.js} +2 -2
- package/dist/chunk-GTKFV7O5.js.map +1 -0
- package/dist/{chunk-ELKO4ZLR.cjs → chunk-GWC3HADL.cjs} +4 -4
- package/dist/{chunk-ELKO4ZLR.cjs.map → chunk-GWC3HADL.cjs.map} +1 -1
- package/dist/{chunk-OXNYIMZZ.js → chunk-H73MEMQB.js} +2 -2
- package/dist/chunk-H73MEMQB.js.map +1 -0
- package/dist/{chunk-E7FJOO4G.cjs → chunk-HJBMA5MB.cjs} +11 -11
- package/dist/{chunk-E7FJOO4G.cjs.map → chunk-HJBMA5MB.cjs.map} +1 -1
- package/dist/{chunk-2FYEVT2B.cjs → chunk-HLPSLDGL.cjs} +275 -160
- package/dist/chunk-HLPSLDGL.cjs.map +1 -0
- package/dist/{chunk-VW6M4B3Z.cjs → chunk-HY57ULY2.cjs} +5 -5
- package/dist/{chunk-VW6M4B3Z.cjs.map → chunk-HY57ULY2.cjs.map} +1 -1
- package/dist/{chunk-CAH3G4IS.js → chunk-HY66GLM6.js} +2 -2
- package/dist/chunk-HY66GLM6.js.map +1 -0
- package/dist/{chunk-G3JWXOGY.js → chunk-I5BE5M5L.js} +310 -122
- package/dist/chunk-I5BE5M5L.js.map +1 -0
- package/dist/{chunk-C4H6PB5J.cjs → chunk-I6TGFUCO.cjs} +4 -4
- package/dist/{chunk-C4H6PB5J.cjs.map → chunk-I6TGFUCO.cjs.map} +1 -1
- package/dist/{chunk-U4UJHOSH.js → chunk-IDCKSLYH.js} +3 -3
- package/dist/{chunk-U4UJHOSH.js.map → chunk-IDCKSLYH.js.map} +1 -1
- package/dist/{chunk-WQ53UQL4.cjs → chunk-ILCGLTSA.cjs} +4 -4
- package/dist/{chunk-WQ53UQL4.cjs.map → chunk-ILCGLTSA.cjs.map} +1 -1
- package/dist/{chunk-QBTVATSF.cjs → chunk-ITSSOVOB.cjs} +44 -47
- package/dist/chunk-ITSSOVOB.cjs.map +1 -0
- package/dist/{chunk-V6HWJQQV.js → chunk-IVNNSANC.js} +27 -30
- package/dist/chunk-IVNNSANC.js.map +1 -0
- package/dist/{chunk-SZHU7A5B.cjs → chunk-IWBGCBR6.cjs} +4 -4
- package/dist/{chunk-SZHU7A5B.cjs.map → chunk-IWBGCBR6.cjs.map} +1 -1
- package/dist/{chunk-Q4RESANI.cjs → chunk-J24VJOH3.cjs} +20 -4
- package/dist/chunk-J24VJOH3.cjs.map +1 -0
- package/dist/{chunk-Y4AXQOT4.cjs → chunk-JHPGF3FP.cjs} +8 -8
- package/dist/{chunk-Y4AXQOT4.cjs.map → chunk-JHPGF3FP.cjs.map} +1 -1
- package/dist/{chunk-BM6N4KHO.cjs → chunk-JTB5Q42C.cjs} +6 -22
- package/dist/chunk-JTB5Q42C.cjs.map +1 -0
- package/dist/{chunk-LPVIRJVF.cjs → chunk-K3FW2XZD.cjs} +9 -9
- package/dist/{chunk-LPVIRJVF.cjs.map → chunk-K3FW2XZD.cjs.map} +1 -1
- package/dist/{chunk-LS3LMQ23.js → chunk-MVAPK2BX.js} +162 -49
- package/dist/chunk-MVAPK2BX.js.map +1 -0
- package/dist/{chunk-XPR366DL.cjs → chunk-NGESVVJN.cjs} +17 -17
- package/dist/chunk-NGESVVJN.cjs.map +1 -0
- package/dist/{chunk-VUKQL3L2.cjs → chunk-NIRE5CNO.cjs} +20 -13
- package/dist/chunk-NIRE5CNO.cjs.map +1 -0
- package/dist/{chunk-VC5ABJXC.js → chunk-NLTVXLGT.js} +3 -3
- package/dist/{chunk-VC5ABJXC.js.map → chunk-NLTVXLGT.js.map} +1 -1
- package/dist/chunk-NUKRL3I6.cjs +23 -0
- package/dist/chunk-NUKRL3I6.cjs.map +1 -0
- package/dist/{chunk-R5YZACGK.js → chunk-OC4NTGMN.js} +3 -3
- package/dist/{chunk-R5YZACGK.js.map → chunk-OC4NTGMN.js.map} +1 -1
- package/dist/{chunk-GOVJO4YE.js → chunk-OHBIUXKM.js} +6 -6
- package/dist/chunk-OHBIUXKM.js.map +1 -0
- package/dist/{chunk-FPYT5WZP.cjs → chunk-P6A3M6VD.cjs} +10 -10
- package/dist/{chunk-FPYT5WZP.cjs.map → chunk-P6A3M6VD.cjs.map} +1 -1
- package/dist/{chunk-OKLYRPKL.cjs → chunk-Q47R5E2X.cjs} +8 -8
- package/dist/chunk-Q47R5E2X.cjs.map +1 -0
- package/dist/{chunk-HSQ5Q3I5.js → chunk-Q4CMI2LP.js} +12 -5
- package/dist/chunk-Q4CMI2LP.js.map +1 -0
- package/dist/{chunk-2XLKLVVR.js → chunk-Q5EWJPRY.js} +2 -2
- package/dist/chunk-Q5EWJPRY.js.map +1 -0
- package/dist/{chunk-SK4QLUBK.js → chunk-QARJGQSA.js} +16 -7
- package/dist/chunk-QARJGQSA.js.map +1 -0
- package/dist/{chunk-CZ2GKKYL.cjs → chunk-QDED6YO6.cjs} +5 -5
- package/dist/{chunk-CZ2GKKYL.cjs.map → chunk-QDED6YO6.cjs.map} +1 -1
- package/dist/{chunk-VK7MAV65.cjs → chunk-QKLOP4VC.cjs} +2 -2
- package/dist/{chunk-VK7MAV65.cjs.map → chunk-QKLOP4VC.cjs.map} +1 -1
- package/dist/{chunk-FIOCJYLA.js → chunk-QRSUA2CV.js} +3 -3
- package/dist/{chunk-FIOCJYLA.js.map → chunk-QRSUA2CV.js.map} +1 -1
- package/dist/{chunk-ZT57WTUJ.cjs → chunk-R3UPQFKK.cjs} +21 -12
- package/dist/chunk-R3UPQFKK.cjs.map +1 -0
- package/dist/{chunk-X2FR4OIT.js → chunk-R7WIIPUR.js} +2 -2
- package/dist/chunk-R7WIIPUR.js.map +1 -0
- package/dist/{chunk-RP5HQVLD.js → chunk-RNB4APBZ.js} +30 -7
- package/dist/chunk-RNB4APBZ.js.map +1 -0
- package/dist/{chunk-GD63JPGC.cjs → chunk-ROYPRJH4.cjs} +9 -9
- package/dist/{chunk-GD63JPGC.cjs.map → chunk-ROYPRJH4.cjs.map} +1 -1
- package/dist/{chunk-V26QVGUG.js → chunk-RUDY2GTT.js} +59 -23
- package/dist/chunk-RUDY2GTT.js.map +1 -0
- package/dist/{chunk-JIQRXKTA.cjs → chunk-SKXBJ2NU.cjs} +7 -7
- package/dist/chunk-SKXBJ2NU.cjs.map +1 -0
- package/dist/{chunk-XROIW6BH.js → chunk-SUKXXLWD.js} +6 -6
- package/dist/chunk-SUKXXLWD.js.map +1 -0
- package/dist/{chunk-LTSTGCL6.js → chunk-T73NA43R.js} +3 -3
- package/dist/{chunk-LTSTGCL6.js.map → chunk-T73NA43R.js.map} +1 -1
- package/dist/chunk-T7O6K6PX.js +20 -0
- package/dist/chunk-T7O6K6PX.js.map +1 -0
- package/dist/{chunk-5F5NWKPN.js → chunk-T7XEKOVW.js} +5 -20
- package/dist/chunk-T7XEKOVW.js.map +1 -0
- package/dist/{chunk-HAWE74GQ.cjs → chunk-U2AC6JUP.cjs} +8 -8
- package/dist/chunk-U2AC6JUP.cjs.map +1 -0
- package/dist/{chunk-3WVMJY7F.js → chunk-UC3HT2S4.js} +3 -3
- package/dist/{chunk-3WVMJY7F.js.map → chunk-UC3HT2S4.js.map} +1 -1
- package/dist/{chunk-PBZ7HMBP.js → chunk-UPRJR6IP.js} +4 -4
- package/dist/chunk-UPRJR6IP.js.map +1 -0
- package/dist/{chunk-3V7UJLQT.js → chunk-UQGQFBRL.js} +3 -3
- package/dist/chunk-UQGQFBRL.js.map +1 -0
- package/dist/{chunk-2D43RD5D.cjs → chunk-V2UUGUY4.cjs} +27 -27
- package/dist/chunk-V2UUGUY4.cjs.map +1 -0
- package/dist/{chunk-6AZDM6LK.js → chunk-VF7EWVDG.js} +3 -3
- package/dist/{chunk-6AZDM6LK.js.map → chunk-VF7EWVDG.js.map} +1 -1
- package/dist/{chunk-PNVDQL5Y.cjs → chunk-VTYY7XL5.cjs} +2 -2
- package/dist/chunk-VTYY7XL5.cjs.map +1 -0
- package/dist/{chunk-Y4I4EQFK.js → chunk-WKRSH2VR.js} +3 -3
- package/dist/{chunk-Y4I4EQFK.js.map → chunk-WKRSH2VR.js.map} +1 -1
- package/dist/{chunk-4QEC4CCS.js → chunk-WTMU7J4U.js} +2 -2
- package/dist/{chunk-4QEC4CCS.js.map → chunk-WTMU7J4U.js.map} +1 -1
- package/dist/{chunk-KSWHTR54.js → chunk-XN7NOENA.js} +6 -6
- package/dist/chunk-XN7NOENA.js.map +1 -0
- package/dist/{chunk-ADLLFY3H.cjs → chunk-XSX2UU6Y.cjs} +10 -9
- package/dist/chunk-XSX2UU6Y.cjs.map +1 -0
- package/dist/{chunk-LD4MOBFX.js → chunk-XV4IZNV4.js} +9 -9
- package/dist/chunk-XV4IZNV4.js.map +1 -0
- package/dist/{chunk-EZ2YEF4F.cjs → chunk-XWL6O3SW.cjs} +4 -4
- package/dist/chunk-XWL6O3SW.cjs.map +1 -0
- package/dist/{chunk-PGP7IOJ2.js → chunk-YMA4S2WO.js} +4 -4
- package/dist/{chunk-PGP7IOJ2.js.map → chunk-YMA4S2WO.js.map} +1 -1
- package/dist/{chunk-OUOXM36O.cjs → chunk-YPJ5NH5N.cjs} +11 -11
- package/dist/chunk-YPJ5NH5N.cjs.map +1 -0
- package/dist/{chunk-YLQQX5W2.cjs → chunk-ZF2LDKQQ.cjs} +2 -2
- package/dist/chunk-ZF2LDKQQ.cjs.map +1 -0
- package/dist/{chunk-L5YO6PWL.cjs → chunk-ZNW6V4Y6.cjs} +2 -2
- package/dist/chunk-ZNW6V4Y6.cjs.map +1 -0
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/theokit-client.d.cts +36 -0
- package/dist/client/theokit-client.d.ts +36 -0
- package/dist/client/types.d.cts +30 -0
- package/dist/client/types.d.ts +30 -0
- package/dist/compact-session-FUJDVF7B.js +22 -0
- package/dist/{compact-session-4MNKNMO2.js.map → compact-session-FUJDVF7B.js.map} +1 -1
- package/dist/compact-session-LEWF554G.cjs +59 -0
- package/dist/{compact-session-EPFBQ46Z.cjs.map → compact-session-LEWF554G.cjs.map} +1 -1
- package/dist/compaction.cjs +17 -16
- package/dist/compaction.d.cts +13 -13
- package/dist/compaction.d.ts +13 -13
- package/dist/compaction.js +4 -3
- package/dist/concurrency.cjs +7 -6
- package/dist/concurrency.cjs.map +1 -1
- package/dist/concurrency.js +5 -4
- package/dist/concurrency.js.map +1 -1
- package/dist/context/index.cjs +7 -7
- package/dist/context/index.js +3 -3
- package/dist/context-FDOON2DB.js +6 -0
- package/dist/{context-ENXZNF6J.js.map → context-FDOON2DB.js.map} +1 -1
- package/dist/context-VMIE4BMD.cjs +23 -0
- package/dist/{context-7USNN6LP.cjs.map → context-VMIE4BMD.cjs.map} +1 -1
- package/dist/cron-BcWmzWzT.d.cts +240 -0
- package/dist/cron-De6hzWCF.d.ts +240 -0
- package/dist/cron.cjs +43 -41
- package/dist/cron.d.cts +5 -3
- package/dist/cron.d.ts +5 -3
- package/dist/cron.js +42 -40
- package/dist/define-tool.d.ts +14 -6
- package/dist/{errors-BSoXcl3F.d.cts → errors-BgJH9PHi.d.cts} +39 -24
- package/dist/{errors-CHllybaU.d.ts → errors-C5fJUqLk.d.ts} +39 -24
- package/dist/errors.cjs +22 -21
- package/dist/errors.d.cts +2 -2
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +3 -2
- package/dist/eval.cjs +61 -58
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.d.cts +38 -0
- package/dist/eval.d.ts +38 -0
- package/dist/eval.js +51 -48
- package/dist/eval.js.map +1 -1
- package/dist/event-bus.d.ts +16 -0
- package/dist/{executor-2Z6XJJJG.js → executor-BMEHFOXZ.js} +8 -7
- package/dist/executor-BMEHFOXZ.js.map +1 -0
- package/dist/{executor-2Z3LGG3I.cjs → executor-ZERJ3DGN.cjs} +25 -24
- package/dist/executor-ZERJ3DGN.cjs.map +1 -0
- package/dist/filesystem/index.cjs +8 -7
- package/dist/filesystem/index.cjs.map +1 -1
- package/dist/filesystem/index.js +4 -3
- package/dist/filesystem/index.js.map +1 -1
- package/dist/filesystem/local-filesystem.d.cts +18 -0
- package/dist/filesystem/local-filesystem.d.ts +18 -0
- package/dist/filesystem/types.d.cts +12 -0
- package/dist/filesystem/types.d.ts +12 -0
- package/dist/fs-session-store-3MOJQGP2.cjs +20 -0
- package/dist/{fs-session-store-VVY2AHWG.cjs.map → fs-session-store-3MOJQGP2.cjs.map} +1 -1
- package/dist/fs-session-store-IN7JTTXD.js +11 -0
- package/dist/{fs-session-store-R5FD3EN6.js.map → fs-session-store-IN7JTTXD.js.map} +1 -1
- package/dist/generate-object-N5MDZUJI.js +8 -0
- package/dist/{generate-object-WQRCXFD2.js.map → generate-object-N5MDZUJI.js.map} +1 -1
- package/dist/generate-object-PGSP5U7N.cjs +21 -0
- package/dist/{generate-object-AVXOJK2I.cjs.map → generate-object-PGSP5U7N.cjs.map} +1 -1
- package/dist/generate-object.d.ts +20 -0
- package/dist/index-manager-NG5YENWO.cjs +22 -0
- package/dist/{index-manager-VRU3A2YL.cjs.map → index-manager-NG5YENWO.cjs.map} +1 -1
- package/dist/index-manager-ZMRJ6ZII.js +13 -0
- package/dist/{index-manager-WS7TVKUW.js.map → index-manager-ZMRJ6ZII.js.map} +1 -1
- package/dist/index.cjs +169 -155
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +702 -54
- package/dist/index.d.ts +702 -54
- package/dist/index.js +61 -58
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-GMBMJVNZ.js → inject-session-BJMJH5BX.js} +9 -8
- package/dist/inject-session-BJMJH5BX.js.map +1 -0
- package/dist/inject-session-WQGGMCQY.cjs +29 -0
- package/dist/inject-session-WQGGMCQY.cjs.map +1 -0
- package/dist/internal/auth/auth-types.d.ts +83 -1
- package/dist/internal/auth/credential-store.d.ts +34 -6
- package/dist/internal/auth/oauth-device.d.ts +0 -1
- package/dist/internal/auth/resolve-credential.d.ts +40 -0
- package/dist/internal/budget/tracker/budget.d.ts +12 -14
- package/dist/internal/budget/usage-accumulator.d.ts +15 -0
- package/dist/internal/llm/anthropic-shared.d.ts +8 -4
- package/dist/internal/llm/model-identifier.d.ts +26 -0
- package/dist/internal/llm/openai.d.ts +8 -0
- package/dist/internal/llm/prompt-cache-key.d.ts +1 -0
- package/dist/internal/llm/responses.d.ts +67 -1
- package/dist/internal/llm/router.d.ts +8 -0
- package/dist/internal/llm/types.d.ts +27 -1
- package/dist/internal/local-agent/real-local-run-provider.d.ts +8 -3
- package/dist/internal/local-agent/real-local-run-tools.d.ts +23 -4
- package/dist/internal/mcp/oauth.d.ts +5 -0
- package/dist/internal/mcp/token-storage.d.ts +34 -0
- package/dist/internal/memory/adapters/index.cjs +12 -11
- package/dist/internal/memory/adapters/index.d.cts +3 -1
- package/dist/internal/memory/adapters/index.d.ts +3 -1
- package/dist/internal/memory/adapters/index.js +9 -8
- package/dist/internal/memory/adapters/openai-compatible.d.cts +45 -0
- package/dist/internal/memory/adapters/openai-compatible.d.ts +45 -0
- package/dist/internal/memory/embedding-cache.d.ts +42 -1
- package/dist/internal/memory/escape-like-pattern.d.ts +22 -0
- package/dist/internal/memory/sqlite-vec-loader.d.ts +1 -3
- package/dist/internal/memory/storage/markdown-store.d.ts +0 -5
- package/dist/internal/persistence/cwd-mutex.d.cts +34 -0
- package/dist/internal/persistence/cwd-mutex.d.ts +34 -0
- package/dist/internal/persistence/exclusive-create.d.cts +31 -0
- package/dist/internal/persistence/exclusive-create.d.ts +31 -0
- package/dist/internal/persistence/file-lock.d.cts +28 -0
- package/dist/internal/persistence/file-lock.d.ts +28 -0
- package/dist/internal/persistence/fs-session-store.d.cts +3 -0
- package/dist/internal/persistence/fs-session-store.d.ts +3 -0
- package/dist/internal/persistence/fts5-sanitize.d.cts +20 -0
- package/dist/internal/persistence/fts5-sanitize.d.ts +20 -0
- package/dist/internal/persistence/index.cjs +40 -39
- package/dist/internal/persistence/index.cjs.map +1 -1
- package/dist/internal/persistence/index.d.cts +6 -1
- package/dist/internal/persistence/index.d.ts +6 -1
- package/dist/internal/persistence/index.js +9 -8
- package/dist/internal/persistence/index.js.map +1 -1
- package/dist/internal/persistence/paths.d.cts +54 -1
- package/dist/internal/persistence/paths.d.ts +54 -1
- package/dist/internal/persistence/persistence-schema.d.cts +9 -1
- package/dist/internal/persistence/persistence-schema.d.ts +9 -1
- package/dist/internal/persistence/schema-version.d.cts +215 -1
- package/dist/internal/persistence/schema-version.d.ts +215 -1
- package/dist/internal/persistence/session-writer.d.cts +7 -7
- package/dist/internal/persistence/session-writer.d.ts +7 -7
- package/dist/internal/persistence/sqlite-cas.d.cts +37 -1
- package/dist/internal/persistence/sqlite-cas.d.ts +37 -1
- package/dist/internal/persistence/sqlite-open.d.cts +14 -0
- package/dist/internal/persistence/sqlite-open.d.ts +14 -0
- package/dist/internal/persistence/sqlite-wal.d.cts +45 -0
- package/dist/internal/persistence/sqlite-wal.d.ts +45 -0
- package/dist/internal/persistence/transcript-ops.d.cts +7 -1
- package/dist/internal/persistence/transcript-ops.d.ts +7 -1
- package/dist/internal/plugins/types.d.cts +1 -1
- package/dist/internal/plugins/types.d.ts +1 -1
- package/dist/internal/providers/builtin/openai-chatgpt.d.ts +12 -0
- package/dist/internal/providers/catalog-loader.d.ts +8 -0
- package/dist/internal/providers/catalog-schema.d.ts +55 -0
- package/dist/internal/providers/catalog-source-models-dev.d.ts +36 -0
- package/dist/internal/runtime/concurrency/delegation-depth.d.ts +27 -0
- package/dist/internal/runtime/concurrency/subagent-credentials.d.ts +33 -1
- package/dist/internal/runtime/context/context-discovery-runner.d.ts +44 -0
- package/dist/internal/runtime/context/context-discovery.d.ts +58 -0
- package/dist/internal/runtime/context/context-rules-frontmatter.d.ts +70 -1
- package/dist/internal/runtime/fixtures/fixture-mode.d.ts +15 -1
- package/dist/internal/runtime/lifecycle/post-run-lifecycle.d.ts +15 -0
- package/dist/internal/runtime/registry/agent-registry-store.d.ts +12 -0
- package/dist/internal/runtime/registry/live-agent-registry.d.ts +37 -0
- package/dist/internal/scorers/llm-judge.d.ts +6 -1
- package/dist/internal/security/index.cjs +14 -13
- package/dist/internal/security/index.d.cts +4 -1
- package/dist/internal/security/index.d.ts +4 -1
- package/dist/internal/security/index.js +4 -3
- package/dist/internal/security/path-guard.d.cts +46 -0
- package/dist/internal/security/path-guard.d.ts +46 -0
- package/dist/internal/security/redact.d.cts +71 -0
- package/dist/internal/security/redact.d.ts +71 -0
- package/dist/internal/session/agent-session.d.ts +15 -4
- package/dist/internal/session/session-cache.d.ts +5 -0
- package/dist/internal/task/store.d.ts +91 -5
- package/dist/internal/telemetry/span-names.d.ts +0 -1
- package/dist/internal/telemetry/tracer.d.ts +14 -0
- package/dist/job-queue.d.ts +18 -0
- package/dist/judge-call-DWHAJATE.js +6 -0
- package/dist/{judge-call-MDIPTBJI.js.map → judge-call-DWHAJATE.js.map} +1 -1
- package/dist/judge-call-EGYRC2RE.cjs +23 -0
- package/dist/{judge-call-G5SGV2M2.cjs.map → judge-call-EGYRC2RE.cjs.map} +1 -1
- package/dist/mcp-auth.cjs +41 -25
- package/dist/mcp-auth.cjs.map +1 -1
- package/dist/mcp-auth.js +34 -18
- package/dist/mcp-auth.js.map +1 -1
- package/dist/models.cjs +42 -27
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +25 -10
- package/dist/models.js.map +1 -1
- package/dist/oauth-transaction-store-BT4GLTLK.cjs +36 -0
- package/dist/{oauth-transaction-store-7CKHPQRN.cjs.map → oauth-transaction-store-BT4GLTLK.cjs.map} +1 -1
- package/dist/oauth-transaction-store-W52KVHQ4.js +3 -0
- package/dist/{oauth-transaction-store-W74I6EFD.js.map → oauth-transaction-store-W52KVHQ4.js.map} +1 -1
- package/dist/path-safety.cjs +11 -10
- package/dist/path-safety.js +4 -3
- package/dist/permission-engine.d.ts +55 -0
- package/dist/persistence.cjs +43 -42
- package/dist/persistence.cjs.map +1 -1
- package/dist/persistence.js +13 -12
- package/dist/persistence.js.map +1 -1
- package/dist/project.cjs +9 -8
- package/dist/project.cjs.map +1 -1
- package/dist/project.js +5 -4
- package/dist/project.js.map +1 -1
- package/dist/providers.cjs +23 -0
- package/dist/providers.cjs.map +1 -0
- package/dist/providers.d.cts +29 -0
- package/dist/providers.d.ts +29 -0
- package/dist/providers.js +10 -0
- package/dist/providers.js.map +1 -0
- package/dist/registry-VFKX7WOP.cjs +47 -0
- package/dist/{registry-63ASMXT4.cjs.map → registry-VFKX7WOP.cjs.map} +1 -1
- package/dist/registry-VFP3WWQP.js +10 -0
- package/dist/{registry-O7FJ2MPM.js.map → registry-VFP3WWQP.js.map} +1 -1
- package/dist/retry.cjs +5 -4
- package/dist/retry.js +4 -3
- package/dist/{run-C8FBAC8o.d.cts → run-BYSHf58D.d.cts} +185 -33
- package/dist/{run-C8FBAC8o.d.ts → run-BYSHf58D.d.ts} +185 -33
- package/dist/{run-to-completion-JDPIUKSH.js → run-to-completion-DRO77625.js} +3 -3
- package/dist/{run-to-completion-JDPIUKSH.js.map → run-to-completion-DRO77625.js.map} +1 -1
- package/dist/{run-to-completion-J73I6IY4.cjs → run-to-completion-X4OWM673.cjs} +13 -13
- package/dist/{run-to-completion-J73I6IY4.cjs.map → run-to-completion-X4OWM673.cjs.map} +1 -1
- package/dist/sandbox/bwrap.d.cts +27 -13
- package/dist/sandbox/bwrap.d.ts +27 -13
- package/dist/sandbox/index.cjs +20 -19
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.js +5 -4
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/linux-sandbox.d.cts +72 -0
- package/dist/sandbox/linux-sandbox.d.ts +72 -0
- package/dist/sandbox/local-sandbox.d.cts +41 -0
- package/dist/sandbox/local-sandbox.d.ts +41 -0
- package/dist/sandbox/seccomp.d.cts +6 -0
- package/dist/sandbox/seccomp.d.ts +6 -0
- package/dist/sandbox/types.d.cts +64 -0
- package/dist/sandbox/types.d.ts +64 -0
- package/dist/scorers.d.ts +38 -7
- package/dist/sdk-agent-D8qJVkuV.d.ts +860 -0
- package/dist/sdk-agent-DEoKhA8a.d.cts +860 -0
- package/dist/server/auth/errors.d.cts +1 -1
- package/dist/server/auth/errors.d.ts +1 -1
- package/dist/server/auth/index.cjs +29 -21
- package/dist/server/auth/index.cjs.map +1 -1
- package/dist/server/auth/index.d.cts +25 -15
- package/dist/server/auth/index.d.ts +25 -15
- package/dist/server/auth/index.js +15 -7
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/auth/oauth-transaction-store.d.cts +13 -1
- package/dist/server/auth/oauth-transaction-store.d.ts +13 -1
- package/dist/server/auth/orchestrator.d.cts +1 -1
- package/dist/server/auth/orchestrator.d.ts +1 -1
- package/dist/server/auth/types.d.cts +1 -1
- package/dist/server/auth/types.d.ts +1 -1
- package/dist/server/auth/validate-return-to.d.cts +21 -11
- package/dist/server/auth/validate-return-to.d.ts +21 -11
- package/dist/server/errors-envelope.cjs +15 -14
- package/dist/server/errors-envelope.cjs.map +1 -1
- package/dist/server/errors-envelope.d.cts +4 -4
- package/dist/server/errors-envelope.d.ts +4 -4
- package/dist/server/errors-envelope.js +4 -3
- package/dist/server/errors-envelope.js.map +1 -1
- package/dist/session-transcript-AKDYYGXQ.js +6 -0
- package/dist/{session-transcript-RAKEK76V.js.map → session-transcript-AKDYYGXQ.js.map} +1 -1
- package/dist/session-transcript-JXHFTB7G.cjs +51 -0
- package/dist/{session-transcript-DOM3UTXR.cjs.map → session-transcript-JXHFTB7G.cjs.map} +1 -1
- package/dist/skills.cjs +8 -7
- package/dist/skills.js +6 -5
- package/dist/stream-object-BUCF5PHO.cjs +21 -0
- package/dist/{stream-object-L3Q7PBMF.cjs.map → stream-object-BUCF5PHO.cjs.map} +1 -1
- package/dist/stream-object-L57K4OFS.js +8 -0
- package/dist/{stream-object-ZYXWS4B2.js.map → stream-object-L57K4OFS.js.map} +1 -1
- package/dist/{stream-to-completion-DFJ5T3BK.js → stream-to-completion-QV5HCL3J.js} +3 -3
- package/dist/{stream-to-completion-DFJ5T3BK.js.map → stream-to-completion-QV5HCL3J.js.map} +1 -1
- package/dist/{stream-to-completion-H2MHISSK.cjs → stream-to-completion-SRISU5AB.cjs} +10 -10
- package/dist/{stream-to-completion-H2MHISSK.cjs.map → stream-to-completion-SRISU5AB.cjs.map} +1 -1
- package/dist/subagents-loader-AZIXJ7D3.cjs +16 -0
- package/dist/{subagents-loader-VRW73QQT.cjs.map → subagents-loader-AZIXJ7D3.cjs.map} +1 -1
- package/dist/subagents-loader-J54ESLDV.js +7 -0
- package/dist/{subagents-loader-I56GSKAQ.js.map → subagents-loader-J54ESLDV.js.map} +1 -1
- package/dist/subagents-loader.cjs +7 -6
- package/dist/subagents-loader.cjs.map +1 -1
- package/dist/subagents-loader.d.cts +3 -2
- package/dist/subagents-loader.d.ts +3 -2
- package/dist/subagents-loader.js +5 -4
- package/dist/subagents-loader.js.map +1 -1
- package/dist/subscription/define-subscription.d.cts +1 -1
- package/dist/subscription/define-subscription.d.ts +1 -1
- package/dist/subscription/index.cjs +22 -9
- package/dist/subscription/index.cjs.map +1 -1
- package/dist/subscription/index.d.cts +1 -1
- package/dist/subscription/index.d.ts +1 -1
- package/dist/subscription/index.js +21 -8
- package/dist/subscription/index.js.map +1 -1
- package/dist/subscription/internal/adapter-types.d.cts +1 -1
- package/dist/subscription/internal/adapter-types.d.ts +1 -1
- package/dist/subscription/internal/server-integration.d.cts +1 -1
- package/dist/subscription/internal/server-integration.d.ts +1 -1
- package/dist/subscription/internal/sse-encoder.d.cts +1 -1
- package/dist/subscription/internal/sse-encoder.d.ts +1 -1
- package/dist/subscription/internal/sse-parser.d.cts +1 -1
- package/dist/subscription/internal/sse-parser.d.ts +1 -1
- package/dist/subscription/internal/subscription-runtime.d.cts +1 -1
- package/dist/subscription/internal/subscription-runtime.d.ts +1 -1
- package/dist/subscription/internal/ws-adapter-node.d.cts +1 -1
- package/dist/subscription/internal/ws-adapter-node.d.ts +1 -1
- package/dist/subscription/theokit-subscribe.d.cts +14 -1
- package/dist/subscription/theokit-subscribe.d.ts +14 -1
- package/dist/subscription/types.d.cts +19 -1
- package/dist/subscription/types.d.ts +19 -1
- package/dist/task-store.cjs +8 -7
- package/dist/task-store.js +5 -4
- package/dist/types/agent-prims.d.ts +14 -0
- package/dist/types/agent.d.ts +92 -11
- package/dist/types/batch.d.ts +7 -1
- package/dist/types/conversation.d.ts +18 -5
- package/dist/types/goal-events.d.ts +4 -8
- package/dist/types/memory-adapter.d.ts +12 -1
- package/dist/types/plugin.d.ts +101 -0
- package/dist/types/provider-profile.d.ts +32 -0
- package/dist/types/run-events.d.ts +28 -1
- package/dist/types/run.d.ts +35 -23
- package/dist/types/sdk-agent.d.ts +14 -0
- package/dist/types/session-record.d.ts +18 -1
- package/dist/types/task.d.ts +15 -1
- package/dist/types/theokit.d.ts +10 -1
- package/dist/types/updates.d.ts +35 -4
- package/dist/types/workflow.d.ts +155 -0
- package/dist/workflow.cjs +29 -28
- package/dist/workflow.d.cts +666 -17
- package/dist/workflow.d.ts +666 -17
- package/dist/workflow.js +8 -7
- package/docs/error-codes.md +215 -0
- package/docs/harness-capability-map.md +1358 -0
- package/package.json +29 -16
- package/bin/init-claude.mjs +0 -68
- package/claude-template/AGENTS.md +0 -157
- package/claude-template/CLAUDE.md +0 -66
- package/claude-template/dot-claude/rules/theokit-conventions.md +0 -32
- package/claude-template/dot-claude/settings.json +0 -16
- package/claude-template/dot-claude/skills/theokit-agent-core/SKILL.md +0 -209
- package/claude-template/dot-claude/skills/theokit-auth/SKILL.md +0 -102
- package/claude-template/dot-claude/skills/theokit-budget/SKILL.md +0 -176
- package/claude-template/dot-claude/skills/theokit-client/SKILL.md +0 -58
- package/claude-template/dot-claude/skills/theokit-compaction/SKILL.md +0 -102
- package/claude-template/dot-claude/skills/theokit-concurrency/SKILL.md +0 -68
- package/claude-template/dot-claude/skills/theokit-config/SKILL.md +0 -139
- package/claude-template/dot-claude/skills/theokit-cron/SKILL.md +0 -148
- package/claude-template/dot-claude/skills/theokit-di/SKILL.md +0 -233
- package/claude-template/dot-claude/skills/theokit-di-agent/SKILL.md +0 -294
- package/claude-template/dot-claude/skills/theokit-errors/SKILL.md +0 -172
- package/claude-template/dot-claude/skills/theokit-eval/SKILL.md +0 -179
- package/claude-template/dot-claude/skills/theokit-filesystem/SKILL.md +0 -74
- package/claude-template/dot-claude/skills/theokit-gateways/SKILL.md +0 -209
- package/claude-template/dot-claude/skills/theokit-memory/SKILL.md +0 -176
- package/claude-template/dot-claude/skills/theokit-messages/SKILL.md +0 -58
- package/claude-template/dot-claude/skills/theokit-models/SKILL.md +0 -79
- package/claude-template/dot-claude/skills/theokit-path-safety/SKILL.md +0 -60
- package/claude-template/dot-claude/skills/theokit-persistence/SKILL.md +0 -85
- package/claude-template/dot-claude/skills/theokit-project/SKILL.md +0 -55
- package/claude-template/dot-claude/skills/theokit-retry/SKILL.md +0 -50
- package/claude-template/dot-claude/skills/theokit-sandbox/SKILL.md +0 -93
- package/claude-template/dot-claude/skills/theokit-sanitize/SKILL.md +0 -66
- package/claude-template/dot-claude/skills/theokit-skills/SKILL.md +0 -68
- package/claude-template/dot-claude/skills/theokit-streaming/SKILL.md +0 -156
- package/claude-template/dot-claude/skills/theokit-subagents/SKILL.md +0 -109
- package/claude-template/dot-claude/skills/theokit-subscriptions/SKILL.md +0 -148
- package/claude-template/dot-claude/skills/theokit-task-store/SKILL.md +0 -75
- package/claude-template/dot-claude/skills/theokit-tools/SKILL.md +0 -170
- package/claude-template/dot-claude/skills/theokit-workflows/SKILL.md +0 -218
- package/dist/agent-FFVV4U5N.js +0 -50
- package/dist/agent-YLAHVHEH.cjs +0 -59
- package/dist/agent-session-store-DUGBAX5V.cjs +0 -23
- package/dist/agent-session-store-TNCGL5RN.js +0 -6
- package/dist/batch-UPKN4SG6.js.map +0 -1
- package/dist/batch-ZEFN5SO7.cjs.map +0 -1
- package/dist/chunk-2D43RD5D.cjs.map +0 -1
- package/dist/chunk-2FYEVT2B.cjs.map +0 -1
- package/dist/chunk-2RW7K6FN.cjs.map +0 -1
- package/dist/chunk-2XLKLVVR.js.map +0 -1
- package/dist/chunk-34XOCZJO.js.map +0 -1
- package/dist/chunk-3V7UJLQT.js.map +0 -1
- package/dist/chunk-4NAKHID5.js.map +0 -1
- package/dist/chunk-4Q4K4WB5.js.map +0 -1
- package/dist/chunk-5F5NWKPN.js.map +0 -1
- package/dist/chunk-5NBUH3NO.js.map +0 -1
- package/dist/chunk-5YKNEMXR.cjs.map +0 -1
- package/dist/chunk-7W7ZWMLQ.js.map +0 -1
- package/dist/chunk-ADLLFY3H.cjs.map +0 -1
- package/dist/chunk-B4YA6BRS.cjs.map +0 -1
- package/dist/chunk-B6HOIWQ6.js.map +0 -1
- package/dist/chunk-BDTVFIPB.cjs.map +0 -1
- package/dist/chunk-BFYGJGC5.js.map +0 -1
- package/dist/chunk-BM6N4KHO.cjs.map +0 -1
- package/dist/chunk-CAH3G4IS.js.map +0 -1
- package/dist/chunk-EZ2YEF4F.cjs.map +0 -1
- package/dist/chunk-F77UENR6.cjs.map +0 -1
- package/dist/chunk-FOXKFTVZ.cjs.map +0 -1
- package/dist/chunk-G3JWXOGY.js.map +0 -1
- package/dist/chunk-GOVJO4YE.js.map +0 -1
- package/dist/chunk-HAWE74GQ.cjs.map +0 -1
- package/dist/chunk-HE4BIAOS.js.map +0 -1
- package/dist/chunk-HSQ5Q3I5.js.map +0 -1
- package/dist/chunk-JIQRXKTA.cjs.map +0 -1
- package/dist/chunk-KSWHTR54.js.map +0 -1
- package/dist/chunk-L5YO6PWL.cjs.map +0 -1
- package/dist/chunk-LD4MOBFX.js.map +0 -1
- package/dist/chunk-LS3LMQ23.js.map +0 -1
- package/dist/chunk-MSFLYJDY.js.map +0 -1
- package/dist/chunk-NZL4BNFQ.js.map +0 -1
- package/dist/chunk-OKLYRPKL.cjs.map +0 -1
- package/dist/chunk-OUOXM36O.cjs.map +0 -1
- package/dist/chunk-OXNYIMZZ.js.map +0 -1
- package/dist/chunk-PBZ7HMBP.js.map +0 -1
- package/dist/chunk-PNVDQL5Y.cjs.map +0 -1
- package/dist/chunk-Q4RESANI.cjs.map +0 -1
- package/dist/chunk-QBTVATSF.cjs.map +0 -1
- package/dist/chunk-RAHSWE5C.cjs.map +0 -1
- package/dist/chunk-RP5HQVLD.js.map +0 -1
- package/dist/chunk-SEL2ZQMT.js.map +0 -1
- package/dist/chunk-SK4QLUBK.js.map +0 -1
- package/dist/chunk-TTJ54H3E.cjs.map +0 -1
- package/dist/chunk-V26QVGUG.js.map +0 -1
- package/dist/chunk-V6HWJQQV.js.map +0 -1
- package/dist/chunk-VGPXHHF3.cjs.map +0 -1
- package/dist/chunk-VUKQL3L2.cjs.map +0 -1
- package/dist/chunk-VYCKUKPA.cjs.map +0 -1
- package/dist/chunk-VYHJZVL5.cjs.map +0 -1
- package/dist/chunk-X2FR4OIT.js.map +0 -1
- package/dist/chunk-XPR366DL.cjs.map +0 -1
- package/dist/chunk-XROIW6BH.js.map +0 -1
- package/dist/chunk-YLQQX5W2.cjs.map +0 -1
- package/dist/chunk-ZT57WTUJ.cjs.map +0 -1
- package/dist/compact-session-4MNKNMO2.js +0 -21
- package/dist/compact-session-EPFBQ46Z.cjs +0 -58
- package/dist/context-7USNN6LP.cjs +0 -22
- package/dist/context-ENXZNF6J.js +0 -5
- package/dist/cron-BMjgFH-_.d.ts +0 -631
- package/dist/cron-DFDdCdMM.d.cts +0 -631
- package/dist/executor-2Z3LGG3I.cjs.map +0 -1
- package/dist/executor-2Z6XJJJG.js.map +0 -1
- package/dist/fs-session-store-R5FD3EN6.js +0 -10
- package/dist/fs-session-store-VVY2AHWG.cjs +0 -19
- package/dist/generate-object-AVXOJK2I.cjs +0 -20
- package/dist/generate-object-WQRCXFD2.js +0 -7
- package/dist/index-manager-VRU3A2YL.cjs +0 -21
- package/dist/index-manager-WS7TVKUW.js +0 -12
- package/dist/inject-session-AUQLBDRS.cjs +0 -28
- package/dist/inject-session-AUQLBDRS.cjs.map +0 -1
- package/dist/inject-session-GMBMJVNZ.js.map +0 -1
- package/dist/judge-call-G5SGV2M2.cjs +0 -22
- package/dist/judge-call-MDIPTBJI.js +0 -5
- package/dist/oauth-transaction-store-7CKHPQRN.cjs +0 -32
- package/dist/oauth-transaction-store-W74I6EFD.js +0 -3
- package/dist/registry-63ASMXT4.cjs +0 -46
- package/dist/registry-O7FJ2MPM.js +0 -9
- package/dist/session-transcript-DOM3UTXR.cjs +0 -50
- package/dist/session-transcript-RAKEK76V.js +0 -5
- package/dist/stream-object-L3Q7PBMF.cjs +0 -20
- package/dist/stream-object-ZYXWS4B2.js +0 -7
- package/dist/subagents-loader-I56GSKAQ.js +0 -6
- package/dist/subagents-loader-VRW73QQT.cjs +0 -15
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/compression/compression-helpers.ts","../src/compaction.ts"],"names":["TheokitAgentError","diag","redactSecrets"],"mappings":";;;;;;;AA0BO,SAAS,uBAAA,CACd,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A,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-XSX2UU6Y.cjs","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,7 +1,7 @@
|
|
|
1
|
-
import { WorkflowNestedError, WorkflowDuplicateStepIdError } from './chunk-
|
|
2
|
-
import { PersistenceSchema } from './chunk-
|
|
1
|
+
import { WorkflowNestedError, WorkflowDuplicateStepIdError } from './chunk-AQLGBKNT.js';
|
|
2
|
+
import { PersistenceSchema } from './chunk-HY66GLM6.js';
|
|
3
3
|
import { toJsonSchema } from './chunk-4VPXM6UU.js';
|
|
4
|
-
import { sanitizeIdentifier } from './chunk-
|
|
4
|
+
import { sanitizeIdentifier } from './chunk-QARJGQSA.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
|
|
7
7
|
// src/internal/workflow/event-stream.ts
|
|
@@ -246,10 +246,10 @@ var Workflow = class {
|
|
|
246
246
|
* `run.status === "failed"`.
|
|
247
247
|
*/
|
|
248
248
|
async run(input, opts) {
|
|
249
|
-
const { executeWorkflow } = await import('./executor-
|
|
249
|
+
const { executeWorkflow } = await import('./executor-BMEHFOXZ.js');
|
|
250
250
|
const result = await executeWorkflow(this._options, this._steps, input, opts);
|
|
251
251
|
if (opts?.task !== void 0) {
|
|
252
|
-
const { submit: taskSubmit } = await import('./registry-
|
|
252
|
+
const { submit: taskSubmit } = await import('./registry-VFP3WWQP.js');
|
|
253
253
|
const taskOpts = opts.task === true ? {} : opts.task;
|
|
254
254
|
const id = taskOpts.id ?? `wf-${result.id}`;
|
|
255
255
|
await taskSubmit({
|
|
@@ -288,7 +288,7 @@ var Workflow = class {
|
|
|
288
288
|
stream(input, opts) {
|
|
289
289
|
const queue = createEventStream();
|
|
290
290
|
const result = (async () => {
|
|
291
|
-
const { executeWorkflow } = await import('./executor-
|
|
291
|
+
const { executeWorkflow } = await import('./executor-BMEHFOXZ.js');
|
|
292
292
|
try {
|
|
293
293
|
return await executeWorkflow(this._options, this._steps, input, {
|
|
294
294
|
...opts,
|
|
@@ -305,7 +305,7 @@ var Workflow = class {
|
|
|
305
305
|
* `WorkflowSnapshotNotFoundError` if `runId` is unknown.
|
|
306
306
|
*/
|
|
307
307
|
static async resume(opts) {
|
|
308
|
-
const { resumeWorkflow } = await import('./executor-
|
|
308
|
+
const { resumeWorkflow } = await import('./executor-BMEHFOXZ.js');
|
|
309
309
|
return resumeWorkflow(opts);
|
|
310
310
|
}
|
|
311
311
|
};
|
|
@@ -411,5 +411,5 @@ function walkStepsValidating(steps, seen) {
|
|
|
411
411
|
}
|
|
412
412
|
|
|
413
413
|
export { Workflow, WorkflowBuilder, WorkflowToolError, agentStep, cloneWorkflow, fn, workflowAsTool, workflowStep };
|
|
414
|
-
//# sourceMappingURL=chunk-
|
|
415
|
-
//# sourceMappingURL=chunk-
|
|
414
|
+
//# sourceMappingURL=chunk-XV4IZNV4.js.map
|
|
415
|
+
//# sourceMappingURL=chunk-XV4IZNV4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/workflow/event-stream.ts","../src/workflow.ts"],"names":[],"mappings":";;;;;;;AAgBO,SAAS,iBAAA,GAAyC;AACvD,EAAA,MAAM,SAA0B,EAAC;AACjC,EAAA,MAAM,UAA6D,EAAC;AACpE,EAAA,IAAI,KAAA,GAAQ,KAAA;AAEZ,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,KAAK,KAAA,EAA4B;AAC/B,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,MAAM,MAAA,GAAS,QAAQ,KAA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V;AAEA,SAAS,mBAAA,CAAoB,OAA4B,IAAA,EAAyB;AAChF,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,IAAI,IAAA,CAAK,IAAI,CAAA,CAAE,EAAE,GAAG,MAAM,IAAI,4BAAA,CAA6B,CAAA,CAAE,EAAE,CAAA;AAC/D,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,EAAE,CAAA;AACb,IAAA,KAAA,MAAW,MAAA,IAAU,aAAA,CAAc,CAAC,CAAA,EAAG;AACrC,MAAA,mBAAA,CAAoB,QAAQ,IAAI,CAAA;AAAA,IAClC;AAAA,EACF;AACF","file":"chunk-XV4IZNV4.js","sourcesContent":["/**\n * SE28 — a minimal pushable async iterator for `Workflow.stream()`. The executor\n * pushes {@link WorkflowEvent}s as steps run; the consumer drains them via\n * `for await`. Buffers events emitted before the consumer is ready; `end()`\n * closes the iterator so a pending/next `next()` resolves `done: true`.\n *\n * @internal\n */\n\nimport type { WorkflowEvent } from \"../../types/workflow.js\";\n\nexport interface PushableEventStream extends AsyncIterableIterator<WorkflowEvent> {\n push(event: WorkflowEvent): void;\n end(): void;\n}\n\nexport function createEventStream(): PushableEventStream {\n const buffer: WorkflowEvent[] = [];\n const waiters: Array<(r: IteratorResult<WorkflowEvent>) => void> = [];\n let ended = false;\n\n const stream: PushableEventStream = {\n push(event: WorkflowEvent): void {\n if (ended) return;\n const waiter = waiters.shift();\n if (waiter !== undefined) waiter({ value: event, done: false });\n else buffer.push(event);\n },\n end(): void {\n if (ended) return;\n ended = true;\n for (const waiter of waiters.splice(0)) waiter({ value: undefined, done: true });\n },\n next(): Promise<IteratorResult<WorkflowEvent>> {\n const buffered = buffer.shift();\n if (buffered !== undefined) return Promise.resolve({ value: buffered, done: false });\n if (ended) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => waiters.push(resolve));\n },\n // `for await` calls return() on break/throw — close early so events stop\n // buffering in memory for a consumer that stopped iterating.\n return(): Promise<IteratorResult<WorkflowEvent>> {\n stream.end();\n buffer.length = 0;\n return Promise.resolve({ value: undefined, done: true });\n },\n [Symbol.asyncIterator](): PushableEventStream {\n return stream;\n },\n };\n return stream;\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport { createEventStream } from \"./internal/workflow/event-stream.js\";\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport type { CustomTool, SDKAgent } from \"./types/agent.js\";\nimport type { MessageOrigin } from \"./types/run.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowDescription,\n WorkflowEvent,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n WorkflowStepDescription,\n WorkflowStream,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError, WorkflowNestedError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n // SE27 — declared so a future `new WorkflowBuilder(parsed)` refactor cannot\n // silently drop them (create() passes the ORIGINAL options today, but the\n // schema is also the documentation of the shape).\n inputSchema: z.custom<ZodType>().optional(),\n outputSchema: z.custom<ZodType>().optional(),\n});\n\n/* ─── Builder ─── */\n\n/**\n * Fluent step accumulator returned by {@link Workflow.create}. Each method\n * appends a step and returns the SAME builder (mutated in place, never a copy);\n * `.commit()` freezes the list into a {@link Workflow} and mints the id its\n * single-flight lock uses.\n *\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (i: { id: string }) => i))\n * .commit();\n *\n * You never construct one directly — `Workflow.create(options)` validates the\n * options with Zod and hands it back. Import it from `@theokit/sdk/workflow`; the\n * root `@theokit/sdk` barrel does not export it.\n *\n * How it fails:\n * - Every appending method throws a plain `Error` after `.commit()` —\n * \"Workflow already committed; create a fresh Workflow.create(...) call.\" A\n * builder is single-use.\n * - A step id is validated on the spot by `sanitizeIdentifier`\n * (`^[a-z0-9][a-z0-9-_]*$`, max 64 chars). Every rejection — length, a space,\n * `/`, `..`, a leading `-`, a NUL or control char — throws `ConfigurationError`\n * with code `invalid_identifier`, not a plain `Error` (#368 collapsed a second\n * class that the control-char branch used to raise).\n * - `sleep(durationMs)` throws a plain `Error` on a negative or non-finite value.\n * - A duplicate id anywhere in the tree, including inside `parallel`, `branch`,\n * `foreach` and `dowhile`, throws `WorkflowDuplicateStepIdError` at\n * `.commit()` — not at the `.then()` that introduced it.\n *\n * Traps:\n * - `.then(step)` is a STEP APPENDER, not a promise continuation. That makes the\n * builder a JavaScript thenable, so `await Workflow.create({ ... })` — the\n * shape `await Agent.create({ ... })` trains you into — is a mistake:\n * TypeScript rejects it (TS1320) and plain JavaScript throws an unrelated\n * `TypeError: Cannot read properties of undefined (reading 'length')` out of\n * the id validator. `Workflow.create` is synchronous.\n * - `parallel`, `branch`, `foreach`, `dowhile` and `suspend` widen the output\n * type to `unknown` (or `unknown[]`); only `.then<T>()` and `sleep` carry a\n * type through. The generics are a convenience, not a checked pipeline —\n * nothing verifies that one step's output matches the next step's input.\n * - Auto-generated ids are POSITIONAL (`parallel_2`, `foreach_5`), so inserting a\n * step earlier renames the later ones. Pass `opts.id` for any step whose id you\n * rely on in event streams or resume snapshots.\n */\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the a peer framework-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\n/**\n * theokit#161 — project one step to its reflectable shape, recursing into the variants that nest.\n *\n * `parallel` branches are FLATTENED: the grouping is a scheduling detail (which steps may run\n * concurrently), not shape a reader of the workflow needs, and preserving it would put a second,\n * branch-shaped level into a type whose whole purpose is to be renderable.\n */\nfunction describeStep(step: Step): WorkflowStepDescription {\n const base = { id: step.id, kind: step.kind } as const;\n if (step.kind === \"parallel\") {\n return { ...base, steps: step.branches.flat().map(describeStep) };\n }\n if (step.kind === \"branch\") {\n const fromPredicates = step.predicates.flatMap(([, steps]) => steps.map(describeStep));\n const fromFallback = (step.fallback ?? []).map(describeStep);\n return { ...base, steps: [...fromPredicates, ...fromFallback] };\n }\n if (step.kind === \"foreach\" || step.kind === \"dowhile\") {\n return { ...base, steps: [describeStep(step.step)] };\n }\n return base;\n}\n\n/**\n * A committed, immutable workflow: a fixed list of steps you can `run`, `stream`\n * or `resume`. Built with `Workflow.create(options)` plus `.commit()`; the\n * constructor is not part of the published surface.\n *\n * import { Workflow, fn } from \"@theokit/sdk/workflow\";\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (i: { id: string }) => i))\n * .commit();\n * const run = await wf.run({ id: \"x\" }); // run.status, run.output\n *\n * THE IMPORT SPECIFIER MATTERS. `Workflow` is emitted TWICE — once as the\n * `@theokit/sdk/workflow` sub-path entry, and once inside the shared chunk behind\n * the root `@theokit/sdk` barrel. Both declarations carry private fields, so the\n * two are DISTINCT nominal types and TypeScript refuses to pass one where the\n * other is expected:\n *\n * Types have separate declarations of a private property '_options'.\n *\n * Import `Workflow` — and everything that consumes one, such as `workflowStep`\n * and `cloneWorkflow` — from `@theokit/sdk/workflow`, and do not mix the two\n * specifiers in one program. The root barrel re-exports only `Workflow`,\n * `agentStep` and `fn`; the builder, the step helpers, the error classes and every\n * workflow type live on the sub-path. (`workflowAsTool` is exempt: it accepts any\n * `{ run }`-shaped value structurally, so either `Workflow` satisfies it.)\n *\n * How it fails: a step that throws does NOT reject `run()`. The promise resolves\n * with `status: \"failed\"` and the cause on `run.error`; `\"suspended\"` and\n * `\"cancelled\"` are the other non-`\"completed\"` terminals, and an `outputSchema`\n * mismatch also lands as `\"failed\"` (`WorkflowOutputError`) rather than a throw.\n * What DOES throw out of `run()` is pre-flight: `WorkflowAlreadyRunningError` when\n * you pin `WorkflowRunOptions.runId` to one still in flight. `Workflow.resume`\n * throws `WorkflowSnapshotNotFoundError` for an unknown `runId`.\n *\n * Traps:\n * - Without an explicit `runId` each call mints its own, so concurrent runs of\n * the same committed workflow do NOT collide — the single-flight lock only\n * bites when you pin the id yourself.\n * - `stream()` reports progress; its `result` promise is the AUTHORITATIVE\n * outcome. Not every terminal emits a closing event, so a consumer that only\n * drains events can miss a failure. Always `await result`.\n * - `run()` and `stream()` load the executor by dynamic `import()`, so the first\n * call pays a module load and cannot be made synchronous.\n *\n * @public\n */\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * theokit#161 — describe this workflow's shape, for a reflection surface.\n *\n * Returns `{ name, steps }`, each step carrying its `id` and `kind`, recursing into `parallel`,\n * `branch`, `foreach` and `dowhile`. Every executable a step holds — predicates, conditions,\n * agents, prompt templates — is omitted: it cannot cross a process boundary and says nothing about\n * shape.\n *\n * There is deliberately no `Workflow.list()`. A workflow is a value the caller constructs and\n * holds, so the caller already knows which ones exist; a registry would add process-global state\n * nothing releases in order to re-answer a question the host can answer itself. A reflection\n * endpoint maps over its own workflows and calls this.\n *\n * @public\n */\n describe(): WorkflowDescription {\n return {\n name: this._options.name,\n steps: this._steps.map(describeStep),\n };\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * SE28 — run the workflow and STREAM step-level events as they happen. Returns\n * an async iterator of {@link WorkflowEvent}s (`step_started` / `step_completed`\n * / `step_failed` / `workflow_suspended` / `workflow_completed`, top-level\n * steps) plus a `result` promise resolving to the same terminal\n * {@link WorkflowRun} `run()` returns. Iterate for progress; await `result` for\n * the outcome. The stream ends when the run terminates.\n *\n * `result` is the AUTHORITATIVE terminal status. Not every terminal state has a\n * closing event: a step failure emits `step_failed`, but an `outputSchema`\n * rejection (SE27) or an abort ends the stream WITHOUT `workflow_completed` —\n * always `await result` to read the final `status`. Consuming order is free:\n * awaiting `result` without draining, or draining without awaiting `result`,\n * both work (breaking out of `for await` stops the buffering early).\n */\n stream(input: TInput, opts?: WorkflowRunOptions): WorkflowStream<TOutput> {\n const queue = createEventStream();\n const result = (async (): Promise<WorkflowRun<TOutput>> => {\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n try {\n return await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, {\n ...opts,\n onStepEvent: (event: WorkflowEvent) => queue.push(event),\n } as WorkflowRunOptions);\n } finally {\n queue.end(); // authoritative terminal is `result`; close the stream\n }\n })();\n return Object.assign(queue, { result });\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy; origin?: MessageOrigin },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n // SE3 — carry the turn's provenance down to `agent.send()` (metadata-only).\n ...(opts?.origin !== undefined ? { origin: opts.origin } : {}),\n };\n}\n\n/**\n * SE30 — use a committed {@link Workflow} as a step inside another workflow.\n * Wraps the child as an `FnStep` (opaque — the child runs in its OWN executor\n * with its own id-space, so nested step-ids never collide with the parent's).\n * The child's output becomes the step output. A non-`completed` child fails the\n * parent step with a typed {@link WorkflowNestedError}: nested `suspended` is NOT\n * resumable in v1 (resume continues AFTER the step — the child would be skipped;\n * use a top-level suspend). See ADR 0010.\n *\n * @public\n */\nexport function workflowStep<TI = unknown, TO = unknown>(\n child: Workflow<TI, TO>,\n opts?: { id?: string },\n): FnStep {\n const id = opts?.id ?? `workflow_${child.__options.name}`;\n validateStepId(id);\n return {\n kind: \"fn\",\n id,\n fn: async (input: unknown, ctx: StepContext): Promise<unknown> => {\n const run = await child.run(input as TI, { signal: ctx.signal });\n if (run.status === \"completed\") return run.output;\n throw new WorkflowNestedError(id, child.__options.name, run.status, run.error);\n },\n };\n}\n\n/**\n * SE30 — clone a committed workflow under a new id/name. The clone runs\n * independently (its own single-flight lock + observability identity) with the\n * same committed steps. Mirrors a peer framework's `cloneWorkflow`.\n *\n * @public\n */\nexport function cloneWorkflow<TI = unknown, TO = unknown>(\n wf: Workflow<TI, TO>,\n opts: { id: string },\n): Workflow<TI, TO> {\n return new Workflow<TI, TO>(\n { ...wf.__options, name: opts.id, workflowId: `wf-${mintShortId()}` },\n [...wf.__steps],\n );\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowInputError,\n WorkflowMaxIterationsExceededError,\n WorkflowNestedError,\n WorkflowNotSerializableError,\n WorkflowOutputError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n WorkflowStateError,\n} from \"./types/workflow.js\";\n\n/* ─── SE19 — workflowAsTool (expose a Workflow as an agent tool) ─── */\n\n/**\n * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not\n * reach `status: \"completed\"` (a step failed, the run was cancelled/suspended).\n * The dispatch converts it to a `tool_result(isError)`.\n *\n * @public\n */\nexport class WorkflowToolError extends Error {\n readonly code = \"workflow_tool_failed\" as const;\n constructor(\n readonly toolName: string,\n readonly workflowStatus: string,\n readonly workflowError?: { name: string; message: string },\n ) {\n super(\n `workflowAsTool(\"${toolName}\"): workflow ${workflowStatus}${\n workflowError ? `: ${workflowError.message}` : \"\"\n }`,\n );\n this.name = \"WorkflowToolError\";\n }\n}\n\n/** Spec for {@link workflowAsTool}. `inputSchema` is the workflow's input shape (Zod). */\nexport interface WorkflowAsToolSpec<T extends ZodType> {\n /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */\n name: string;\n /** Description surfaced to the LLM — when the agent should trigger the workflow. */\n description: string;\n /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */\n inputSchema: T;\n}\n\n/**\n * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the\n * \"X as tools\" trio (tools; agents-as-tools via `defineSubAgent`; workflows-as-tools).\n * The handler validates the model's args against `spec.inputSchema`, runs the\n * workflow, and returns its output (a string as-is, else JSON). A run that does not\n * reach `status: \"completed\"` raises a typed {@link WorkflowToolError} (workflow\n * step errors do NOT throw — they surface via `run.status === \"failed\"`).\n *\n * Accepts any `{ run }`-shaped workflow (structural), so it never imports the\n * `Workflow` class directly.\n *\n * @public\n */\nexport function workflowAsTool<T extends ZodType, TOutput = unknown>(\n workflow: { run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>> },\n spec: WorkflowAsToolSpec<T>,\n): CustomTool {\n const inputSchema = toJsonSchema(spec.inputSchema, { unrepresentable: \"any\" });\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (rawInput: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(rawInput) as z.infer<T>;\n const run = await workflow.run(parsed);\n if (run.status !== \"completed\") {\n throw new WorkflowToolError(spec.name, run.status, run.error);\n }\n const output = run.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n },\n };\n}\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkI6TGFUCO_cjs = require('./chunk-I6TGFUCO.cjs');
|
|
4
4
|
var promises = require('fs/promises');
|
|
5
5
|
var path = require('path');
|
|
6
6
|
|
|
@@ -180,7 +180,7 @@ var JsonFileWorkflowSnapshotStore = class {
|
|
|
180
180
|
);
|
|
181
181
|
}
|
|
182
182
|
await promises.mkdir(this.dir, { recursive: true });
|
|
183
|
-
await
|
|
183
|
+
await chunkI6TGFUCO_cjs.atomicWriteText(this.filePath(snapshot.runId), serialized);
|
|
184
184
|
}
|
|
185
185
|
async load(runId) {
|
|
186
186
|
try {
|
|
@@ -264,5 +264,5 @@ exports.WorkflowSnapshotNotFoundError = WorkflowSnapshotNotFoundError;
|
|
|
264
264
|
exports.WorkflowStateError = WorkflowStateError;
|
|
265
265
|
exports.__resetSnapshotStoresForTests = __resetSnapshotStoresForTests;
|
|
266
266
|
exports.getSnapshotStoreFor = getSnapshotStoreFor;
|
|
267
|
-
//# sourceMappingURL=chunk-
|
|
268
|
-
//# sourceMappingURL=chunk-
|
|
267
|
+
//# sourceMappingURL=chunk-XWL6O3SW.cjs.map
|
|
268
|
+
//# sourceMappingURL=chunk-XWL6O3SW.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types/workflow.ts","../src/internal/workflow/snapsh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AAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,WAAA;AACT;AAGO,SAAS,6BAAA,GAAsC;AACpD,EAAA,UAAA,CAAW,KAAA,EAAM;AAGjB,EAAC,WAAA,CAAoB,IAAI,KAAA,EAAM;AACjC","file":"chunk-XWL6O3SW.cjs","sourcesContent":["/**\n * Public type contract for `Workflow.create / .run / .resume` (Adoption\n * Roadmap #5; ADRs D230-D248).\n *\n * Step types form a discriminated union by `kind`. Helper factory functions\n * (`fn()`, `agentStep()`) live in `workflow.ts` and hide the discriminator\n * from end users.\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\n\nimport type { SDKAgent } from \"./agent.js\";\nimport type { MessageOrigin } from \"./run.js\";\n\n/* ─── Step discriminated union (D232) ─── */\n\n/**\n * Any node of a committed workflow, discriminated by `kind`.\n *\n * Build these with the helpers rather than by hand: `fn()` and `agentStep()` set the discriminator,\n * validate the id, and parse the retry policy at construction — where a mistake is cheap — while the\n * builder methods `.parallel()`, `.branch()`, `.foreach()`, `.dowhile()`, `.sleep()` and `.suspend()`\n * cover the remaining variants and mint a positional default id (`parallel_0`, `branch_1`, ...) when\n * you do not pass one.\n *\n * Every id, nested ones included, must match `^[a-z0-9][a-z0-9_-]*$` case-insensitively and be at\n * most 64 characters, and must be unique across the whole workflow. `.commit()` walks the tree —\n * parallel branches, branch predicates, the fallback, and the inner step of a `foreach`/`dowhile` —\n * and throws {@link WorkflowDuplicateStepIdError} on the second occurrence.\n */\nexport type Step =\n | FnStep\n | AgentStep\n | ParallelStep\n | BranchStep\n | ForeachStep\n | DowhileStep\n | SleepStep\n | SuspendStep;\n\n/** A pure function step. */\nexport interface FnStep {\n readonly kind: \"fn\";\n readonly id: string;\n readonly fn: (input: unknown, ctx: StepContext) => Promise<unknown> | unknown;\n readonly inputSchema?: ZodType;\n readonly outputSchema?: ZodType;\n readonly retry?: RetryPolicy;\n /** D238 — slot reserved; runtime throws if engine not yet implemented. */\n readonly compensate?: (input: unknown, output: unknown, error: Error) => Promise<void> | void;\n}\n\n/** An agent.send-driven step. */\nexport interface AgentStep {\n readonly kind: \"agent\";\n readonly id: string;\n readonly agent: SDKAgent;\n readonly promptTemplate: string | ((input: unknown) => string);\n readonly retry?: RetryPolicy;\n /**\n * SE3 — provenance stamped onto this step's `agent.send()` (forwarded to\n * `RunResult.origin`). Squad sets `{ kind: \"peer\", from: \"agent-<i-1>\" }` on\n * every step after the first so a peer-driven turn is attributable.\n */\n readonly origin?: MessageOrigin;\n}\n\n/** N concurrent branches, each its own mini-step-list. */\nexport interface ParallelStep {\n readonly kind: \"parallel\";\n readonly id: string;\n readonly branches: ReadonlyArray<ReadonlyArray<Step>>;\n readonly concurrency?: number;\n readonly errorPolicy?: \"fail-fast\" | \"collect\";\n}\n\n/** First-match-wins predicates + optional fallback. */\nexport interface BranchStep {\n readonly kind: \"branch\";\n readonly id: string;\n readonly predicates: ReadonlyArray<\n readonly [(input: unknown) => boolean | Promise<boolean>, ReadonlyArray<Step>]\n >;\n readonly fallback?: ReadonlyArray<Step>;\n}\n\n/** Map a step over an upstream array output. */\nexport interface ForeachStep {\n readonly kind: \"foreach\";\n readonly id: string;\n /** ID of an upstream top-level step whose output is iterable. */\n readonly iterableFrom: string;\n readonly step: Step;\n readonly concurrency?: number;\n}\n\n/** Loop a step until condFn returns false. */\nexport interface DowhileStep {\n readonly kind: \"dowhile\";\n readonly id: string;\n readonly step: Step;\n readonly condFn: (output: unknown, iteration: number) => boolean | Promise<boolean>;\n readonly maxIterations?: number;\n}\n\n/** Pause for a fixed duration. */\nexport interface SleepStep {\n readonly kind: \"sleep\";\n readonly id: string;\n readonly durationMs: number;\n}\n\n/** Standalone explicit suspend point. */\nexport interface SuspendStep {\n readonly kind: \"suspend\";\n readonly id: string;\n readonly payloadSchema?: ZodType;\n}\n\n/* ─── Reflection (theokit#161) ─── */\n\n/**\n * theokit#161 — one step of a workflow, as a reflection surface sees it.\n *\n * `id` and `kind` are the only fields every step variant shares, and they are what a reflection\n * endpoint renders. Everything else a step carries is an executable — a predicate, a condition, an\n * agent, a prompt template — which cannot cross a process boundary and means nothing to a caller\n * enumerating shape.\n *\n * @public\n */\nexport interface WorkflowStepDescription {\n readonly id: string;\n readonly kind: Step[\"kind\"];\n /**\n * Nested steps, for the variants that contain them: `parallel` (all branches, flattened — the\n * branch grouping is a scheduling detail, not shape a reader needs), `branch` (each predicate's\n * steps plus the fallback), `foreach` and `dowhile` (their single inner step).\n *\n * Absent for leaf steps. A flat list would misreport a parallel or branching workflow as linear.\n */\n readonly steps?: readonly WorkflowStepDescription[];\n}\n\n/**\n * theokit#161 — the read-only shape of a committed workflow.\n *\n * Returned by `Workflow.describe()`. There is deliberately NO workflow registry to enumerate: a\n * `Workflow` is a value the caller constructs and holds, so the caller already knows which ones\n * exist. What it lacked was a way to DESCRIBE one. A registry would have added process-global state\n * that nothing ever releases, to re-answer a question the host can answer itself.\n *\n * @public\n */\nexport interface WorkflowDescription {\n readonly name: string;\n readonly steps: readonly WorkflowStepDescription[];\n}\n\n/* ─── Supporting types ─── */\n\n/** D237 — retry policy applied per fn/agent step. */\nexport interface RetryPolicy {\n /** Total attempts (MIN 1, MAX 20). `1` = no retry. */\n readonly maxAttempts: number;\n readonly initialBackoffMs?: number;\n readonly backoffCoefficient?: number;\n readonly maximumBackoffMs?: number;\n readonly nonRetryableErrors?: ReadonlyArray<string>;\n}\n\n/** D247 — context handed to every step.fn. */\nexport interface StepContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly log: {\n debug: (msg: string, attrs?: Record<string, unknown>) => void;\n info: (msg: string, attrs?: Record<string, unknown>) => void;\n warn: (msg: string, attrs?: Record<string, unknown>) => void;\n };\n /** Pause the workflow; resume via `Workflow.resume({...})`. */\n readonly suspend: (payload?: unknown) => Promise<never>;\n /**\n * SE29 — the workflow's shared state (from `WorkflowOptions.initialState`,\n * mutated by {@link setState}), visible to every subsequent step in the run.\n * `undefined` when no `initialState`/`setState` has run. Persisted across\n * suspend/resume.\n */\n readonly state: unknown;\n /**\n * SE29 — update the shared state for subsequent steps. Validated against\n * `WorkflowOptions.stateSchema` when set (a mismatch throws\n * {@link WorkflowStateError}, which fails the step/run — Rule 8).\n */\n readonly setState: (next: unknown) => void;\n}\n\n/* ─── Result types ─── */\n\n/**\n * The outcome of one step, appended to `WorkflowRun.stepResults` in execution order.\n *\n * A failing step does not throw out of `run()`. It lands here with `status: \"failed\"` and its error\n * flattened to `{ name, message }` — the thrown instance is gone by the time a caller sees it, so\n * match on `error.name` and never on `instanceof`.\n *\n * `\"skipped\"` occurs only for a `branch` step whose predicates all returned false and which declared\n * no fallback; its `output` is the step input, passed through unchanged. `\"suspended\"` marks the step\n * that called `StepContext.suspend()`, is always the last entry of the run, and carries no output.\n *\n * `attempts` means different things per kind. For `fn` and `agent` it counts execution attempts: 1\n * without a `retry` policy, and 0 when the step failed before its body ran — an `inputSchema`\n * rejection, a prompt template that threw, a `compensate` v1 refuses, or a cloud agent. For `dowhile`\n * it counts loop iterations instead.\n */\nexport interface StepResult {\n readonly stepId: string;\n readonly kind: Step[\"kind\"];\n readonly status: \"completed\" | \"failed\" | \"skipped\" | \"suspended\";\n readonly attempts: number;\n readonly durationMs: number;\n readonly output?: unknown;\n readonly error?: { name: string; message: string };\n}\n\n/**\n * The terminal record of one run — what `Workflow.run()` resolves to, what `Workflow.resume()`\n * returns, and what the `result` promise of `Workflow.stream()` settles with.\n *\n * Read `status`; do not rely on `catch`. A step that throws does not reject the promise, it ends the\n * run with `status: \"failed\"` and the error in `error`. Only `completed` populates `output`; `failed`\n * and `cancelled` (an aborted `signal`) populate `error`; `suspended` populates neither and means a\n * snapshot exists under `id` for `Workflow.resume()`. `running` is part of the union for the benefit\n * of a host tracking a run in flight — the executor only ever assembles a terminal one.\n *\n * `stepResults` is cumulative across a resume: the executor seeds it with the snapshot's prior\n * results, so the record of a resumed run covers the steps that ran before the suspend as well.\n */\nexport interface WorkflowRun<TOutput = unknown> {\n readonly id: string;\n readonly name: string;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly output?: TOutput;\n readonly error?: { name: string; message: string };\n readonly startedAt: number;\n readonly endedAt?: number;\n readonly stepResults: ReadonlyArray<StepResult>;\n}\n\n/**\n * The persisted state of a suspended run: written when a step calls `StepContext.suspend()`, read\n * back by `Workflow.resume()`. Callers never construct one — the type is exported so a host can\n * inspect what the persistence backend wrote.\n *\n * Snapshots are single-shot. `resume()` deletes the snapshot before re-entering the executor, so the\n * same one cannot be resumed twice; a second attempt raises\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * Everything reachable from here must survive `JSON.stringify` — the store serializes on save even\n * for the memory backend, and raises `WorkflowNotSerializableError` rather than letting a `TypeError`\n * escape. That rules out BigInt, circular references and class instances in step outputs, in\n * `accumulatedInput` and in `state`.\n *\n * `currentStepId` is the suspending step, and resume continues from the step AFTER it. A workflow\n * definition edited between suspend and resume therefore either fails with\n * `WorkflowResumeStepNotFoundError` (the id is gone) or resumes at a position the author did not\n * intend (the id moved).\n */\nexport interface WorkflowSnapshot {\n /** v1 = pre-SE29 (no `state`); v2 = SE29 (carries `state`). Resume reads both. */\n readonly _schemaVersion: 1 | 2;\n readonly runId: string;\n readonly workflowName: string;\n readonly currentStepId: string;\n readonly suspendedPayload?: unknown;\n readonly stepResults: ReadonlyArray<StepResult>;\n readonly accumulatedInput: unknown;\n /** SE29 — shared state captured at suspend (v2). Absent on a v1 snapshot. */\n readonly state?: unknown;\n readonly suspendedAt: number;\n}\n\n/* ─── SE28 — streaming ─── */\n\n/**\n * SE28 — a step-level workflow event emitted by `Workflow.stream()` as top-level\n * steps run. Coarse-grained (one event per top-level step; nested\n * parallel/branch/foreach emit as their single wrapping step), distinct from the\n * token-delta agent stream. Discriminate on `type`.\n *\n * @public\n */\nexport type WorkflowEvent =\n | { readonly type: \"step_started\"; readonly stepId: string }\n | { readonly type: \"step_completed\"; readonly stepId: string; readonly output: unknown }\n | {\n readonly type: \"step_failed\";\n readonly stepId: string;\n readonly error: { readonly name: string; readonly message: string };\n }\n | { readonly type: \"workflow_suspended\"; readonly stepId: string }\n | { readonly type: \"workflow_completed\" };\n\n/**\n * SE28 — the async iterator returned by `Workflow.stream()`. Yields\n * {@link WorkflowEvent}s in execution order; `result` resolves to the same\n * terminal {@link WorkflowRun} the `run()` path returns (the authoritative\n * outcome — the stream ends when the run terminates).\n *\n * @public\n */\nexport type WorkflowStream<TOutput = unknown> = AsyncIterableIterator<WorkflowEvent> & {\n readonly result: Promise<WorkflowRun<TOutput>>;\n};\n\n/* ─── Options ─── */\n\n/**\n * Where suspend snapshots are kept. Omitting `WorkflowOptions.persistence` selects the same store\n * `backend: \"memory\"` selects explicitly.\n *\n * `\"memory\"` is one process-wide map shared by every workflow, so a run suspended under it can only\n * be resumed by the process that suspended it, and only until it exits. `\"json\"` writes one\n * `{runId}.json` per snapshot into `dir` through an atomic write and survives a restart. Any suspend\n * point that waits on a human or an external system needs `\"json\"`; `\"memory\"` is for tests and for\n * suspends resolved within the same process.\n *\n * `dir` is required when `backend` is `\"json\"` and ignored otherwise — `Workflow.create()` rejects\n * the options up front when it is missing or empty, rather than failing at the first suspend.\n */\nexport interface WorkflowPersistenceOptions {\n readonly backend: \"memory\" | \"json\";\n /** Required for `backend: \"json\"`. */\n readonly dir?: string;\n}\n\n/**\n * Configuration for `Workflow.create()`, validated by Zod before the builder is handed back: a `name`\n * outside 1..128 characters, or `persistence.backend: \"json\"` without a `dir`, throws there rather\n * than at run time.\n *\n * `name` is an observability and error-message label, not an identity. Two workflows may share one;\n * the identity behind the single-flight lock is minted per `.commit()` call, so two separately\n * committed workflows never block each other however they are named.\n *\n * The three schemas are independent and each optional: `inputSchema` guards `run(input)` before step\n * 1, `outputSchema` guards the final value on the completed path only (a suspended or failed run\n * skips it), and `stateSchema` guards `initialState` plus every `StepContext.setState()` call. All\n * three must be synchronous — a schema carrying an async refinement is reported as a validation\n * failure with that explanation, never awaited.\n */\nexport interface WorkflowOptions {\n readonly name: string;\n readonly persistence?: WorkflowPersistenceOptions;\n /**\n * SE27 — Zod schema for the WHOLE workflow's input. When set, `run(input)`\n * validates `input` BEFORE step 1; a mismatch yields `status: \"failed\"` with a\n * typed {@link WorkflowInputError} in `error` (fail-fast, no step runs, no\n * silent coerce). Absent ⇒ no whole-workflow input validation (unchanged).\n */\n readonly inputSchema?: ZodType;\n /**\n * SE27 — Zod schema for the workflow's final output. When set, the terminal\n * `completed` output is validated before `WorkflowRun.output` is populated; a\n * mismatch yields `status: \"failed\"` with a typed {@link WorkflowOutputError}.\n * Only validated on the `completed` path (suspended/failed runs skip it).\n */\n readonly outputSchema?: ZodType;\n /**\n * SE29 — Zod schema for the workflow's shared state (see `StepContext.state` /\n * `setState`). When set, `initialState` and every `setState(next)` are\n * validated against it (a mismatch throws {@link WorkflowStateError}). When\n * `initialState` is absent, `state` starts as `undefined` and validation fires\n * on the first `setState` call.\n */\n readonly stateSchema?: ZodType;\n /**\n * SE29 — the initial shared state, seeded onto `StepContext.state` before\n * step 1. Validated against `stateSchema` when both are set. Persisted across\n * suspend/resume.\n */\n readonly initialState?: unknown;\n /** Internal — minted at `.commit()`. Not user-facing. */\n readonly workflowId?: string;\n}\n\n/**\n * Per-run options for `Workflow.run()` and `Workflow.stream()`.\n *\n * `signal` is combined with the run's internal single-flight signal and reaches every step through\n * `StepContext.signal`. The executor itself checks it at step boundaries, so a step that ignores the\n * signal runs to completion before the run reports `status: \"cancelled\"` — a step doing long I/O\n * should pass `ctx.signal` down to make abort prompt.\n *\n * `runId` is minted per call (`wfr-` plus 8 hex) unless you pass it, which is why concurrent runs of\n * one workflow do not interfere. Pinning it buys a deterministic id for resume, and buys the\n * single-flight lock with it: starting a second run of the same committed workflow under a `runId`\n * that is still in flight throws {@link WorkflowAlreadyRunningError}.\n */\nexport interface WorkflowRunOptions {\n readonly signal?: AbortSignal;\n /** Override run ID for deterministic resume (advanced; default = mintRunId). */\n readonly runId?: string;\n /**\n * Opt-in Task wrapping (ADRs D363, D374). Registers the workflow run\n * as a `Task` (kind=\"workflow\") with a `wf-` namespaced id (D368,\n * EC-5). The task transitions terminal when `Workflow.run` resolves.\n *\n * Auto-id: `wf-{runId}`.\n *\n * @public\n */\n readonly task?: true | { id?: string; meta?: Record<string, unknown> };\n}\n\n/**\n * Arguments for `Workflow.resume()`.\n *\n * `workflow` is typed structurally as `{ run }`, but resume needs more than `run`: it reads the\n * committed steps and options off the instance and throws a plain `Error` — \"Workflow.resume requires\n * an instance from Workflow.create().commit()\" — for anything else. Pass the same committed\n * `Workflow` the suspended run came from, not a stand-in.\n *\n * `runId` selects the snapshot. An id with no snapshot throws\n * {@link WorkflowSnapshotNotFoundError}.\n *\n * `payload` becomes the input of the step after the suspend point, and is parsed against the\n * suspending step's `payloadSchema` first when it declared one (a mismatch throws out of `resume`).\n * Omit it to resume from the accumulated input captured in the snapshot instead — the two are\n * alternatives, not a merge.\n */\nexport interface WorkflowResumeOptions<TI = unknown> {\n readonly runId: string;\n readonly workflow: { run: (input: TI, opts?: WorkflowRunOptions) => Promise<WorkflowRun> };\n readonly payload?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/* ─── Error classes ─── */\n\n/**\n * Thrown by `.commit()` when one step id appears twice anywhere in the workflow — including inside a\n * parallel branch, a branch predicate, the fallback, and the inner step of a `foreach` or `dowhile`.\n *\n * Ids address steps in snapshots and on resume, so this is refused at build time rather than\n * discovered mid-run. Workflows nested with `workflowStep()` are exempt: the child runs in its own\n * executor with its own id-space, so its ids cannot collide with the parent's.\n */\nexport class WorkflowDuplicateStepIdError extends Error {\n override readonly name = \"WorkflowDuplicateStepIdError\";\n constructor(public readonly stepId: string) {\n super(`Duplicate step id \"${stepId}\" in workflow.`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `inputSchema` rejected `run(input)` (before step 1).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowInputError extends Error {\n override readonly name = \"WorkflowInputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" input failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE27 — the whole-workflow `outputSchema` rejected the final output (on `completed`).\n * `detail` is a pre-formatted issues summary (a string, NOT Zod's `ZodIssue[]`).\n */\nexport class WorkflowOutputError extends Error {\n override readonly name = \"WorkflowOutputError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" output failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE29 — `WorkflowOptions.stateSchema` rejected an `initialState` or a\n * `setState(next)` call. `detail` is a pre-formatted issues summary.\n */\nexport class WorkflowStateError extends Error {\n override readonly name = \"WorkflowStateError\";\n constructor(\n public readonly workflowName: string,\n public readonly detail: string,\n ) {\n super(`Workflow \"${workflowName}\" state failed schema validation: ${detail}`);\n }\n}\n\n/**\n * SE30 — a nested workflow (via `workflowStep`) did not `complete`. A nested\n * `suspended` is NOT resumable in v1 (resume continues AFTER the step, so the\n * child would be skipped) — restructure with a top-level suspend. A nested\n * `failed`/`cancelled` fails the parent step with the child's error attached.\n */\nexport class WorkflowNestedError extends Error {\n override readonly name = \"WorkflowNestedError\";\n constructor(\n public readonly stepId: string,\n public readonly childName: string,\n public readonly childStatus: Exclude<WorkflowRun[\"status\"], \"completed\">,\n public readonly childError?: { name: string; message: string },\n ) {\n super(\n `Nested workflow \"${childName}\" (step \"${stepId}\") ended with status \"${childStatus}\"${\n childStatus === \"suspended\"\n ? \" — nested suspend/resume is not supported in v1 (use a top-level suspend)\"\n : \"\"\n }${childError ? `: ${childError.name}: ${childError.message}` : \"\"}`,\n // Reconstruct a synthetic Error from the serialized child-error shape so\n // debuggers surface the nested cause chain — the original Error instance is\n // lost at the WorkflowRun serialization boundary, so this is the best\n // achievable without changing the run protocol.\n childError\n ? { cause: Object.assign(new Error(childError.message), { name: childError.name }) }\n : undefined,\n );\n }\n}\n\n/**\n * Thrown out of `Workflow.run()` — one of the few workflow failures that rejects instead of arriving\n * as `run.status === \"failed\"` — when the committed workflow already has a run in flight under the\n * same run id.\n *\n * The lock key pairs the id minted at `.commit()` with the run id, not `WorkflowOptions.name`, so\n * two workflows sharing a name are independent and concurrent runs with distinct minted ids never\n * collide. In practice this only fires when a caller pins `WorkflowRunOptions.runId`, or resumes a\n * run id that is still executing. The registry is an in-process map: a crash releases every lock, and\n * it says nothing about runs in other processes.\n */\nexport class WorkflowAlreadyRunningError extends Error {\n override readonly name = \"WorkflowAlreadyRunningError\";\n constructor(\n public readonly workflowName: string,\n public readonly runId: string,\n ) {\n super(`Workflow \"${workflowName}\" run \"${runId}\" already in-flight.`);\n }\n}\n\n/**\n * Thrown by `Workflow.resume()` when no snapshot exists for the given run id.\n *\n * The message suggests configuring persistence, which is the common cause but not the only one. The\n * run may never have suspended; it may have suspended under the default memory backend in a process\n * that has since exited; or the snapshot may already have been consumed, since resume deletes it\n * before re-entering the executor and a second resume of the same run id lands here.\n */\nexport class WorkflowSnapshotNotFoundError extends Error {\n override readonly name = \"WorkflowSnapshotNotFoundError\";\n constructor(public readonly runId: string) {\n super(`No snapshot found for runId \"${runId}\". Configure persistence to enable resume.`);\n }\n}\n\n/**\n * Raised when a `dowhile` step's condition kept returning true past `maxIterations` (default 100).\n *\n * It does not escape `run()`: the step fails, the run ends `status: \"failed\"`, and the error reaches\n * the caller flattened as `run.error` with `name: \"WorkflowMaxIterationsExceededError\"` — match on\n * the name, the instance does not survive. The guard is evaluated before each iteration, so the inner\n * step runs at most `maxIterations` times; raising the ceiling is a `maxIterations` on the step, and\n * there is no global default to change.\n */\nexport class WorkflowMaxIterationsExceededError extends Error {\n override readonly name = \"WorkflowMaxIterationsExceededError\";\n constructor(\n public readonly stepId: string,\n public readonly maxIterations: number,\n ) {\n super(`Step \"${stepId}\" exceeded max iterations (${maxIterations}).`);\n }\n}\n\n/** EC-4 absorbed — JSON.stringify failed on snapshot payload. */\nexport class WorkflowNotSerializableError extends Error {\n override readonly name = \"WorkflowNotSerializableError\";\n constructor(\n public readonly stepId: string,\n public readonly underlying: Error,\n ) {\n super(\n `Workflow snapshot at step \"${stepId}\" failed to serialize as JSON: ${underlying.message}. ` +\n `Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`,\n );\n }\n}\n\n/** EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. */\nexport class WorkflowResumeStepNotFoundError extends Error {\n override readonly name = \"WorkflowResumeStepNotFoundError\";\n constructor(\n public readonly stepId: string,\n public readonly workflowName: string,\n ) {\n super(\n `Cannot resume: step \"${stepId}\" not found in workflow \"${workflowName}\". ` +\n `The Workflow definition diverged from the snapshot.`,\n );\n }\n}\n\n/** Aggregate failure from parallel branches. */\nexport class WorkflowParallelError extends AggregateError {\n override readonly name = \"WorkflowParallelError\";\n constructor(\n errors: ReadonlyArray<Error>,\n public readonly stepId: string,\n ) {\n super(errors, `${errors.length} branch(es) failed in parallel step \"${stepId}\".`);\n }\n}\n\n/** D238 — saga engine not yet implemented. */\nexport class WorkflowCompensateNotImplementedError extends Error {\n override readonly name = \"WorkflowCompensateNotImplementedError\";\n constructor(public readonly stepId: string) {\n super(\n `Step \"${stepId}\" defines compensate, but saga engine is deferred to v1.2. ` +\n `Remove compensate or implement rollback manually.`,\n );\n }\n}\n","/**\n * Snapshot store interface + InMemory and JsonFile backends (ADR D235).\n *\n * EC-4 absorbed: serialization happens here. `JSON.stringify` failure raises\n * `WorkflowNotSerializableError` instead of letting the underlying `TypeError`\n * leak.\n *\n * @internal\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n WorkflowNotSerializableError,\n type WorkflowOptions,\n type WorkflowSnapshot,\n} from \"../../types/workflow.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nexport interface WorkflowSnapshotStore {\n save(snapshot: WorkflowSnapshot): Promise<void>;\n load(runId: string): Promise<WorkflowSnapshot | undefined>;\n delete(runId: string): Promise<void>;\n list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>>;\n}\n\n/* ─── InMemory backend (default) ─── */\n\nclass InMemoryWorkflowSnapshotStore implements WorkflowSnapshotStore {\n private readonly map = new Map<string, WorkflowSnapshot>();\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n // Verify serializability even in-memory so behavior is consistent with json backend.\n try {\n JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n this.map.set(snapshot.runId, snapshot);\n }\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n return this.map.get(runId);\n }\n async delete(runId: string): Promise<void> {\n this.map.delete(runId);\n }\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n return [...this.map.values()]\n .filter((s) => workflowName === undefined || s.workflowName === workflowName)\n .map((s) => ({\n runId: s.runId,\n workflowName: s.workflowName,\n suspendedAt: s.suspendedAt,\n }));\n }\n}\n\n/* ─── Json file backend (opt-in) ─── */\n\nclass JsonFileWorkflowSnapshotStore implements WorkflowSnapshotStore {\n constructor(private readonly dir: string) {}\n\n private filePath(runId: string): string {\n return join(this.dir, `${runId}.json`);\n }\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n let serialized: string;\n try {\n serialized = JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n await mkdir(this.dir, { recursive: true });\n await atomicWriteText(this.filePath(snapshot.runId), serialized);\n }\n\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(this.filePath(runId), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n }\n\n async delete(runId: string): Promise<void> {\n try {\n await (await import(\"node:fs/promises\")).unlink(this.filePath(runId));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n private async readEntriesOrEmpty(): Promise<string[]> {\n try {\n return await readdir(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n }\n\n private async readSnapshotSafe(file: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(join(this.dir, file), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch {\n return undefined;\n }\n }\n\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n const entries = await this.readEntriesOrEmpty();\n const results: Array<{ runId: string; workflowName: string; suspendedAt: number }> = [];\n for (const file of entries) {\n if (!file.endsWith(\".json\")) continue;\n const snap = await this.readSnapshotSafe(file);\n if (snap === undefined) continue;\n if (workflowName !== undefined && snap.workflowName !== workflowName) continue;\n results.push({\n runId: snap.runId,\n workflowName: snap.workflowName,\n suspendedAt: snap.suspendedAt,\n });\n }\n return results;\n }\n}\n\n/* ─── Resolver: per-Workflow store cache ─── */\n\nconst memoryStore = new InMemoryWorkflowSnapshotStore();\nconst jsonStores = new Map<string, JsonFileWorkflowSnapshotStore>();\n\nexport function getSnapshotStoreFor(options: WorkflowOptions): WorkflowSnapshotStore {\n if (options.persistence?.backend === \"json\") {\n const dir = options.persistence.dir as string; // schema enforces dir is set\n let store = jsonStores.get(dir);\n if (store === undefined) {\n store = new JsonFileWorkflowSnapshotStore(dir);\n jsonStores.set(dir, store);\n }\n return store;\n }\n return memoryStore;\n}\n\n/** Test seam — clear in-memory store between tests. */\nexport function __resetSnapshotStoresForTests(): void {\n jsonStores.clear();\n // memoryStore has private map; reset via assignment.\n // biome-ignore lint/suspicious/noExplicitAny: test-only seam\n (memoryStore as any).map.clear();\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ConfigurationError } from './chunk-
|
|
2
|
-
import { diag } from './chunk-
|
|
1
|
+
import { ConfigurationError } from './chunk-IDCKSLYH.js';
|
|
2
|
+
import { diag } from './chunk-T7O6K6PX.js';
|
|
3
3
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
4
4
|
import { existsSync } from 'fs';
|
|
5
5
|
import { readFile } from 'fs/promises';
|
|
@@ -131,5 +131,5 @@ function warnPersonalitySwitchInsideFork(agentId) {
|
|
|
131
131
|
}
|
|
132
132
|
|
|
133
133
|
export { currentPersonalityContext, loadHookConfig, warnOnce, warnPersonalitySwitchInsideFork, withPersonalityContext };
|
|
134
|
-
//# sourceMappingURL=chunk-
|
|
135
|
-
//# sourceMappingURL=chunk-
|
|
134
|
+
//# sourceMappingURL=chunk-YMA4S2WO.js.map
|
|
135
|
+
//# sourceMappingURL=chunk-YMA4S2WO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":[],"mappings":";;;;;;;AAiCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AAYA,IAAM,MAAA,uBAAa,GAAA,EAAY;AAYxB,SAAS,QAAA,CAAS,KAAa,OAAA,EAAuB;AAC3D,EAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG;AACrB,EAAA,MAAA,CAAO,IAAI,GAAG,CAAA;AACd,EAAA,IAAA,CAAK,GAAG,OAAO;AAAA,CAAI,CAAA;AACrB;AAcA,eAAsB,eAAe,GAAA,EAAkC;AACrE,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,EAAK,UAAA,EAAY,YAAY,CAAA;AAEnD,EAAA,IAAI,CAAC,UAAA,CAAW,QAAQ,CAAA,EAAG;AACzB,IAAA,IAAI,WAAW,IAAA,CAAK,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AAA,EACH;AACA,EAAA,MAAM,EAAA,GAAkB,EAAE,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ;AAC/C,EAAA,IAAI,OAAA,KAAY,MAAA,EAAW,EAAA,CAAG,OAAA,GAAU,OAAA;AACxC,EAAA,IAAI,OAAO,GAAA,CAAI,OAAA,KAAY,QAAA,IAAY,GAAA,CAAI,UAAU,CAAA,EAAG;AACtD,IAAA,EAAA,CAAG,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,UAAU,GAAI,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,EAAA;AACT;;;ACrKA,IAAM,OAAA,GAAU,IAAI,iBAAA,EAA0C;AAQvD,SAAS,sBAAA,CACd,KACA,EAAA,EACY;AACZ,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAQO,SAAS,yBAAA,GAAgE;AAC9E,EAAA,OAAO,QAAQ,QAAA,EAAS;AAC1B;AASO,SAAS,gCAAgC,OAAA,EAAuB;AACrE,EAAA,QAAA;AAAA,IACE,8BAA8B,OAAO,CAAA,CAAA;AAAA,IACrC,CAAA,0IAAA;AAAA,GACF;AACF","file":"chunk-PGP7IOJ2.js","sourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(cwd: string): Promise<HookConfig> {\n const jsonPath = join(cwd, \".theokit\", \"hooks.json\");\n\n if (!existsSync(jsonPath)) {\n if (existsSync(join(cwd, \".theokit\", \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return {};\n }\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/** Narrow an unknown to a record, or throw a typed config error. */\nfunction asRecord(value: unknown, path: string, where: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value as Record<string, unknown>;\n}\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":[],"mappings":";;;;;;;AAiCA,IAAM,qBAAA,GAA6D;AAAA,EACjE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAA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ourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config shape (identical to Claude Code's `settings.json` hooks):\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag } from \"../../diagnostics.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * Claude Code event name → the SDK firing event. Only events the runtime\n * genuinely emits are mapped; a Claude Code event with no SDK firing point\n * (SessionStart / SubagentStop / PreCompact / Notification / SessionEnd) is\n * skipped with a warn rather than silently accepted (it would never run).\n */\nconst CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(cwd: string): Promise<HookConfig> {\n const jsonPath = join(cwd, \".theokit\", \"hooks.json\");\n\n if (!existsSync(jsonPath)) {\n if (existsSync(join(cwd, \".theokit\", \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return {};\n }\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/** Narrow an unknown to a record, or throw a typed config error. */\nfunction asRecord(value: unknown, path: string, where: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an object at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value as Record<string, unknown>;\n}\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n warnOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n const hc: HookCommand = { command: cmd.command };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
5
|
-
var
|
|
3
|
+
var chunk4I55V454_cjs = require('./chunk-4I55V454.cjs');
|
|
4
|
+
var chunkJHPGF3FP_cjs = require('./chunk-JHPGF3FP.cjs');
|
|
5
|
+
var chunk2ADR2GSO_cjs = require('./chunk-2ADR2GSO.cjs');
|
|
6
6
|
var promises = require('fs/promises');
|
|
7
7
|
var path = require('path');
|
|
8
8
|
|
|
@@ -13,7 +13,7 @@ async function acquireShared(path) {
|
|
|
13
13
|
existing.refs++;
|
|
14
14
|
return createProxy(path);
|
|
15
15
|
}
|
|
16
|
-
const lease = await
|
|
16
|
+
const lease = await chunk4I55V454_cjs.acquireSessionWriter(path);
|
|
17
17
|
sharedLeases.set(path, { lease, refs: 1 });
|
|
18
18
|
return createProxy(path);
|
|
19
19
|
}
|
|
@@ -50,14 +50,14 @@ var FsSessionStore = class {
|
|
|
50
50
|
this.#cwd = options.cwd;
|
|
51
51
|
}
|
|
52
52
|
async readRecords(agentId) {
|
|
53
|
-
return
|
|
53
|
+
return chunkJHPGF3FP_cjs.readTranscript(chunkJHPGF3FP_cjs.transcriptPath(this.#baseDir, this.#cwd, agentId));
|
|
54
54
|
}
|
|
55
55
|
async appendRecords(agentId, records) {
|
|
56
56
|
if (records.length === 0) return;
|
|
57
|
-
const path$1 =
|
|
57
|
+
const path$1 = chunkJHPGF3FP_cjs.transcriptPath(this.#baseDir, this.#cwd, agentId);
|
|
58
58
|
await promises.mkdir(path.dirname(path$1), { recursive: true });
|
|
59
|
-
await
|
|
60
|
-
for (const record of records)
|
|
59
|
+
await chunk2ADR2GSO_cjs.withFileLock(path$1, async () => {
|
|
60
|
+
for (const record of records) chunk2ADR2GSO_cjs.appendJsonl(path$1, record);
|
|
61
61
|
});
|
|
62
62
|
}
|
|
63
63
|
/**
|
|
@@ -76,7 +76,7 @@ var FsSessionStore = class {
|
|
|
76
76
|
*/
|
|
77
77
|
async acquire(agentId) {
|
|
78
78
|
if (this.#leases.has(agentId)) return;
|
|
79
|
-
const path$1 =
|
|
79
|
+
const path$1 = chunkJHPGF3FP_cjs.transcriptPath(this.#baseDir, this.#cwd, agentId);
|
|
80
80
|
await promises.mkdir(path.dirname(path$1), { recursive: true });
|
|
81
81
|
this.#leases.set(agentId, await acquireShared(path$1));
|
|
82
82
|
}
|
|
@@ -108,5 +108,5 @@ var FsSessionStore = class {
|
|
|
108
108
|
};
|
|
109
109
|
|
|
110
110
|
exports.FsSessionStore = FsSessionStore;
|
|
111
|
-
//# sourceMappingURL=chunk-
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
111
|
+
//# sourceMappingURL=chunk-YPJ5NH5N.cjs.map
|
|
112
|
+
//# sourceMappingURL=chunk-YPJ5NH5N.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":["acquireSessionWriter","readTranscript","transcriptPath","path","mkdir","dirname","withFileLock","appendJsonl"],"mappings":";;;;;;;;AAqDA,IAAM,YAAA,uBAAmB,GAAA,EAAyD;AAElF,eAAe,cAAc,IAAA,EAA2C;AACtE,EAAA,MAAM,QAAA,GAAW,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA;AACtC,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,QAAA,CAAS,IAAA,EAAA;AACT,IAAA,OAAO,YAAY,IAAI,CAAA;AAAA,EACzB;AACA,EAAA,MAAM,KAAA,GAAQ,MAAMA,sCAAA,CAAqB,IAAI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AAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,SAAS,CAAC,GAAG,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA;AACxC,IAAA,IAAA,CAAK,QAAQ,KAAA,EAAM;AACnB,IAAA,KAAA,MAAW,KAAA,IAAS,MAAA,EAAQ,MAAM,KAAA,CAAM,OAAA,EAAQ;AAAA,EAClD;AACF","file":"chunk-YPJ5NH5N.cjs","sourcesContent":["/**\n * SE41 — `FsSessionStore`, the DEFAULT reference implementation of the pluggable\n * {@link SessionStore} seam. It reads and append-writes the native Claude-shaped\n * `.jsonl` transcript at `<baseDir>/projects/<encoded-cwd>/<agentId>.jsonl` — the\n * exact on-disk format SE40 introduced (the file the Claude Code CLI can\n * `--continue`). Omitting `local.sessionStore` resolves to this store, so the\n * default persistence path is byte-identical to SE40 behavior.\n *\n * `readRecords` is `readTranscript(transcriptPath(...))` (a missing session →\n * `[]`, not an error — a fresh agent has no history). `appendRecords` is a TRUE\n * append: it reads the prior records, concatenates the new-turn delta, and\n * rewrites the whole line set atomically under the SE40 cross-process file lock\n * (`writeTranscript` never shrinks — the native format is an append-only\n * `parentUuid` DAG). The parent dir is created BEFORE acquiring the lock because\n * the lock's companion `<path>.lock` file needs an existing parent dir (the SE40\n * `mkdir(dirname)`-before-lock fix).\n *\n * @internal\n */\n\nimport { mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { withFileLock } from \"./file-lock.js\";\nimport { appendJsonl } from \"./jsonl.js\";\nimport { readTranscript, type SessionRecord, transcriptPath } from \"./session-transcript.js\";\nimport { acquireSessionWriter, type SessionWriterLease } from \"./session-writer.js\";\n\n/** Options identifying the on-disk transcript location for the FS default store. */\nexport interface FsSessionStoreOptions {\n /** Transcript base dir (`~/.theokit` default, `~/.claude` for CLI interop) — already `~`-expanded. */\n baseDir: string;\n /** The workspace cwd whose encoded form is the transcript project dir. */\n cwd: string;\n}\n\n/**\n * Reference-counted leases, shared per path.\n *\n * `acquireSessionWriter` is STRICT on purpose: two concurrent acquisitions of the same path, and\n * exactly one wins — \"a lease that let both through would be decorative\" (the M81 test says exactly\n * that, and it is right). That is the primitive's contract, and it does not change.\n *\n * But within ONE process it is normal to have more than one store over the same session: the golden\n * compaction tests and the concurrent-send tests do exactly that, and they record real runtime\n * behavior. Applying the raw primitive there would turn a legitimate pattern into a\n * `SessionBusyError`.\n *\n * The reconciliation belongs here, in the primitive's consumer: the process takes ONE lease per path\n * and counts how many stores use it. The last to release actually frees it. Cross-process stays\n * strict — which is the problem M81 states (\"`exec resume --last` can write into the TUI's live\n * session\").\n */\nconst sharedLeases = new Map<string, { lease: SessionWriterLease; refs: number }>();\n\nasync function acquireShared(path: string): Promise<SessionWriterLease> {\n const existing = sharedLeases.get(path);\n if (existing !== undefined) {\n existing.refs++;\n return createProxy(path);\n }\n const lease = await acquireSessionWriter(path);\n sharedLeases.set(path, { lease, refs: 1 });\n return createProxy(path);\n}\n\n/** A handle that decrements the count; the last to release frees the real lease. */\nfunction createProxy(path: string): SessionWriterLease {\n let released = false;\n return {\n sessionPath: path,\n // The proxy forwards the renewal to the ONE real lease this path shares. Renewing through any\n // holder is correct and is the point: the record must say \"someone in this process is still\n // writing\", and the refcount already guarantees they are all the same owner.\n renew: (): void => {\n if (released) return;\n sharedLeases.get(path)?.lease.renew();\n },\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n const entry = sharedLeases.get(path);\n if (entry === undefined) return;\n entry.refs--;\n if (entry.refs > 0) return;\n sharedLeases.delete(path);\n await entry.lease.release();\n },\n };\n}\n\n/**\n * The default `SessionStore` — reads/append-writes the native `.jsonl` transcript.\n */\nexport class FsSessionStore implements SessionStore {\n readonly #baseDir: string;\n readonly #cwd: string;\n /** One lease per `agentId` — a store serves more than one session over the process lifetime. */\n readonly #leases = new Map<string, SessionWriterLease>();\n\n constructor(options: FsSessionStoreOptions) {\n this.#baseDir = options.baseDir;\n this.#cwd = options.cwd;\n }\n\n async readRecords(agentId: string): Promise<SessionRecord[]> {\n return readTranscript(transcriptPath(this.#baseDir, this.#cwd, agentId));\n }\n\n async appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void> {\n // Empty delta → nothing to persist (avoids an unnecessary lock + rewrite).\n if (records.length === 0) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n // mkdir BEFORE the lock: withFileLock's companion `<path>.lock` needs the parent dir.\n await mkdir(dirname(path), { recursive: true });\n\n await withFileLock(path, async () => {\n // M93 — appends the DELTA instead of rewriting the whole file.\n //\n // Before: `readTranscript` + `writeTranscript` of everything, per turn. O(n) of I/O **and** of\n // parsing on every turn, O(n^2) per session — the consumer note in\n // `agents/lib/session/backtrack.ts` records 1.4 MB / 3000 lines over 200 turns.\n //\n // Correct because the format **is already append-only**: the `parentUuid` DAG does not depend\n // on line order, and every record carries its own parent. `appendJsonl` **already existed in\n // the package** and had a single caller (`eval/runner.ts`) — the primitive was there, it was\n // the store that ignored it (rung 4).\n //\n // `withFileLock` stays — but the earlier claim that \"it is what serializes two concurrent\n // `appendRecords`\" was too strong, and M93's adversarial review measured it: removing it fails\n // no test. The reason is the paragraph above — the `parentUuid` DAG does not depend on line\n // order, so two interleaved batches reconstruct identically. The work the lock was doing\n // (protecting a read-modify-write) disappeared along with the rewrite.\n //\n // What it still covers is the TOCTOU window in `needsLineBreakBefore` (read the last byte,\n // then write): without it, two processes can both conclude \"a \\n is missing\" and produce a\n // blank line — which the reader discards, i.e. benign. It stays as a **declared, not\n // mechanized** defense (the discipline in `error-handling.md` § 4: enumerate the residue\n // rather than let a missing test pass for coverage).\n //\n // `writeTranscript` still exists for **compaction**, the one operation that legitimately\n // rewrites the file.\n for (const record of records) appendJsonl(path, record);\n });\n }\n\n /**\n * Takes the session's writer lease. Throws `SessionBusyError` when another process holds it.\n *\n * **Explicit, and NOT inside `appendRecords`** — M95's adversarial review measured why that\n * matters: the `SessionStore` contract states that \"an `appendRecords` rejection is logged to\n * stderr, NOT thrown to the caller (best-effort write)\". Acquiring there made the\n * `SessionBusyError` get **swallowed**, and the result was worse than the original problem:\n * instead of two writers interleaving lines, the loser **lost the turn silently** — nothing on\n * disk, a stderr warning invisible under the TUI, and no way for the caller to react.\n *\n * At init the error reaches someone who can act: `exec` forks to a new id, which is exactly what\n * the error message itself prescribes. It is the difference between failing where a decision is\n * possible and failing where only loss is.\n */\n async acquire(agentId: string): Promise<void> {\n if (this.#leases.has(agentId)) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n await mkdir(dirname(path), { recursive: true });\n this.#leases.set(agentId, await acquireShared(path));\n }\n\n /**\n * Releases ONE agent's lease.\n *\n * It exists because `dispose()` releases **every** lease the store holds, and a store injected by\n * the consumer may serve several agents: an init that fails for agent B must not free agent A's\n * lease, which is still live and writing.\n */\n async release(agentId: string): Promise<void> {\n const lease = this.#leases.get(agentId);\n if (lease === undefined) return;\n this.#leases.delete(agentId);\n await lease.release();\n }\n\n /**\n * Releases every lease this store holds.\n *\n * Without it the `.writer.lock` outlives the process and the next open would have to wait out the\n * heartbeat window — recoverable, but 30 s of waiting after a CLEAN shutdown would be an avoidable\n * defect. Idempotent: calling it twice is not an error.\n */\n async dispose(): Promise<void> {\n const leases = [...this.#leases.values()];\n this.#leases.clear();\n for (const lease of leases) await lease.release();\n }\n}\n"]}
|
|
@@ -16,5 +16,5 @@ function withCwdMutex(key, fn) {
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
exports.withCwdMutex = withCwdMutex;
|
|
19
|
-
//# sourceMappingURL=chunk-
|
|
20
|
-
//# sourceMappingURL=chunk-
|
|
19
|
+
//# sourceMappingURL=chunk-ZF2LDKQQ.cjs.map
|
|
20
|
+
//# sourceMappingURL=chunk-ZF2LDKQQ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/cwd-mutex.ts"],"names":[],"mappings":";;;AAIA,IAAM,KAAA,uBAAY,GAAA,EAA8B;AAoCzC,SAAS,YAAA,CAAgB,KAAa,EAAA,EAAkC;AAC7E,EAAA,MAAM,OAAO,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AAC/C,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,EAAA,EAAI,EAAE,CAAA;AAG7B,EAAA,KAAA,CAAM,GAAA;AAAA,IACJ,GAAA;AAAA,IACA,IAAA,CAAK,IAAA;AAAA,MACH,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-ZF2LDKQQ.cjs","sourcesContent":["// Tail of the queue per key. Module-scoped on purpose — see `withCwdMutex` below, which is where\n// the contract is documented. Entries are never removed, so the Map holds one promise per distinct\n// key for the life of the process; keys are expected to come from a bounded set (a file path, a\n// subsystem name), not from unbounded user input.\nconst tails = new Map<string, Promise<unknown>>();\n\n/**\n * Run `fn` after every earlier `withCwdMutex` call for the same `key` has settled, and return\n * what `fn` returns.\n *\n * Calls with the same key run strictly in the order they were made — FIFO, never concurrent.\n * Calls with different keys never wait on each other. The key is an opaque string: two callers\n * serialize against each other exactly when they pass equal keys, so a shared key IS the\n * contract, and a mismatched one silently buys no protection at all.\n *\n * A rejection does not poison the queue. The next waiter runs whether the previous `fn` fulfilled\n * or rejected, and the rejection is delivered only to the caller whose `fn` threw. This function\n * neither retries nor swallows: the returned promise rejects with whatever `fn` rejected with.\n *\n * There is no timeout and no cancellation. An `fn` that never settles blocks that key for the\n * lifetime of the process.\n *\n * **Scope — this is an in-process lock only.** State is a module-scoped Map, so it serializes\n * callers that share one module instance and nothing else. Two processes, two worker threads, or\n * two copies of the SDK resolved into the same tree do not see each other's queue. When the\n * resource is a file that other processes can also write, use `withFileLock` from\n * `./file-lock.ts` instead — it takes an OS-level lock and layers this mutex underneath, so it\n * gives both guarantees. Reach for `withCwdMutex` directly when the shared state is in memory, or\n * when the file is one only this process touches.\n *\n * Extracted packages (`@theokit/sdk-budget`, `@theokit/sdk-memory`) import this from\n * `@theokit/sdk` rather than reimplementing it, precisely so the Map is the same one: a per-package\n * copy would give each package its own queue and let their writes race.\n *\n * The Map is module-scoped, so nothing survives a process restart or a fresh module instance, and\n * its entries are never removed — pass keys from a bounded set rather than from arbitrary input.\n * Signature and semantics will not change before sdk-core v3.0.\n *\n * @public\n */\nexport function withCwdMutex<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = tails.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn); // run fn whether prev fulfilled or rejected\n // Save the new tail. Store the .then() chain that swallows the result so a\n // failure here doesn't poison subsequent waiters.\n tails.set(\n key,\n next.then(\n () => undefined,\n () => undefined,\n ),\n );\n return next;\n}\n"]}
|
|
@@ -130,5 +130,5 @@ exports.findGitRoot = findGitRoot;
|
|
|
130
130
|
exports.isSafePattern = isSafePattern;
|
|
131
131
|
exports.walkUpForFile = walkUpForFile;
|
|
132
132
|
exports.walkUpForGlob = walkUpForGlob;
|
|
133
|
-
//# sourceMappingURL=chunk-
|
|
134
|
-
//# sourceMappingURL=chunk-
|
|
133
|
+
//# sourceMappingURL=chunk-ZNW6V4Y6.cjs.map
|
|
134
|
+
//# sourceMappingURL=chunk-ZNW6V4Y6.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/context/context-discovery.ts"],"names":["isAbsolute","resolve","existsSync","join","dirname","realpathSync","glob"],"mappings":";;;;;;;AAsFO,IAAM,uBAAA,GAAwD;AAAA,EACnE;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,KAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,E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GAAI,CAAE,CAAA;AAC1D","file":"chunk-ZNW6V4Y6.cjs","sourcesContent":["/**\n * Context file discovery (T1.1, ADRs D150 / D151).\n *\n * Discovers context files via three scopes:\n * - `cwd-only` — single dir, single path lookup\n * - `git-root-walk` — walk cwd → git-root, collect every directory's match\n * (nearest-first ordering)\n * - `globbed` — glob pattern relative to cwd (e.g. `.cursor/rules/*.mdc`)\n *\n * Pure `existsSync` checks — **no `.gitignore` parsing** (EC-A, KISS) and\n * **no invented `.theokitignore`** (EC-B). Paths normalized via\n * `realpath` to dedup symlink chains pointing to the same physical file\n * (EC-F). Git worktrees work transparently because `.git` exists as a\n * file in that case (EC-N).\n *\n * @internal\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { glob } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\n/** Single filename (\"AGENTS.md\") or relative glob (\".cursor/rules/*.mdc\"). */\nexport type DiscoveryScope = \"cwd-only\" | \"git-root-walk\" | \"globbed\";\n\n/** Parser to apply once file is read. */\nexport type DiscoveryParser = \"plain-markdown\" | \"mdc\" | \"frontmatter-zod\" | \"rules-frontmatter\";\n\n/**\n * One kind of context file the runner knows how to find and read. The shipped registry is\n * `DEFAULT_DISCOVERY_SPECS`; a caller supplies its own array to change the set.\n *\n * `scope` decides how `pattern` is used and how many files a single spec can yield:\n * `cwd-only` looks for one path and stops, `git-root-walk` collects a match in every directory\n * from `cwd` up to the git root (nearest first), and `globbed` expands `pattern` as a glob\n * relative to `cwd`. So `pattern` is a filename for the first two and a glob for the third —\n * putting a glob on a walk scope silently finds nothing.\n *\n * `priority` orders the merged prompt, ascending, and is a plain number rather than an index, so\n * a new spec can be slotted between two existing ones. Lower means earlier and therefore more\n * general; later content wins on conflict.\n *\n * `parser` must match the file format — `plain-markdown` reads the whole file, `mdc` and\n * `rules-frontmatter` parse frontmatter and can DECLINE the file when its activation conditions\n * do not hold, and `frontmatter-zod` is the legacy path the runner currently skips entirely.\n *\n * `followImports` is honored only by `plain-markdown`, and turns `@path` directives in the body\n * into inlined content bounded by the import root. Setting it on a frontmatter parser does\n * nothing.\n *\n * `id` names the source in `<source name=\"\">` and in telemetry. When one spec matches files in\n * several directories, the runner suffixes it with the path relative to the git root to keep them\n * apart.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport interface DiscoverySpec {\n /** Stable identifier — used as `<source name=\"\">` and telemetry key. */\n readonly id: string;\n /** Priority for merge (lower = earlier in prompt). */\n readonly priority: number;\n /** Filename (cwd-only/git-root-walk) or glob (globbed). */\n readonly pattern: string;\n readonly scope: DiscoveryScope;\n readonly parser: DiscoveryParser;\n /** Whether to follow `@path` import directives (CLAUDE.md / GEMINI.md). */\n readonly followImports: boolean;\n}\n\n/**\n * The context files theokit looks for out of the box, in the order they are concatenated.\n *\n * Two things follow from the ordering. `AGENTS.md` comes first at priority 10 and `THEO.md` last,\n * so theokit-specific instruction wins over the vendor-neutral file on conflict. And the array is\n * consumed in the order written — the runner does not re-sort it — so a caller passing its own\n * array is responsible for keeping `priority` and array position consistent.\n *\n * `CLAUDE.md` and `GEMINI.md` are the only two entries with `followImports: true`, which means\n * they are the only files whose `@path` directives pull other files into the prompt. Those\n * imports cannot escape the import root.\n *\n * Frozen only by type: `ReadonlyArray` is a compile-time constraint, and the array and its\n * elements are not deep-frozen at runtime. Build a new array rather than mutating this one.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport const DEFAULT_DISCOVERY_SPECS: ReadonlyArray<DiscoverySpec> = [\n {\n id: \"AGENTS.md\",\n pattern: \"AGENTS.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 10,\n },\n {\n id: \"GEMINI.md\",\n pattern: \"GEMINI.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 20,\n },\n {\n id: \"CLAUDE.md\",\n pattern: \"CLAUDE.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 30,\n },\n {\n id: \"cursor-rules\",\n pattern: \".cursor/rules/*.mdc\",\n scope: \"globbed\",\n parser: \"mdc\",\n followImports: false,\n priority: 40,\n },\n {\n id: \"theokit-rules\",\n pattern: \".theokit/rules/*.md\",\n scope: \"globbed\",\n parser: \"rules-frontmatter\",\n followImports: false,\n priority: 45,\n },\n {\n id: \"theokit-context\",\n pattern: \".theokit/context/*.md\",\n scope: \"globbed\",\n parser: \"frontmatter-zod\",\n followImports: false,\n priority: 50,\n },\n {\n id: \"THEO.md\",\n pattern: \".theokit/THEO.md\",\n scope: \"cwd-only\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 60,\n },\n];\n\nconst SAFE_FILENAME = /^[a-zA-Z0-9_.\\-/*]+$/;\nconst TRAVERSAL_RE = /(^|\\/)\\.\\.(\\/|$)/;\n\n/**\n * Reject patterns that contain path traversal (`..`) or non-allowed\n * characters (D81 parity, EC-4).\n *\n * @internal\n */\nexport function isSafePattern(pattern: string): boolean {\n if (typeof pattern !== \"string\" || pattern.length === 0) return false;\n if (TRAVERSAL_RE.test(pattern)) return false;\n if (isAbsolute(pattern)) return false;\n return SAFE_FILENAME.test(pattern);\n}\n\n/**\n * Walk upward from `cwd` looking for the closest directory containing\n * a `.git` entry (file OR directory — worktrees use a `.git` FILE,\n * EC-N). Returns the absolute path of that directory, or `undefined`\n * when no git root exists at or above `cwd`.\n *\n * @internal\n */\nexport function findGitRoot(cwd: string): string | undefined {\n if (typeof cwd !== \"string\" || cwd.length === 0) return undefined;\n let current = resolve(cwd);\n // Guard against infinite loops on weird filesystems.\n for (let i = 0; i < 64; i += 1) {\n if (existsSync(join(current, \".git\"))) return current;\n const parent = dirname(current);\n if (parent === current) return undefined;\n current = parent;\n }\n return undefined;\n}\n\n/**\n * Walk `cwd` upward to `stopDir` (inclusive) collecting every existing\n * occurrence of `filename`. Returns absolute, realpath-deduped paths in\n * nearest-first order (innermost dir first).\n *\n * No `.gitignore` parsing (EC-A). Realpath collapses symlink chains\n * pointing to the same physical file (EC-F). Filesystem races (file\n * deleted mid-walk) are skipped silently (EC-5).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: walk-up loop combines validation + realpath dedup + FS-race handling + stopDir guard in a single bounded loop; splitting fragments the dedup invariant.\nexport function walkUpForFile(\n cwd: string,\n filename: string,\n stopDir: string | undefined,\n): string[] {\n if (!isSafePattern(filename)) {\n return [];\n }\n const start = resolve(cwd);\n const stop = stopDir !== undefined ? resolve(stopDir) : undefined;\n const found: string[] = [];\n const seenReal = new Set<string>();\n let current = start;\n // 64-level depth cap.\n for (let i = 0; i < 64; i += 1) {\n const candidate = join(current, filename);\n if (existsSync(candidate)) {\n let real: string;\n try {\n real = realpathSync(candidate);\n } catch {\n // FS race (deleted mid-walk) — skip.\n real = candidate;\n }\n if (!seenReal.has(real)) {\n seenReal.add(real);\n found.push(real);\n }\n }\n if (stop !== undefined && current === stop) break;\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return found;\n}\n\n/**\n * Glob-style discovery under `cwd` (e.g. `.cursor/rules/*.mdc`, `.theokit/rules/**\\/*.md`).\n * Returns absolute, lex-sorted paths.\n *\n * `*` matches within one path segment and `**` spans any depth, including zero — so\n * `.theokit/rules/**\\/*.md` finds `rules/top.md` as well as `rules/deep/nested/inner.md`, while\n * `.theokit/rules/*.md` keeps its flat meaning and finds only the first. That distinction is the\n * compatibility contract: every existing spec uses a single `*`, and widening it would silently\n * start absorbing nested files nobody chose to expose.\n *\n * ## Why this used to be flat, and what changed (B-119)\n *\n * The previous implementation split the pattern at its LAST `/`, treated the prefix as a literal\n * directory and did one `readdir` — documented as \"nested directories deferred to v2\" (EC-R). The\n * deferral was deliberate; what made it a defect was measured from a consumer. TheoCode's own rule\n * loader descends recursively, so migrating it onto the `theokit-rules` spec would have silently\n * dropped every nested rule — on the path that decides whether a repository's hooks execute. And a\n * pattern written to say so, `.theokit/rules/**\\/*.md`, resolved its directory part to a literal\n * `**` and matched NOTHING, not even the top-level file it matched before the globstar was added.\n *\n * ## Why the stdlib rather than a walker\n *\n * `fs.promises.glob` (Node ≥ 22, and this package requires ≥ 22.12) implements exactly these\n * semantics, verified against a fixture before adoption: `**\\/*.md` returns all three depths,\n * `*.md` returns one, and it emits no experimental warning. Writing a recursive walker here would\n * have been a third implementation of matching inside one package — the same duplication that let\n * the enumerator and the compiler in `context-glob.ts` disagree in the first place. `globToRegex`\n * stays where it belongs: deciding whether a rule APPLIES to a set of paths, which is a different\n * question from which files exist.\n *\n * `isSafePattern` still runs first and is unchanged, so `..` is refused before any I/O.\n *\n * @internal\n */\nexport async function walkUpForGlob(cwd: string, pattern: string): Promise<string[]> {\n if (!isSafePattern(pattern)) return [];\n const found: string[] = [];\n try {\n for await (const entry of glob(pattern, { cwd })) {\n found.push(resolve(cwd, entry));\n }\n } catch {\n // A pattern whose directory does not exist is the ordinary case — most projects have no\n // `.cursor/rules/`. Same outcome as matching nothing.\n return [];\n }\n // Sorted, because discovery order becomes prompt order and must not vary with the filesystem.\n //\n // The comparator is explicit and deliberately NOT `localeCompare`, which is the usual suggestion\n // for a bare `.sort()`. `localeCompare` orders by the machine's locale, so the same tree would\n // assemble a different prompt on a differently-configured machine — trading one source of\n // non-determinism for a subtler one. Code-unit ordering is what a bare `.sort()` already does for\n // strings; writing it out states the intent and keeps the result machine-independent.\n return found.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n"]}
|